Repository: fanenr/flutter-chatbot Branch: master Commit: b2508200fc4c Files: 77 Total size: 378.0 KB Directory structure: gitextract_khs2npmo/ ├── .github/ │ └── workflows/ │ └── build.yaml ├── .gitignore ├── .metadata ├── CHANGELOG ├── COPYING ├── README ├── analysis_options.yaml ├── android/ │ ├── .gitignore │ ├── app/ │ │ ├── build.gradle │ │ └── src/ │ │ ├── debug/ │ │ │ └── AndroidManifest.xml │ │ ├── main/ │ │ │ ├── AndroidManifest.xml │ │ │ ├── kotlin/ │ │ │ │ └── cc/ │ │ │ │ └── arthur63/ │ │ │ │ └── chatbot/ │ │ │ │ └── MainActivity.kt │ │ │ └── res/ │ │ │ ├── drawable-v21/ │ │ │ │ └── launch_background.xml │ │ │ ├── values/ │ │ │ │ └── styles.xml │ │ │ └── values-night/ │ │ │ └── styles.xml │ │ └── profile/ │ │ └── AndroidManifest.xml │ ├── build.gradle │ ├── gradle/ │ │ └── wrapper/ │ │ └── gradle-wrapper.properties │ ├── gradle.properties │ └── settings.gradle ├── lib/ │ ├── chat/ │ │ ├── chat.dart │ │ ├── current.dart │ │ ├── input.dart │ │ ├── message.dart │ │ └── settings.dart │ ├── config.dart │ ├── gen/ │ │ ├── intl/ │ │ │ ├── messages_all.dart │ │ │ ├── messages_en.dart │ │ │ └── messages_zh_CN.dart │ │ └── l10n.dart │ ├── image/ │ │ ├── config.dart │ │ ├── generate.dart │ │ └── image.dart │ ├── l10n/ │ │ ├── intl_en.arb │ │ └── intl_zh_CN.arb │ ├── llm/ │ │ ├── llm.dart │ │ └── web.dart │ ├── main.dart │ ├── markdown/ │ │ ├── code.dart │ │ ├── latex.dart │ │ └── util.dart │ ├── settings/ │ │ ├── api.dart │ │ ├── bot.dart │ │ ├── config.dart │ │ └── settings.dart │ ├── util.dart │ └── workspace/ │ ├── document.dart │ ├── model.dart │ ├── task.dart │ └── workspace.dart ├── linux/ │ ├── .gitignore │ ├── CMakeLists.txt │ ├── flutter/ │ │ ├── CMakeLists.txt │ │ ├── generated_plugin_registrant.cc │ │ ├── generated_plugin_registrant.h │ │ └── generated_plugins.cmake │ ├── main.cc │ ├── my_application.cc │ └── my_application.h ├── pubspec.yaml └── windows/ ├── .gitignore ├── CMakeLists.txt ├── flutter/ │ ├── CMakeLists.txt │ ├── generated_plugin_registrant.cc │ ├── generated_plugin_registrant.h │ └── generated_plugins.cmake └── runner/ ├── CMakeLists.txt ├── Runner.rc ├── flutter_window.cpp ├── flutter_window.h ├── main.cpp ├── resource.h ├── runner.exe.manifest ├── utils.cpp ├── utils.h ├── win32_window.cpp └── win32_window.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/build.yaml ================================================ name: Build and Release on: push: tags: - "v*" permissions: contents: write jobs: build-apk: runs-on: ubuntu-latest steps: - name: Clone repository uses: actions/checkout@v4 with: fetch-depth: 0 - name: Setup JDK17 uses: actions/setup-java@v4 with: distribution: "zulu" java-version: "17" - name: Setup Flutter uses: subosito/flutter-action@v2 with: flutter-version: 3.24.5 - name: Setup signing run: | echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 --decode > android/app/keystore.jks echo "storePassword=${{ secrets.KEYSTORE_PASSWORD }}" > android/key.properties echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/key.properties echo "keyAlias=${{ secrets.KEY_ALIAS }}" >> android/key.properties echo "storeFile=keystore.jks" >> android/key.properties - name: Build run: | flutter pub get flutter build apk --split-per-abi - name: ChangeLog id: changelog run: | echo "latest<> $GITHUB_OUTPUT awk '/^[0-9]/{i++}i==1' CHANGELOG | sed '${/^$/d}' >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - name: Release uses: softprops/action-gh-release@v2 with: files: | build/app/outputs/flutter-apk/app-arm64-v8a-release.apk build/app/outputs/flutter-apk/app-arm64-v8a-release.apk.sha1 build/app/outputs/flutter-apk/app-x86_64-release.apk build/app/outputs/flutter-apk/app-x86_64-release.apk.sha1 body: ${{ steps.changelog.outputs.latest }} ================================================ FILE: .gitignore ================================================ # Miscellaneous *.log *.pyc *.swp *.class .history .DS_Store .svn/ .atom/ .buildlog/ migrate_working_dir/ # IntelliJ related *.iml *.ipr *.iws .idea/ # Flutter/Dart/Pub related **/doc/api/ **/ios/Flutter/.last_build_id .flutter-plugins devtools_options.yaml .flutter-plugins-dependencies .pub/ /build/ .pub-cache/ .dart_tool/ # Obfuscation related app.*.map.json # Symbolication related app.*.symbols # Android Studio related /android/app/debug /android/app/profile /android/app/release ================================================ FILE: .metadata ================================================ # This file tracks properties of this Flutter project. # Used by Flutter tool to assess capabilities and perform upgrades etc. # # This file should be version controlled and should not be manually edited. version: revision: "dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668" channel: "stable" project_type: app # Tracks metadata for the flutter migrate command migration: platforms: - platform: root create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 - platform: linux create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 - platform: windows create_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 base_revision: dec2ee5c1f98f8e84a7d5380c05eb8a3d0a81668 # User provided section # List of Local paths (relative to this file) that should be # ignored by the migrate tool. # # Files that are not part of the templates will be ignored by default. unmanaged_files: - 'lib/main.dart' - 'ios/Runner.xcodeproj/project.pbxproj' ================================================ FILE: CHANGELOG ================================================ 0.3.5 (2025-01-10) * Add: General Web Search. * Improve: Additional page details. * 增加:通用联网搜索 * 改进:更多页面细节 0.3.4 (2025-01-02) * Improve: Chat Settings. * Improve: Model Settings. * Add: Data Clearing. * 改进:对话设置页面 * 改进:模型设置功能 * 增加:清除数据功能 0.3.3 (2024-12-27) * Improve: Chat Settings Page. * Improve: Input Widget. * 改进:对话设置页面 * 改进:输入组件 0.3.2 (2024-12-25) * Add: Title Generation. * Improve: Input Widget. * Fix: Google Gemini API proxy not working. * 增加:标题生成 * 改进:输入组件 * 修复:Google Gemini 接口代理无效。 0.3.1 (2024-12-17) * Add: Workspace. * Improve: Input Widget. * 增加:工作空间 * 改进:输入组件 0.2.10 (2024-12-13) * Add: Checking for updates. * Improve: Images display. * 增加:检查更新 * 改进:图片显示 0.2.9 (2024-12-13) * Add: Google Search support (gemini-2.0-flash-exp only) * Add: Support for sending multiple images. * 增加:支持 GoogleSearch(仅 gemini-2.0-flash-exp) * 增加:支持发送多张图片 0.2.8 (2024-12-09) * Add: Support Google Gemini API. * Improve: Chat Response. * 增加:支持 Google Gemini 接口 * 改进:对话响应 0.2.7 (2024-12-06) * Add: Export chat as image. * Improve: Refine UI details. * 增加:将对话导出为图片 * 改进:调整了界面细节 0.2.6 (2024-12-04) * Improve: LaTeX Rendering. * 改进:LaTeX 渲染 0.2.5 (2024-12-04) * Add: Image Generation. * Improve: Message List. * Improve: Configuration Loading and Export. * 增加:图像生成 * 改进:消息列表 * 改进:配置加载及导出 0.2.4 (2024-11-29) * Add: Image compression controls. * Improve: Redesigned settings page. * 增加:图片压缩控制 * 改进:重新设计的设置页 0.2.3 (2024-11-27) * Add: A new app icon. * Improve: Remove unnecessary animations. * 增加:新的应用图标 * 改进:删除不必要的动画 0.2.2 (2024-11-25) * Add: Chat clone and clear functionality. * Improve: More animations. * 增加:对话复制和清空 * 改进:更多动画 0.2.1 (2024-11-23) * Improve: The Reanswering can be stopped. * 改进:可以终止重新回答 0.2.0 (2024-11-23) * Add: Reanswer. * Improve: TTS button. * 增加:重新回答 * 改进:文本转语音按钮 0.1.11 (2024-11-22) * Add: More informative error messages. * Improve: Style of the Message Widget. * 增加:更多错误提示 * 改进:消息卡片组件样式 ================================================ FILE: COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README ================================================ This project is no longer maintained. ChatBot is licensed under the GNU General Public License v3.0 - see the COPYING file for details. ================================================ FILE: analysis_options.yaml ================================================ include: package:flutter_lints/flutter.yaml linter: rules: analyzer: plugins: ================================================ FILE: android/.gitignore ================================================ gradle-wrapper.jar /.gradle /captures/ /gradlew /gradlew.bat /local.properties GeneratedPluginRegistrant.java # Remember to never publicly share your keystore. # See https://flutter.dev/to/reference-keystore key.properties **/*.keystore **/*.jks ================================================ FILE: android/app/build.gradle ================================================ plugins { id "kotlin-android" id "com.android.application" id "dev.flutter.flutter-gradle-plugin" } def keystoreProperties = new Properties() def keystorePropertiesFile = rootProject.file("key.properties") if (keystorePropertiesFile.exists()) { keystoreProperties.load(new FileInputStream(keystorePropertiesFile)) } android { namespace = "cc.arthur63.chatbot" compileSdk = flutter.compileSdkVersion compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } kotlinOptions { jvmTarget = JavaVersion.VERSION_17 } defaultConfig { minSdk = flutter.minSdkVersion versionCode = flutter.versionCode versionName = flutter.versionName targetSdk = flutter.targetSdkVersion applicationId = "cc.arthur63.chatbot" } signingConfigs { release { keyAlias keystoreProperties["keyAlias"] keyPassword keystoreProperties["keyPassword"] storePassword keystoreProperties["storePassword"] storeFile keystoreProperties["storeFile"] ? file(keystoreProperties["storeFile"]) : null } } buildTypes { release { minifyEnabled true shrinkResources true signingConfig signingConfigs.release } } } flutter { source = "../.." } ================================================ FILE: android/app/src/debug/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/AndroidManifest.xml ================================================ ================================================ FILE: android/app/src/main/kotlin/cc/arthur63/chatbot/MainActivity.kt ================================================ package cc.arthur63.chatbot import io.flutter.embedding.android.FlutterActivity class MainActivity: FlutterActivity() ================================================ FILE: android/app/src/main/res/drawable-v21/launch_background.xml ================================================ ================================================ FILE: android/app/src/main/res/values/styles.xml ================================================ ================================================ FILE: android/app/src/main/res/values-night/styles.xml ================================================ ================================================ FILE: android/app/src/profile/AndroidManifest.xml ================================================ ================================================ FILE: android/build.gradle ================================================ allprojects { repositories { google() mavenCentral() } } rootProject.buildDir = "../build" subprojects { project.buildDir = "${rootProject.buildDir}/${project.name}" } subprojects { project.evaluationDependsOn(":app") } tasks.register("clean", Delete) { delete rootProject.buildDir } ================================================ FILE: android/gradle/wrapper/gradle-wrapper.properties ================================================ zipStorePath=wrapper/dists zipStoreBase=GRADLE_USER_HOME distributionPath=wrapper/dists distributionBase=GRADLE_USER_HOME distributionUrl=https\://services.gradle.org/distributions/gradle-8.4-all.zip ================================================ FILE: android/gradle.properties ================================================ android.useAndroidX=true android.enableJetifier=true org.gradle.daemon=false org.gradle.jvmargs=-Xmx2G -XX:MaxMetaspaceSize=1G ================================================ FILE: android/settings.gradle ================================================ pluginManagement { def flutterSdkPath = { def properties = new Properties() file("local.properties").withInputStream { properties.load(it) } def flutterSdkPath = properties.getProperty("flutter.sdk") assert flutterSdkPath != null, "flutter.sdk not set in local.properties" return flutterSdkPath }() includeBuild("$flutterSdkPath/packages/flutter_tools/gradle") repositories { google() mavenCentral() gradlePluginPortal() } } plugins { id "dev.flutter.flutter-plugin-loader" version "1.0.0" id "com.android.application" version "8.3.2" apply false id "org.jetbrains.kotlin.android" version "1.8.22" apply false } include ":app" ================================================ FILE: lib/chat/chat.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "input.dart"; import "message.dart"; import "current.dart"; import "settings.dart"; import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "../settings/api.dart"; import "dart:io"; import "package:flutter/material.dart"; import "package:screenshot/screenshot.dart"; import "package:animate_do/animate_do.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; final chatProvider = NotifierProvider.autoDispose(ChatNotifier.new); final chatsProvider = NotifierProvider.autoDispose(ChatsNotifier.new); final messagesProvider = NotifierProvider.autoDispose(MessagesNotifier.new); class ChatNotifier extends AutoDisposeNotifier { @override void build() => ref.listen(apisProvider, (p, n) => notify()); void notify() => ref.notifyListeners(); } class ChatsNotifier extends AutoDisposeNotifier { @override void build() {} void notify() => ref.notifyListeners(); } class MessagesNotifier extends AutoDisposeNotifier { @override void build() {} void notify() => ref.notifyListeners(); } class ChatPage extends ConsumerStatefulWidget { const ChatPage({super.key}); @override ConsumerState createState() => _ChatPageState(); } class _ChatPageState extends ConsumerState { final List _chats = Config.chats; final List _messages = Current.messages; final ScrollController _scrollCtrl = ScrollController(); @override void initState() { super.initState(); WidgetsBinding.instance.addPostFrameCallback((_) { Util.checkUpdate(context: context, notify: false); }); _scrollCtrl.addListener(() { final show = ref.read(_toBottomProvider); if (_scrollCtrl.position.pixels < 200) { if (show) ref.read(_toBottomProvider.notifier).hide(); } else { if (!show) ref.read(_toBottomProvider.notifier).show(); } }); } @override void dispose() { _scrollCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: _buildAppBar(), drawer: Drawer( shape: const RoundedRectangleBorder( borderRadius: BorderRadius.zero, ), child: SafeArea(child: _buildDrawer()), ), body: _buildBody(), ); } AppBar _buildAppBar() { return AppBar( title: Row( children: [ Flexible( child: Consumer( builder: (context, ref, child) { ref.watch(chatProvider); final id = Current.model; final config = Config.models[id]; return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( Current.title ?? S.of(context).new_chat, maxLines: 1, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.titleMedium, ), Text( config?.name ?? id ?? S.of(context).no_model, overflow: TextOverflow.ellipsis, style: Theme.of(context).textTheme.labelSmall, ) ], ); }, ), ), const SizedBox(width: 8), SizedBox.square( dimension: 32, child: IconButton( icon: const Icon(Icons.edit, size: 16), padding: EdgeInsets.zero, onPressed: () { InputWidget.unFocus(); showModalBottomSheet( context: context, useSafeArea: true, isScrollControlled: true, builder: (context) => Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), child: ChatSettings(), ), ); }, ), ), ], ), leading: Builder( builder: (context) => IconButton( icon: const Icon(Icons.menu), onPressed: () { InputWidget.unFocus(); Scaffold.of(context).openDrawer(); }, ), ), actions: [ PopupMenuButton( icon: const Icon(Icons.more_horiz), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(8)), ), onOpened: () => InputWidget.unFocus(), color: Theme.of(context).colorScheme.surfaceContainerLow, itemBuilder: (context) => [ PopupMenuItem( padding: EdgeInsets.zero, child: ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), leading: const Icon(Icons.file_copy, size: 20), title: Text(S.of(context).clone_chat), minTileHeight: 0, ), onTap: () { InputWidget.unFocus(); if (!Current.hasChat) return; Current.newChat(Current.title!); Current.save(); Util.showSnackBar( context: context, content: Text(S.of(context).cloned_successfully), ); ref.read(chatsProvider.notifier).notify(); }, ), PopupMenuItem( padding: EdgeInsets.zero, child: ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), leading: const Icon(Icons.delete, size: 24), title: Text(S.of(context).clear_chat), minTileHeight: 0, ), onTap: () async { InputWidget.unFocus(); if (_messages.isEmpty) return; final result = await showDialog( context: context, builder: (context) => AlertDialog( title: Text(S.of(context).clear_chat), content: Text(S.of(context).ensure_clear_chat), actions: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( onPressed: () => Navigator.of(context).pop(true), child: Text(S.of(context).clear), ), ], ), ); if (!(result ?? false)) return; _messages.clear(); Current.save(); ref.read(messagesProvider.notifier).notify(); }, ), PopupMenuItem( height: 1, padding: EdgeInsets.zero, child: const Divider(height: 1), ), PopupMenuItem( padding: EdgeInsets.zero, onTap: _exportChatAsImage, child: ListTile( contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 0), leading: const Icon(Icons.photo_library, size: 20), title: Text(S.of(context).export_chat_as_image), minTileHeight: 0, ), ), ], ), ], ); } Widget _buildDrawer() { return Column( children: [ ListTile( title: Text( "ChatBot", style: Theme.of(context).textTheme.titleLarge, ), trailing: IconButton( icon: const Icon(Icons.settings), onPressed: () => Navigator.of(context).pushNamed("/settings"), ), contentPadding: const EdgeInsets.only(left: 16, right: 8), ), Divider(), ListView( shrinkWrap: true, padding: EdgeInsets.only(left: 8, right: 8), children: [ ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).new_chat), leading: const Icon(Icons.article_outlined), onTap: () { if (Current.chatStatus.isResponding) return; Current.clear(); ref.read(chatProvider.notifier).notify(); ref.read(chatsProvider.notifier).notify(); ref.read(messagesProvider.notifier).notify(); }, ), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).workspace), leading: const Icon(Icons.workspaces_outlined), onTap: () => Navigator.of(context).pushNamed("/workspace"), ), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).image_generation), leading: const Icon(Icons.image_outlined), onTap: () => Navigator.of(context).pushNamed("/image"), ), ], ), Container( alignment: Alignment.topLeft, padding: const EdgeInsets.only(left: 16, top: 8, bottom: 4), child: Text( S.of(context).all_chats, style: Theme.of(context).textTheme.labelSmall, ), ), Expanded( child: Consumer( builder: (context, ref, child) { ref.watch(chatsProvider); return ListView.builder( itemCount: _chats.length, itemBuilder: (context, index) => _buildChatItem(index), padding: EdgeInsets.only(left: 8, right: 8, bottom: 8), ); }, ), ), ], ); } Widget _buildChatItem(int index) { final chat = _chats[index]; return Container( margin: EdgeInsets.only(top: 4), child: ListTile( dense: true, minTileHeight: 48, shape: const StadiumBorder(), leading: const Icon(Icons.article), selected: Current.chat == chat, contentPadding: const EdgeInsets.only(left: 16, right: 8), title: Text( chat.title, maxLines: 1, softWrap: false, overflow: TextOverflow.ellipsis, ), subtitle: Text(chat.time), onTap: () async { if (Current.chat == chat) return; Current.chat = chat; ref.read(chatsProvider.notifier).notify(); await Current.load(chat); ref.read(chatProvider.notifier).notify(); ref.read(messagesProvider.notifier).notify(); }, trailing: IconButton( icon: const Icon(Icons.delete), onPressed: () { _chats.removeAt(index); ref.read(chatsProvider.notifier).notify(); Config.save(); File(Config.chatFilePath(chat.fileName)).delete(); if (Current.chat == chat) { Current.clear(); ref.read(chatProvider.notifier).notify(); ref.read(messagesProvider.notifier).notify(); } }, ), ), ); } Widget _buildBody() { return Column( children: [ Expanded( child: Stack( alignment: Alignment.topCenter, children: [ Consumer( builder: (context, ref, child) { ref.watch(messagesProvider); final length = _messages.length; return ListView.separated( reverse: true, shrinkWrap: true, controller: _scrollCtrl, padding: const EdgeInsets.all(16), separatorBuilder: (context, index) => const SizedBox(height: 16), itemCount: length, itemBuilder: (context, index) { final message = _messages[length - index - 1]; return MessageWidget( key: ValueKey(message), message: message, ); }, ); }, ), Positioned( bottom: 8, child: Consumer( builder: (context, ref, child) { final show = ref.watch(_toBottomProvider); final child = ElevatedButton( style: ElevatedButton.styleFrom( elevation: 2, shape: const CircleBorder(), padding: const EdgeInsets.all(8), ), onPressed: () => _scrollCtrl.jumpTo(0), child: Icon(Icons.arrow_downward_rounded, size: 20), ); return show ? ZoomIn(child: child) : ZoomOut(child: child); }, ), ), ], ), ), Padding( padding: const EdgeInsets.only(top: 0, left: 8, right: 8, bottom: 8), child: const InputWidget(), ), ], ); } Future _exportChatAsImage() async { InputWidget.unFocus(); if (Current.messages.isEmpty) return; try { Dialogs.loading( context: context, hint: S.of(context).exporting, ); final width = MediaQuery.of(context).size.width; final page = Container( padding: const EdgeInsets.only(top: 16, left: 16, right: 16, bottom: 0), constraints: BoxConstraints(maxWidth: width), child: MediaQuery( data: MediaQueryData.fromView(View.of(context)).copyWith( size: Size(width, double.infinity), ), child: Column( children: [ for (final message in _messages) ...[ MessageView(message: message), const SizedBox(height: 16), ] ], ), ), ); final png = await ScreenshotController().captureFromLongWidget( InheritedTheme.captureAll( context, Material(child: page), ), context: context, pixelRatio: MediaQuery.of(context).devicePixelRatio, ); final time = DateTime.now().millisecondsSinceEpoch.toString(); final path = Config.cacheFilePath("$time.png"); final file = File(path); await file.writeAsBytes(png.toList()); if (!mounted) return; Navigator.of(context).pop(); Dialogs.handleImage(context: context, path: path); } catch (e) { Navigator.of(context).pop(); Dialogs.error(context: context, error: e); } } } final _toBottomProvider = AutoDisposeNotifierProvider<_ToBottomNotifier, bool>(_ToBottomNotifier.new); class _ToBottomNotifier extends AutoDisposeNotifier { @override bool build() { ref.listen(messagesProvider, (prev, next) { if (state) hide(); }); return false; } void show() => state = true; void hide() => state = false; } ================================================ FILE: lib/chat/current.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "message.dart"; import "../util.dart"; import "../config.dart"; import "dart:io"; import "dart:isolate"; import "dart:convert"; class Current { static File? _file; static ChatConfig? _chat; static CoreConfig core = Config.core; static final List messages = []; static TtsStatus ttsStatus = TtsStatus.nothing; static ChatStatus chatStatus = ChatStatus.nothing; static Future load(ChatConfig chat) async { _file = File(Config.chatFilePath(chat.fileName)); final from = _file; final json = await Isolate.run(() async { return jsonDecode(await from!.readAsString()); }); final messagesJson = json["messages"] ?? []; final coreJson = json["core"]; messages.clear(); for (final message in messagesJson) { messages.add(Message.fromJson(message)); } core = coreJson != null ? CoreConfig.fromJson(coreJson) : Config.core; } static Future save() async { await _file!.writeAsString(jsonEncode({ "core": core, "messages": messages, })); } static void clear() { _chat = null; _file = null; messages.clear(); core = Config.core; } static void newChat(String title) { final now = DateTime.now(); final timestamp = now.millisecondsSinceEpoch.toString(); final time = Util.formatDateTime(now); final fileName = "$timestamp.json"; _chat = ChatConfig( time: time, title: title, fileName: fileName, ); _file = File(Config.chatFilePath(fileName)); Config.chats.insert(0, _chat!); Config.save(); } static String? get bot => core.bot; static String? get api => core.api; static String? get model => core.model; static ApiConfig? get _api => Config.apis[api]; static BotConfig? get _bot => Config.bots[bot]; static String? get apiUrl => _api?.url; static String? get apiKey => _api?.key; static String? get apiType => _api?.type; static bool? get stream => _bot?.stream; static int? get maxTokens => _bot?.maxTokens; static double? get temperature => _bot?.temperature; static String? get systemPrompts => _bot?.systemPrompts; static ChatConfig? get chat => _chat; static set chat(ChatConfig? chat) => _chat = chat!; static String? get title => _chat?.title; static set title(String? title) => _chat?.title = title!; static bool get hasChat => _chat != null; } enum TtsStatus { nothing, loading, playing; bool get isNothing => this == TtsStatus.nothing; bool get isLoading => this == TtsStatus.loading; bool get isPlaying => this == TtsStatus.playing; } enum ChatStatus { nothing, responding; bool get isNothing => this == ChatStatus.nothing; bool get isResponding => this == ChatStatus.responding; } ================================================ FILE: lib/chat/input.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "chat.dart"; import "message.dart"; import "current.dart"; import "../util.dart"; import "../config.dart"; import "../llm/llm.dart"; import "../gen/l10n.dart"; import "dart:convert"; import "package:flutter/material.dart"; import "package:flutter/services.dart"; import "package:image_picker/image_picker.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_image_compress/flutter_image_compress.dart"; class InputWidget extends ConsumerStatefulWidget { static final FocusNode focusNode = FocusNode(); const InputWidget({super.key}); @override ConsumerState createState() => _InputWidgetState(); static void unFocus() => focusNode.unfocus(); } typedef _Image = ({String name, MessageImage image}); class _InputWidgetState extends ConsumerState { String _lastText = ""; static final List<_Image> _images = []; final TextEditingController _inputCtrl = TextEditingController(); @override void initState() { super.initState(); _inputCtrl.addListener(() { final text = _inputCtrl.text; if (_lastText.isEmpty ^ text.isEmpty) { setState(() {}); } _lastText = text; }); } @override void dispose() { _inputCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { ref.watch(llmProvider); return Container( constraints: BoxConstraints( maxHeight: MediaQuery.of(context).size.height / 4, ), decoration: BoxDecoration( color: Theme.of(context).colorScheme.surfaceContainerHigh, borderRadius: const BorderRadius.all(Radius.circular(12)), border: Border.all( color: Theme.of(context).colorScheme.outlineVariant, ), ), child: Column( mainAxisSize: MainAxisSize.min, children: [ Flexible( child: TextField( maxLines: null, autofocus: false, controller: _inputCtrl, focusNode: InputWidget.focusNode, keyboardType: TextInputType.multiline, decoration: InputDecoration( border: InputBorder.none, constraints: const BoxConstraints(), hintText: S.of(context).enter_message, contentPadding: const EdgeInsets.only( top: 8, left: 16, right: 16, bottom: 8), ), ), ), Row( children: [ const SizedBox(width: 8), SizedBox.square( dimension: 36, child: IconButton( icon: const Icon(Icons.upload_file), padding: EdgeInsets.zero, onPressed: _addFile, ), ), const SizedBox(width: 8), SizedBox.square( dimension: 36, child: GestureDetector( onLongPress: () { final old = Preferences.googleSearch; Util.showSnackBar( context: context, content: Text(old ? S.of(context).search_general_mode : S.of(context).search_gemini_mode), ); setState(() => Preferences.googleSearch = !old); }, child: IconButton( icon: const Icon(Icons.language), isSelected: Preferences.search, selectedIcon: Badge( label: const Text("G"), isLabelVisible: Preferences.googleSearch, child: const Icon(Icons.language), ), padding: EdgeInsets.zero, onPressed: () => setState( () => Preferences.search = !Preferences.search), ), ), ), if (_images.isNotEmpty) ...[ const SizedBox(width: 8), SizedBox.square( dimension: 36, child: IconButton( icon: const Icon(Icons.image_outlined), isSelected: true, padding: EdgeInsets.zero, onPressed: _editImages, ), ), ], const Expanded(child: SizedBox()), const SizedBox(width: 8), SizedBox.square( dimension: 36, child: _buildSendButton(), ), const SizedBox(width: 8), ], ), const SizedBox(height: 8), ], ), ); } Widget _buildSendButton() { IconData icon; Color background; Color? foreground; if (Current.chatStatus.isResponding) { icon = Icons.pause; background = Theme.of(context).colorScheme.primaryContainer; foreground = Theme.of(context).colorScheme.onPrimaryContainer; } else { icon = Icons.arrow_upward; if (_inputCtrl.text.isEmpty) { background = Colors.grey.withOpacity(0.2); } else { background = Theme.of(context).colorScheme.primaryContainer; foreground = Theme.of(context).colorScheme.onPrimaryContainer; } } return IconButton( icon: Icon(icon), onPressed: _sendMessage, padding: EdgeInsets.zero, style: IconButton.styleFrom( foregroundColor: foreground, backgroundColor: background, ), ); } Future _addFile() async { InputWidget.unFocus(); final result = await showModalBottomSheet( context: context, builder: (context) => Padding( padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DragHandle(), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).camera), leading: const Icon(Icons.camera_outlined), onTap: () => Navigator.of(context).pop(1), ), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).gallery), leading: const Icon(Icons.photo_library_outlined), onTap: () => Navigator.of(context).pop(2), ), ], ), ), ); switch (result) { case 1: await _addImage(ImageSource.camera); break; case 2: await _addImage(ImageSource.gallery); break; } } Future _addImage(ImageSource source) async { XFile? result; Uint8List? compressed; final picker = ImagePicker(); try { result = await picker.pickImage(source: source); if (result == null) return; } catch (e) { return; } if (Config.cic.enable ?? true) { try { compressed = await FlutterImageCompress.compressWithFile( result.path, quality: Config.cic.quality ?? 95, minWidth: Config.cic.minWidth ?? 1920, minHeight: Config.cic.minHeight ?? 1080, ); if (compressed == null) throw false; } catch (e) { if (mounted) { Util.showSnackBar( context: context, content: Text(S.of(context).image_compress_failed), ); } } } final bytes = compressed ?? await result.readAsBytes(); final image = ( name: result.name, image: (bytes: bytes, base64: base64Encode(bytes)), ); setState(() => _images.add(image)); } void _editImages() async { InputWidget.unFocus(); showModalBottomSheet( context: context, scrollControlDisabledMaxHeightRatio: 0.7, builder: (context) => StatefulBuilder( builder: (context, setState2) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DialogHeader(title: S.of(context).images), const Divider(height: 1), ListView.builder( shrinkWrap: true, itemCount: _images.length, itemBuilder: (context, index) => ListTile( title: Text(_images[index].name), contentPadding: const EdgeInsets.only(left: 24, right: 12), trailing: IconButton( icon: const Icon(Icons.delete), onPressed: () { setState(() => _images.removeAt(index)); if (_images.isEmpty) { Navigator.of(context).pop(); } else { setState2(() {}); } }, ), ), ), const Divider(height: 1), DialogFooter( children: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( onPressed: () { setState(() => _images.clear()); Navigator.of(context).pop(); }, child: Text(S.of(context).clear), ), ], ), ], ), ), ); } Future _sendMessage() async { if (!Current.chatStatus.isNothing) { ref.read(llmProvider.notifier).stopChat(); return; } if (!Util.checkChat(context)) return; final text = _inputCtrl.text; if (text.isEmpty) return; final messages = Current.messages; final user = MessageItem( text: text, role: MessageRole.user, ); for (final image in _images) { user.images.add(image.image); } messages.add(Message.fromItem(user)); final assistant = Message.fromItem(MessageItem( text: "", model: Current.model, role: MessageRole.assistant, time: Util.formatDateTime(DateTime.now()), )); messages.add(assistant); ref.read(messagesProvider.notifier).notify(); _images.clear(); _inputCtrl.clear(); final results = await Future.wait([ _generateTitle(text).catchError((e) => text), ref.read(llmProvider.notifier).chat(assistant), ]); final title = results[0]; final error = results[1]; if (error != null && mounted) { _inputCtrl.text = text; Dialogs.error(context: context, error: error); } if (title != null) { Current.newChat(title); ref.read(chatProvider.notifier).notify(); ref.read(chatsProvider.notifier).notify(); } Current.save(); } Future _generateTitle(String text) async { if (Current.hasChat) return null; return await generateTitle(text); } } ================================================ FILE: lib/chat/message.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "chat.dart"; import "input.dart"; import "current.dart"; import "../util.dart"; import "../config.dart"; import "../llm/llm.dart"; import "../gen/l10n.dart"; import "../markdown/util.dart"; import "../markdown/code.dart"; import "../markdown/latex.dart"; import "dart:async"; import "dart:convert"; import "dart:typed_data"; import "package:flutter/material.dart"; import "package:animate_do/animate_do.dart"; import "package:flutter_spinkit/flutter_spinkit.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_markdown/flutter_markdown.dart"; final messageProvider = NotifierProvider.autoDispose .family(MessageNotifier.new); class MessageNotifier extends AutoDisposeFamilyNotifier { @override void build(Message arg) {} void notify() => ref.notifyListeners(); } enum MessageRole { user, assistant; bool get isUser => this == MessageRole.user; bool get isAssistant => this == MessageRole.assistant; } enum CitationType { web, } typedef MessageImage = ({ Uint8List bytes, String base64, }); typedef MessageCitation = ({ CitationType type, String content, String source, }); class MessageItem { String text; String? time; String? model; MessageRole role; List images = []; List citations = []; MessageItem({ required this.role, required this.text, this.model, this.time, }); factory MessageItem.fromJson(Map json) { final item = switch (json["role"]) { "assistant" => MessageItem( time: json["time"], text: json["text"], model: json["model"], role: MessageRole.assistant, ), "user" => MessageItem( text: json["text"], role: MessageRole.user, ), _ => throw "bad role", }; final image = json["image"]; final images = json["images"] ?? []; if (image != null) { item.images.add(( bytes: base64Decode(image), base64: image, )); } for (final base64 in images) { item.images.add(( bytes: base64Decode(base64), base64: base64, )); } return item; } Map toJson() => switch (role) { MessageRole.assistant => { "time": time, "text": text, "model": model, "role": "assistant", }, MessageRole.user => { "text": text, "role": "user", "images": [ for (final image in images) image.base64, ], }, }; } class Message { int index; List list; Message({ required this.index, required this.list, }); factory Message.fromItem(MessageItem item) => Message( index: 0, list: [item], ); factory Message.fromJson(Map json) => json["index"] == null && json["list"] == null ? Message.fromItem(MessageItem.fromJson(json)) : Message( index: json["index"], list: [ for (final item in json["list"]) MessageItem.fromJson(item), ], ); Map toJson() => { "index": index, "list": list, }; MessageItem get item => list[index]; } class MessageWidget extends ConsumerStatefulWidget { final Message message; const MessageWidget({ required this.message, super.key, }); @override ConsumerState createState() => _MessageWidgetState(); } class _MessageWidgetState extends ConsumerState { @override Widget build(BuildContext context) { final message = widget.message; ref.watch(messageProvider(message)); final item = message.item; final role = item.role; return Container( alignment: role.isUser ? Alignment.topRight : Alignment.topLeft, child: Column( crossAxisAlignment: role.isAssistant ? CrossAxisAlignment.start : CrossAxisAlignment.end, children: [ if (item.images.isNotEmpty) ...[ _buildImages(), const SizedBox(height: 8), ], if (role.isAssistant) ...[ _buildHeader(), SizedBox(height: 8), ], _buildBody(), if (Current.messages.lastOrNull == message && Current.chatStatus.isNothing) ...[ const SizedBox(height: 4), FadeIn(child: _buildToolBar()), ], ], ), ); } Widget _buildImages() { final item = widget.message.item; return LayoutBuilder(builder: (context, constraints) { final n = (constraints.maxWidth / 120).ceil(); final width = (constraints.maxWidth - 8 * (n - 1)) / n; return Wrap( spacing: 8, runSpacing: 8, children: [ for (final image in item.images) Ink( width: width, height: width, decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(12)), image: DecorationImage( image: MemoryImage(image.bytes), fit: BoxFit.cover, ), ), child: InkWell( borderRadius: const BorderRadius.all(Radius.circular(12)), onTap: () async { InputWidget.unFocus(); final result = await showDialog( context: context, builder: (context) => AlertDialog( title: Text(S.of(context).delete_image), content: Text(S.of(context).ensure_delete_image), actions: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( onPressed: () => Navigator.of(context).pop(true), child: Text(S.of(context).delete), ), ], ), ); if (!(result ?? false)) return; setState(() => item.images.remove(image)); Current.save(); }, ), ), ], ); }); } Widget _buildHeader() { final message = widget.message; final item = message.item; final id = item.model; return Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ ModelAvatar(id: id), const SizedBox(width: 12), Flexible( child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 1), Text( Config.models[id]?.name ?? id ?? S.of(context).no_model, style: Theme.of(context).textTheme.titleMedium, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 1), Text( item.time ?? Util.formatDateTime(DateTime.now()), style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 2), ], ), ), if (message.list.length > 1 && (Current.chatStatus.isNothing || message != Current.messages.lastOrNull)) ...[ const SizedBox(width: 8), SizedBox( width: 32, height: 32, child: IconButton( icon: const Icon(Icons.arrow_back_ios_rounded), iconSize: 16, onPressed: () { if (item == message.list.first) return; setState(() => message.index--); Current.save(); }, ), ), Text("${message.index + 1}/${message.list.length}"), SizedBox( width: 32, height: 32, child: IconButton( icon: const Icon(Icons.arrow_forward_ios_rounded), iconSize: 16, onPressed: () { if (item == message.list.last) return; setState(() => message.index++); Current.save(); }, ), ), ], ], ); } Widget _buildBody() { final item = widget.message.item; final text = item.text; final role = item.role; final colorScheme = Theme.of(context).colorScheme; final markdownStyleSheet = MarkdownStyleSheet( codeblockPadding: EdgeInsets.all(0), codeblockDecoration: BoxDecoration( color: colorScheme.surfaceContainerHighest, borderRadius: const BorderRadius.all(Radius.circular(12)), ), blockquoteDecoration: BoxDecoration( color: colorScheme.brightness == Brightness.light ? Colors.blueGrey.withOpacity(0.3) : Colors.black.withOpacity(0.3), borderRadius: const BorderRadius.all(Radius.circular(12)), ), ); final radius = BorderRadius.only( topLeft: const Radius.circular(12), bottomLeft: const Radius.circular(12), bottomRight: const Radius.circular(12), topRight: Radius.circular(role.isUser ? 2 : 12), ); return LayoutBuilder( key: UniqueKey(), builder: (context, constraints) => Ink( decoration: BoxDecoration( color: role.isAssistant ? colorScheme.surfaceContainer : colorScheme.secondaryContainer, borderRadius: radius, ), child: InkWell( borderRadius: radius, onLongPress: _longPress, child: Container( padding: const EdgeInsets.all(12), constraints: BoxConstraints( maxWidth: constraints.maxWidth * (role.isUser ? 0.9 : 1), ), child: switch (text.isNotEmpty) { true => MarkdownBody( data: text, extensionSet: mdExtensionSet, onTapLink: (text, href, title) => Dialogs.openLink(context: context, link: href), builders: { "pre": CodeBlockBuilder(context: context), "latex": LatexElementBuilder(textScaleFactor: 1.2), }, styleSheet: markdownStyleSheet, styleSheetTheme: MarkdownStyleSheetBaseTheme.material, ), false => SizedBox( width: 36, height: 18, child: SpinKitWave( size: 18, color: colorScheme.onSurfaceVariant, ), ), }, ), ), ), ); } Widget _buildToolBar() { final item = widget.message.item; final role = item.role; return Row( mainAxisAlignment: role.isUser ? MainAxisAlignment.end : MainAxisAlignment.start, children: [ if (role.isAssistant) ...[ SizedBox( width: 36, height: 26, child: IconButton( icon: Icon(switch (Current.ttsStatus) { TtsStatus.loading => Icons.cancel_outlined, TtsStatus.nothing => Icons.volume_up_outlined, TtsStatus.playing => Icons.pause_circle_outlined, }), iconSize: 18, onPressed: _tts, padding: EdgeInsets.zero, ), ), SizedBox( width: 36, height: 26, child: IconButton( icon: const Icon(Icons.sync_outlined), iconSize: 18, onPressed: _reanswer, padding: EdgeInsets.zero, ), ), if (item.citations.isNotEmpty) SizedBox( width: 36, height: 26, child: IconButton( icon: const Icon(Icons.find_in_page_outlined), iconSize: 18, onPressed: _citations, padding: EdgeInsets.zero, ), ), ], SizedBox( width: 36, height: 26, child: IconButton( icon: const Icon(Icons.paste_outlined), iconSize: 16, onPressed: _copy, padding: EdgeInsets.zero, ), ), SizedBox( width: 36, height: 26, child: IconButton( icon: const Icon(Icons.edit_outlined), iconSize: 18, onPressed: _edit, padding: EdgeInsets.zero, ), ), SizedBox( width: 36, height: 26, child: IconButton( icon: const Icon(Icons.delete_outlined), iconSize: 18, onPressed: _delete, padding: EdgeInsets.zero, ), ), ], ); } void _edit() { InputWidget.unFocus(); Navigator.of(context).push(MaterialPageRoute( builder: (context) => _MessageEditor(message: widget.message), )); } void _copy() { Util.copyText( context: context, text: widget.message.item.text, ); } void _delete() { if (!Current.chatStatus.isNothing) return; if (!Current.ttsStatus.isNothing) return; final message = widget.message; final list = message.list; final item = message.item; if (list.length == 1) { Current.messages.remove(message); ref.read(messagesProvider.notifier).notify(); } else { if (item == list.last) message.index--; setState(() => list.remove(item)); } Current.save(); } void _source() { InputWidget.unFocus(); showModalBottomSheet( context: context, useSafeArea: true, showDragHandle: true, scrollControlDisabledMaxHeightRatio: 1, builder: (context) => ConstrainedBox( constraints: BoxConstraints( minWidth: double.infinity, minHeight: MediaQuery.of(context).size.height * 0.6, ), child: SingleChildScrollView( padding: const EdgeInsets.only(left: 24, right: 24), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ SelectableText( widget.message.item.text, style: Theme.of(context).textTheme.bodyLarge, ), const SizedBox(height: 48), ], ), ), ), ); } void _citations() { InputWidget.unFocus(); final citations = widget.message.item.citations; void onTap(MessageCitation citation) { switch (citation.type) { case CitationType.web: Dialogs.openLink( context: context, link: citation.source, ); break; } } showModalBottomSheet( context: context, useSafeArea: true, scrollControlDisabledMaxHeightRatio: 0.7, builder: (context) => Column( mainAxisSize: MainAxisSize.min, children: [ DialogHeader(title: S.of(context).citations), const Divider(height: 1), Flexible( child: ListView.separated( itemCount: citations.length, itemBuilder: (context, index) { final citation = citations[index]; final content = citation.content; final source = citation.source; return Card.filled( margin: EdgeInsets.zero, color: Theme.of(context).colorScheme.surfaceContainer, child: ListTile( title: Text( source, maxLines: 1, overflow: TextOverflow.ellipsis, ), subtitle: Text( content, maxLines: 2, overflow: TextOverflow.ellipsis, ), onTap: () => onTap(citation), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(12)), ), contentPadding: const EdgeInsets.symmetric(horizontal: 12), ), ); }, padding: const EdgeInsets.all(12), separatorBuilder: (context, index) => const SizedBox(height: 12), ), ), ], ), ); } void _longPress() { InputWidget.unFocus(); void invoke(VoidCallback func) { Navigator.of(context).pop(); func(); } showModalBottomSheet( context: context, builder: (context) => Padding( padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DragHandle(), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).edit), leading: const Icon(Icons.edit_outlined), onTap: () => invoke(_edit), ), ListTile( minTileHeight: 48, shape: StadiumBorder(), title: Text(S.of(context).copy), leading: const Icon(Icons.copy_all), onTap: () => invoke(_copy), ), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).delete), leading: const Icon(Icons.delete_outlined), onTap: () => invoke(_delete), ), ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).source), leading: const Icon(Icons.code_outlined), onTap: () => invoke(_source), ), if (widget.message.item.citations.isNotEmpty) ListTile( minTileHeight: 48, shape: const StadiumBorder(), title: Text(S.of(context).citations), leading: const Icon(Icons.find_in_page_outlined), onTap: () => invoke(_citations), ), ], ), ), ); } Future _tts() async { if (!Current.ttsStatus.isNothing) { ref.read(llmProvider.notifier).stopTts(); return; } final message = widget.message; final text = message.item.text; if (text.isEmpty) return; final tts = Config.tts; final ttsOk = tts.api != null && tts.model != null && tts.voice != null; if (!ttsOk) { Util.showSnackBar( context: context, content: Text(S.of(context).setup_tts_first), ); return; } final error = await ref.read(llmProvider.notifier).tts(message); if (error != null && mounted) { Dialogs.error(context: context, error: error); } } Future _reanswer() async { if (!Current.chatStatus.isNothing) { ref.read(llmProvider.notifier).stopChat(); return; } if (!Util.checkChat(context)) return; final message = widget.message; message.list.add(MessageItem( text: "", model: Current.model, role: MessageRole.assistant, time: Util.formatDateTime(DateTime.now()), )); message.index = message.list.length - 1; final error = await ref.read(llmProvider.notifier).chat(message); if (error != null && mounted) { Dialogs.error(context: context, error: error); } Current.save(); } } class MessageView extends StatelessWidget { final Message message; final MessageItem item; MessageView({ required this.message, super.key, }) : item = message.item; @override Widget build(BuildContext context) { final role = item.role; return Container( alignment: role.isUser ? Alignment.topRight : Alignment.topLeft, child: Column( crossAxisAlignment: role.isAssistant ? CrossAxisAlignment.start : CrossAxisAlignment.end, children: [ if (item.images.isNotEmpty) ...[ _buildImages(context), const SizedBox(height: 8), ], if (role.isAssistant) ...[ _buildHeader(context), const SizedBox(height: 8), ], _buildBody(context), ], ), ); } Widget _buildImages(BuildContext context) { return LayoutBuilder(builder: (context, constraints) { final n = (constraints.maxWidth / 120).ceil(); final width = (constraints.maxWidth - 8 * (n - 1)) / n; return Wrap( spacing: 8, runSpacing: 8, children: [ for (final image in item.images) ClipRRect( borderRadius: const BorderRadius.all(Radius.circular(8)), child: Image.memory( image.bytes, width: width, height: width, fit: BoxFit.cover, ), ), ], ); }); } Widget _buildHeader(BuildContext context) { final id = item.model; return Row( crossAxisAlignment: CrossAxisAlignment.center, children: [ ModelAvatar(id: id), const SizedBox(width: 12), Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 1), Text( Config.models[id]?.name ?? id ?? S.current.no_model, style: Theme.of(context).textTheme.titleMedium, overflow: TextOverflow.ellipsis, ), const SizedBox(height: 1), Text( item.time ?? Util.formatDateTime(DateTime.now()), style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 2), ], ), ], ); } Widget _buildBody(BuildContext context) { final text = item.text; final role = item.role; final colorScheme = Theme.of(context).colorScheme; final markdownStyleSheet = MarkdownStyleSheet( codeblockPadding: EdgeInsets.all(0), codeblockDecoration: BoxDecoration( color: colorScheme.surfaceContainerHighest, borderRadius: const BorderRadius.all(Radius.circular(12)), ), blockquoteDecoration: BoxDecoration( color: colorScheme.brightness == Brightness.light ? Colors.blueGrey.withOpacity(0.3) : Colors.black.withOpacity(0.3), borderRadius: const BorderRadius.all(Radius.circular(12)), ), ); final radius = BorderRadius.only( topLeft: const Radius.circular(12), bottomLeft: const Radius.circular(12), bottomRight: const Radius.circular(12), topRight: Radius.circular(role.isUser ? 2 : 12), ); return Container( padding: const EdgeInsets.all(12), constraints: BoxConstraints( maxWidth: MediaQuery.of(context).size.width * (role.isUser ? 0.9 : 1), ), decoration: BoxDecoration( borderRadius: radius, color: role.isAssistant ? colorScheme.surfaceContainer : colorScheme.secondaryContainer, ), child: MarkdownBody( data: text, extensionSet: mdExtensionSet, onTapLink: (text, href, title) => Dialogs.openLink(context: context, link: href), builders: { "pre": CodeBlockBuilder2(context: context), "latex": LatexElementBuilder2(textScaleFactor: 1.2), }, styleSheet: markdownStyleSheet, styleSheetTheme: MarkdownStyleSheetBaseTheme.material, ), ); } } class _MessageEditor extends ConsumerStatefulWidget { final Message message; const _MessageEditor({ required this.message, }); @override ConsumerState<_MessageEditor> createState() => _MessageEditorState(); } class _MessageEditorState extends ConsumerState<_MessageEditor> { late final Message message; late final UndoHistoryController _undoCtrl; late final TextEditingController _editCtrl; @override void initState() { super.initState(); message = widget.message; _undoCtrl = UndoHistoryController(); final text = widget.message.item.text; _editCtrl = TextEditingController(text: text); } @override void dispose() { _editCtrl.dispose(); _undoCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text(S.of(context).edit), actions: [ IconButton( icon: const Icon(Icons.undo), onPressed: () => _undoCtrl.undo(), ), IconButton( icon: const Icon(Icons.redo), onPressed: () => _undoCtrl.redo(), ), IconButton( icon: const Icon(Icons.done), onPressed: () { message.item.text = _editCtrl.text; ref.read(messageProvider(message).notifier).notify(); Current.save(); Navigator.of(context).pop(); }, ), ], ), body: TextField( expands: true, maxLines: null, controller: _editCtrl, undoController: _undoCtrl, textAlign: TextAlign.start, keyboardType: TextInputType.multiline, decoration: InputDecoration( border: InputBorder.none, hintText: S.of(context).enter_message, contentPadding: const EdgeInsets.only(top: 12, left: 16, right: 16, bottom: 12), ), ), ); } } ================================================ FILE: lib/chat/settings.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "chat.dart"; import "current.dart"; import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "../settings/api.dart"; import "../settings/bot.dart"; import "../workspace/model.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class ChatSettings extends ConsumerStatefulWidget { const ChatSettings({super.key}); @override ConsumerState createState() => _ChatSettingsState(); } class _ChatSettingsState extends ConsumerState { String? _error; String? _bot = Current.bot; String? _api = Current.api; String? _model = Current.model; final TextEditingController _ctrl = TextEditingController(text: Current.title); @override void dispose() { _ctrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { ref.watch(chatProvider); ref.watch(botsProvider); ref.watch(apisProvider); return Column( mainAxisSize: MainAxisSize.min, children: [ DialogHeader(title: S.of(context).chat_settings), const Divider(height: 1), const SizedBox(height: 4), Row( children: [ const SizedBox(width: 24), Expanded( child: TextField( controller: _ctrl, decoration: InputDecoration( errorText: _error, labelText: S.of(context).chat_title, border: const UnderlineInputBorder(), ), ), ), IconButton( icon: const Icon(Icons.subdirectory_arrow_left), onPressed: _saveTitle, ), const SizedBox(width: 12), ], ), const SizedBox(height: 12), Flexible( child: SingleChildScrollView( padding: const EdgeInsets.only(left: 12, right: 12), child: Column( mainAxisSize: MainAxisSize.min, children: [ _buildBots(), const SizedBox(height: 8), ConstrainedBox( constraints: const BoxConstraints(maxHeight: 320), child: IntrinsicHeight( child: Row( crossAxisAlignment: CrossAxisAlignment.start, children: [ Flexible( flex: 2, child: _buildApis(), ), const SizedBox(width: 8), Flexible( flex: 3, child: _buildModels(), ), ], ), ), ), const SizedBox(height: 12), ], ), ), ), ], ); } Widget _buildBots() { final bots = Config.bots.keys.toList(); return Card.filled( margin: EdgeInsets.zero, color: Theme.of(context).colorScheme.surfaceContainer, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 12), Row( children: [ const SizedBox(width: 12), Icon( Icons.smart_toy, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 16), Text( S.of(context).bot, style: TextStyle( color: Theme.of(context).colorScheme.primary, ), ), ], ), const SizedBox(height: 12), if (bots.isNotEmpty) ...[ const Divider(height: 1), const SizedBox(height: 8), Stack( children: [ const IgnorePointer( child: Opacity( opacity: 0, child: ChoiceChip( label: Text("bot"), padding: EdgeInsets.all(4), selected: true, ), ), ), const SizedBox(width: double.infinity), Positioned.fill( child: ListView.separated( shrinkWrap: true, scrollDirection: Axis.horizontal, padding: const EdgeInsets.only(left: 12, right: 12), itemCount: bots.length, itemBuilder: (context, index) { final bot = bots[index]; return GestureDetector( onLongPress: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => BotSettings(bot: bot), )), child: ChoiceChip( label: Text(bot), padding: const EdgeInsets.all(4), selected: _bot == bot, onSelected: (value) { setState(() => _bot = value ? bot : null); _saveCore(); }, ), ); }, separatorBuilder: (context, index) => const SizedBox(width: 8), ), ), ], ), const SizedBox(height: 8), ], ], ), ); } Widget _buildApis() { final apis = Config.apis.keys.toList(); return Card.filled( margin: EdgeInsets.zero, color: Theme.of(context).colorScheme.surfaceContainer, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 12), Row( children: [ const SizedBox(width: 12), Icon( Icons.api, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 16), Text( S.of(context).api, style: TextStyle( color: Theme.of(context).colorScheme.primary, ), ), ], ), const SizedBox(height: 12), if (apis.isNotEmpty) ...[ const Divider(height: 1), Flexible( child: SingleChildScrollView( child: Column( children: [ for (final api in apis) ListTile( title: Text(api), minTileHeight: 48, selected: _api == api, contentPadding: const EdgeInsets.only(left: 16, right: 16), onTap: () => setState(() => _api = api), onLongPress: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => ApiSettings(api: api), )), ), ], ), ), ), const SizedBox(height: 12), ], ], ), ); } Widget _buildModels() { final ids = Config.apis[_api]?.models ?? []; final models = <({String id, String name})>[]; for (final it in ids) { final config = Config.models[it]; if (config == null) { models.add((id: it, name: it)); } else if (config.chat) { models.add((id: it, name: config.name)); } } return Card.filled( margin: EdgeInsets.zero, color: Theme.of(context).colorScheme.surfaceContainer, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const SizedBox(height: 12), Row( children: [ const SizedBox(width: 12), Icon( Icons.face, color: Theme.of(context).colorScheme.primary, ), const SizedBox(width: 16), Text( S.of(context).model, style: TextStyle( color: Theme.of(context).colorScheme.primary, ), ), ], ), const SizedBox(height: 12), if (ids.isNotEmpty) ...[ const Divider(height: 1), Flexible( child: SingleChildScrollView( child: Column( children: [ for (final model in models) ListTile( title: Text(model.name), minTileHeight: 48, selected: _model == model.id, contentPadding: const EdgeInsets.only(left: 16, right: 16), onTap: () { setState(() => _model = model.id); _saveCore(); }, onLongPress: () => showModalBottomSheet( context: context, useSafeArea: true, isScrollControlled: true, builder: (context) => Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), child: ModelSettings(id: model.id), ), ), ), ], ), ), ), const SizedBox(height: 12), ], ], ), ); } void _saveCore() { final oldModel = Current.model; Current.core = CoreConfig( bot: _bot, api: _api, model: _model, ); if (_model != oldModel) { ref.read(chatProvider.notifier).notify(); } if (Current.hasChat) Current.save(); } void _saveTitle() { final title = _ctrl.text; final hasChat = Current.hasChat; final oldTitle = Current.title ?? ""; if (title.isEmpty && hasChat) { final error = S.of(context).enter_a_title; setState(() => _error = error); return; } if (title != oldTitle) { if (hasChat) { Current.title = title; } else { Current.newChat(title); } ref.read(chatProvider.notifier).notify(); ref.read(chatsProvider.notifier).notify(); } setState(() => _error = null); if (Current.hasChat) Current.save(); } } ================================================ FILE: lib/config.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "dart:io"; import "dart:convert"; import "dart:isolate"; import "package:http/http.dart"; import "package:flutter/material.dart"; import "package:archive/archive_io.dart"; import "package:path_provider/path_provider.dart"; import "package:package_info_plus/package_info_plus.dart"; import "package:shared_preferences/shared_preferences.dart"; class Config { static late final TtsConfig tts; static late final CicConfig cic; static late final CoreConfig core; static late final ImageConfig image; static late final TitleConfig title; static late final SearchConfig search; static late final VectorConfig vector; static late final DocumentConfig document; static final List chats = []; static final Map bots = {}; static final Map apis = {}; static final Map models = {}; static late final File _file; static late final String _dir; static late final String _sep; static late final String _cache; static const String _chatDir = "chat"; static const String _audioDir = "audio"; static const String _imageDir = "image"; static const String _settingsFile = "settings.json"; static Future init() async { _sep = Platform.pathSeparator; _cache = (await getTemporaryDirectory()).path; if (Platform.isAndroid) { _dir = (await getExternalStorageDirectory())!.path; } else { _dir = (await getApplicationSupportDirectory()).path; } _initDir(); _initFile(); _fixChatFile(); await Preferences.init(); } static Future save() async { await _file.writeAsString(jsonEncode(toJson())); } static String chatFilePath(String fileName) => "$_dir$_sep$_chatDir$_sep$fileName"; static String audioFilePath(String fileName) => "$_dir$_sep$_audioDir$_sep$fileName"; static String imageFilePath(String fileName) => "$_dir$_sep$_imageDir$_sep$fileName"; static String cacheFilePath(String fileName) => "$_cache$_sep$fileName"; static Map toJson() => { "tts": tts, "cic": cic, "core": core, "bots": bots, "apis": apis, "chats": chats, "image": image, "title": title, "search": search, "vector": vector, "models": models, "document": document, }; static void fromJson(Map json) { final ttsJson = json["tts"] ?? {}; final imgJson = json["cic"] ?? {}; final coreJson = json["core"] ?? {}; final botsJson = json["bots"] ?? {}; final apisJson = json["apis"] ?? {}; final chatsJson = json["chats"] ?? []; final imageJson = json["image"] ?? {}; final titleJson = json["title"] ?? {}; final searchJson = json["search"] ?? {}; final vectorJson = json["vector"] ?? {}; final modelsJson = json["models"] ?? {}; final documentJson = json["document"] ?? {}; tts = TtsConfig.fromJson(ttsJson); cic = CicConfig.fromJson(imgJson); core = CoreConfig.fromJson(coreJson); image = ImageConfig.fromJson(imageJson); title = TitleConfig.fromJson(titleJson); search = SearchConfig.fromJson(searchJson); vector = VectorConfig.fromJson(vectorJson); document = DocumentConfig.fromJson(documentJson); for (final chat in chatsJson) { chats.add(ChatConfig.fromJson(chat)); } for (final pair in botsJson.entries) { bots[pair.key] = BotConfig.fromJson(pair.value); } for (final pair in apisJson.entries) { apis[pair.key] = ApiConfig.fromJson(pair.value); } for (final pair in modelsJson.entries) { models[pair.key] = ModelConfig.fromJson(pair.value); } } static void _initDir() { final chatPath = "$_dir$_sep$_chatDir"; final chatDir = Directory(chatPath); if (!(chatDir.existsSync())) { chatDir.createSync(); } final imagePath = "$_dir$_sep$_imageDir"; final imageDir = Directory(imagePath); if (!(imageDir.existsSync())) { imageDir.createSync(); } final audioPath = "$_dir$_sep$_audioDir"; final audioDir = Directory(audioPath); if (!(audioDir.existsSync())) { audioDir.createSync(); } } static void _initFile() { final path = "$_dir$_sep$_settingsFile"; _file = File(path); if (_file.existsSync()) { final data = _file.readAsStringSync(); fromJson(jsonDecode(data)); } else { fromJson({}); } } static void _fixChatFile() { for (final chat in chats) { final fileName = chat.fileName; final oldPath = "$_dir$_sep$fileName"; final newPath = chatFilePath(fileName); final file = File(oldPath); if (file.existsSync()) { file.renameSync(newPath); } } } } class Backup { static Future exportConfig(String to) async { final time = DateTime.now().millisecondsSinceEpoch.toString(); final path = "$to${Config._sep}chatbot-backup-$time.zip"; final root = Directory(Config._dir); await Isolate.run(() async { final encoder = ZipFileEncoder(); encoder.create(path); await for (final entity in root.list()) { if (entity is File) { encoder.addFile(entity); } else if (entity is Directory) { encoder.addDirectory(entity); } } await encoder.close(); }); } static Future importConfig(String from) async { final root = Config._dir; await Isolate.run(() async { await extractFileToDisk(from, root); }); } static Future clearData(List dirs) async { final root = Config._dir; final sep = Config._sep; await Isolate.run(() async { for (final dir in dirs) { final directory = Directory("$root$sep$dir"); if (!directory.existsSync()) continue; directory.deleteSync(recursive: true); } }); Config._initDir(); } } class Updater { static List? versionCode; static const String latestUrl = "https://github.com/fanenr/flutter-chatbot/releases/latest"; static const String apiEndPoint = "https://api.github.com/repos/fanenr/flutter-chatbot/releases/latest"; static Future check() async { if (versionCode == null) { final version = (await PackageInfo.fromPlatform()).version; versionCode = version.split('.').map(int.parse).toList(); } final client = Client(); final response = await client.get(Uri.parse(apiEndPoint)); if (response.statusCode != 200) { throw "${response.statusCode} ${response.body}"; } final json = jsonDecode(response.body); return _isNewer(json["tag_name"]) ? json : null; } static bool _isNewer(String latest) { final latestCode = latest.substring(1).split('.').map(int.parse).toList(); for (int i = 0; i < 3; i++) { if (latestCode[i] < versionCode![i]) return false; if (latestCode[i] > versionCode![i]) return true; } return false; } } class Preferences { static late bool _search; static late bool _googleSearch; static late SharedPreferencesAsync _prefs; static Future init() async { SharedPreferences.setPrefix("chatbot"); _prefs = SharedPreferencesAsync(); await _init(); } static bool get search => _search; static bool get googleSearch => _googleSearch; static set search(bool value) { _search = value; _prefs.setBool("search", value); } static set googleSearch(bool value) { _googleSearch = value; _prefs.setBool("googleSearch", value); } static Future _init() async { _search = await _prefs.getBool("search") ?? false; _googleSearch = await _prefs.getBool("googleSearch") ?? false; } } class BotConfig { bool? stream; int? maxTokens; double? temperature; String? systemPrompts; BotConfig({ this.stream, this.maxTokens, this.temperature, this.systemPrompts, }); Map toJson() => { "stream": stream, "maxTokens": maxTokens, "temperature": temperature, "systemPrompts": systemPrompts, }; factory BotConfig.fromJson(Map json) => BotConfig( stream: json["stream"], maxTokens: json["maxTokens"], temperature: json["temperature"], systemPrompts: json["systemPrompts"], ); } class ApiConfig { String url; String key; String? type; List models; ApiConfig({ required this.url, required this.key, required this.models, this.type, }); Map toJson() => { "url": url, "key": key, "type": type, "models": models, }; factory ApiConfig.fromJson(Map json) => ApiConfig( url: json["url"], key: json["key"], type: json["type"], models: json["models"].cast(), ); } class CoreConfig { String? _bot; String? _api; String? _model; CoreConfig({ String? bot, String? api, String? model, }) : _bot = bot, _api = api, _model = model; String? get bot => Config.bots.containsKey(_bot) ? _bot : null; String? get api => Config.apis.containsKey(_api) ? _api : null; String? get model => (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null; set bot(String? value) => _bot = value; set api(String? value) => _api = value; set model(String? value) => _model = value; Map toJson() => { "bot": bot, "api": api, "model": model, }; factory CoreConfig.fromJson(Map json) => CoreConfig( bot: json["bot"], api: json["api"], model: json["model"], ); } class ChatConfig { String time; String title; String fileName; ChatConfig({ required this.time, required this.title, required this.fileName, }); Map toJson() => { "time": time, "title": title, "fileName": fileName, }; factory ChatConfig.fromJson(Map json) => ChatConfig( time: json["time"], title: json["title"], fileName: json["fileName"], ); } class TtsConfig { String? _api; String? _model; String? voice; TtsConfig({ String? api, String? model, this.voice, }) : _api = api, _model = model; String? get api => Config.apis.containsKey(_api) ? _api : null; String? get model => (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null; set api(String? value) => _api = value; set model(String? value) => _model = value; Map toJson() => { "api": api, "model": model, "voice": voice, }; factory TtsConfig.fromJson(Map json) => TtsConfig( api: json["api"], model: json["model"], voice: json["voice"], ); } class CicConfig { bool? enable; int? quality; int? minWidth; int? minHeight; CicConfig({ this.enable, this.quality, this.minWidth, this.minHeight, }); Map toJson() => { "enable": enable, "quality": quality, "minWidth": minWidth, "minHeight": minHeight, }; factory CicConfig.fromJson(Map json) => CicConfig( enable: json["enable"], quality: json["quality"], minWidth: json["minWidth"], minHeight: json["minHeight"], ); } class ImageConfig { String? _api; String? _model; String? size; String? style; String? quality; ImageConfig({ String? api, String? model, this.size, this.style, this.quality, }) : _api = api, _model = model; String? get api => Config.apis.containsKey(_api) ? _api : null; String? get model => (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null; set api(String? value) => _api = value; set model(String? value) => _model = value; Map toJson() => { "api": api, "model": model, "size": size, "style": style, "quality": quality, }; factory ImageConfig.fromJson(Map json) => ImageConfig( api: json["api"], size: json["size"], model: json["model"], style: json["style"], quality: json["quality"], ); } class ModelConfig { bool chat; String name; ModelConfig({ required this.chat, required this.name, }); Map toJson() => { "chat": chat, "name": name, }; factory ModelConfig.fromJson(Map json) => ModelConfig( chat: json["chat"], name: json["name"], ); } class TitleConfig { bool? enable; String? _api; String? _model; String? prompt; TitleConfig({ String? api, String? model, this.enable, this.prompt, }) : _api = api, _model = model; String? get api => Config.apis.containsKey(_api) ? _api : null; String? get model => (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null; set api(String? value) => _api = value; set model(String? value) => _model = value; Map toJson() => { "api": api, "model": model, "prompt": prompt, "enable": enable, }; factory TitleConfig.fromJson(Map json) => TitleConfig( api: json["api"], model: json["model"], prompt: json["prompt"], enable: json["enable"], ); } class SearchConfig { int? n; bool? vector; int? queryTime; int? fetchTime; String? prompt; String? searxng; SearchConfig({ this.n, this.vector, this.prompt, this.searxng, this.queryTime, this.fetchTime, }); Map toJson() => { "n": n, "vector": vector, "prompt": prompt, "query": queryTime, "fetch": fetchTime, "searxng": searxng, }; factory SearchConfig.fromJson(Map json) => SearchConfig( n: json["n"], vector: json["vector"], prompt: json["prompt"], queryTime: json["query"], fetchTime: json["fetch"], searxng: json["searxng"], ); } class VectorConfig { String? _api; String? _model; int? batchSize; int? dimensions; VectorConfig({ String? api, String? model, this.batchSize, this.dimensions, }) : _api = api, _model = model; String? get api => Config.apis.containsKey(_api) ? _api : null; String? get model => (Config.apis[_api]?.models.contains(_model) ?? false) ? _model : null; set api(String? value) => _api = value; set model(String? value) => _model = value; factory VectorConfig.fromJson(Map json) => VectorConfig( api: json["api"], model: json["model"], batchSize: json["batchSize"], dimensions: json["dimensions"], ); Map toJson() => { "api": api, "model": model, "batchSize": batchSize, "dimensions": dimensions, }; } class DocumentConfig { int? n; int? size; int? overlap; DocumentConfig({ this.n, this.size, this.overlap, }); Map toJson() => { "n": n, "size": size, "overlap": overlap, }; factory DocumentConfig.fromJson(Map json) => DocumentConfig( n: json["n"], size: json["size"], overlap: json["overlap"], ); } const _baseColor = Colors.indigo; final ColorScheme darkColorScheme = ColorScheme.fromSeed( brightness: Brightness.dark, seedColor: _baseColor, ); final ColorScheme lightColorScheme = ColorScheme.fromSeed( brightness: Brightness.light, seedColor: _baseColor, ); final darkTheme = ThemeData.dark(useMaterial3: true).copyWith( colorScheme: darkColorScheme, bottomSheetTheme: BottomSheetThemeData( backgroundColor: darkColorScheme.surface, ), appBarTheme: AppBarTheme(color: darkColorScheme.primaryContainer), ); final lightTheme = ThemeData.light(useMaterial3: true).copyWith( colorScheme: lightColorScheme, bottomSheetTheme: BottomSheetThemeData( backgroundColor: lightColorScheme.surface, ), appBarTheme: AppBarTheme(color: lightColorScheme.primaryContainer), ); ================================================ FILE: lib/gen/intl/messages_all.dart ================================================ // DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that looks up messages for specific locales by // delegating to the appropriate library. // Ignore issues from commonly used lints in this file. // ignore_for_file:implementation_imports, file_names, unnecessary_new // ignore_for_file:unnecessary_brace_in_string_interps, directives_ordering // ignore_for_file:argument_type_not_assignable, invalid_assignment // ignore_for_file:prefer_single_quotes, prefer_generic_function_type_aliases // ignore_for_file:comment_references import 'dart:async'; import 'package:flutter/foundation.dart'; import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; import 'package:intl/src/intl_helpers.dart'; import 'messages_en.dart' as messages_en; import 'messages_zh_CN.dart' as messages_zh_cn; typedef Future LibraryLoader(); Map _deferredLibraries = { 'en': () => new SynchronousFuture(null), 'zh_CN': () => new SynchronousFuture(null), }; MessageLookupByLibrary? _findExact(String localeName) { switch (localeName) { case 'en': return messages_en.messages; case 'zh_CN': return messages_zh_cn.messages; default: return null; } } /// User programs should call this before using [localeName] for messages. Future initializeMessages(String localeName) { var availableLocale = Intl.verifiedLocale( localeName, (locale) => _deferredLibraries[locale] != null, onFailure: (_) => null); if (availableLocale == null) { return new SynchronousFuture(false); } var lib = _deferredLibraries[availableLocale]; lib == null ? new SynchronousFuture(false) : lib(); initializeInternalMessageLookup(() => new CompositeMessageLookup()); messageLookup.addLocale(availableLocale, _findGeneratedMessagesFor); return new SynchronousFuture(true); } bool _messagesExistFor(String locale) { try { return _findExact(locale) != null; } catch (e) { return false; } } MessageLookupByLibrary? _findGeneratedMessagesFor(String locale) { var actualLocale = Intl.verifiedLocale(locale, _messagesExistFor, onFailure: (_) => null); if (actualLocale == null) return null; return _findExact(actualLocale); } ================================================ FILE: lib/gen/intl/messages_en.dart ================================================ // DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a en locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'en'; static String m0(pages, text) => "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."; static String m1(text) => "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."; final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { "all_chats": MessageLookupByLibrary.simpleMessage("All Chats"), "api": MessageLookupByLibrary.simpleMessage("API"), "api_key": MessageLookupByLibrary.simpleMessage("API Key"), "api_type": MessageLookupByLibrary.simpleMessage("API Type"), "api_url": MessageLookupByLibrary.simpleMessage("API Url"), "apis": MessageLookupByLibrary.simpleMessage("APIs"), "base_config": MessageLookupByLibrary.simpleMessage("Base Config"), "bot": MessageLookupByLibrary.simpleMessage("Bot"), "bots": MessageLookupByLibrary.simpleMessage("Bots"), "camera": MessageLookupByLibrary.simpleMessage("Camera"), "cancel": MessageLookupByLibrary.simpleMessage("Cancel"), "cannot_open": MessageLookupByLibrary.simpleMessage("Cannot Open"), "chat_image_compress": MessageLookupByLibrary.simpleMessage("Chat Image Compress"), "chat_model": MessageLookupByLibrary.simpleMessage("Chat Model"), "chat_model_hint": MessageLookupByLibrary.simpleMessage("Is it a Chat Model?"), "chat_settings": MessageLookupByLibrary.simpleMessage("Chat Settings"), "chat_title": MessageLookupByLibrary.simpleMessage("Chat Title"), "check_for_updates": MessageLookupByLibrary.simpleMessage("Check for Updates"), "choose_api": MessageLookupByLibrary.simpleMessage("Choose API"), "choose_bot": MessageLookupByLibrary.simpleMessage("Choose Bot"), "choose_model": MessageLookupByLibrary.simpleMessage("Choose Model"), "chunk_n": MessageLookupByLibrary.simpleMessage("Number of Chunks"), "chunk_n_hint": MessageLookupByLibrary.simpleMessage( "Number of chunks to be integrated into the context"), "chunk_overlap": MessageLookupByLibrary.simpleMessage("Chunk Overlap"), "chunk_overlap_hint": MessageLookupByLibrary.simpleMessage( "Size of the overlapping portion with the previous chunk"), "chunk_size": MessageLookupByLibrary.simpleMessage("Chunk Size"), "chunk_size_hint": MessageLookupByLibrary.simpleMessage( "Maximum number of characters a single chunk can contain"), "citations": MessageLookupByLibrary.simpleMessage("Citations"), "clear": MessageLookupByLibrary.simpleMessage("Clear"), "clear_chat": MessageLookupByLibrary.simpleMessage("Clear Chat"), "clear_data": MessageLookupByLibrary.simpleMessage("Clear Data"), "clear_data_audio": MessageLookupByLibrary.simpleMessage("All TTS cache files"), "clear_data_chat": MessageLookupByLibrary.simpleMessage("All chat history"), "clear_data_image": MessageLookupByLibrary.simpleMessage("All generated images"), "cleared_successfully": MessageLookupByLibrary.simpleMessage("Cleared Successfully"), "clearing": MessageLookupByLibrary.simpleMessage("Clearing..."), "clone_chat": MessageLookupByLibrary.simpleMessage("Clone Chat"), "cloned_successfully": MessageLookupByLibrary.simpleMessage("Cloned Successfully"), "complete_all_fields": MessageLookupByLibrary.simpleMessage("Please complete all fields"), "config": MessageLookupByLibrary.simpleMessage("Config"), "config_hint": MessageLookupByLibrary.simpleMessage( "To avoid export failures, it\'s recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder."), "config_import_export": MessageLookupByLibrary.simpleMessage("Config Import and Export"), "copied_successfully": MessageLookupByLibrary.simpleMessage("Copied Successfully"), "copy": MessageLookupByLibrary.simpleMessage("Copy"), "default_config": MessageLookupByLibrary.simpleMessage("Default Config"), "delete": MessageLookupByLibrary.simpleMessage("Delete"), "delete_image": MessageLookupByLibrary.simpleMessage("Delete image"), "document": MessageLookupByLibrary.simpleMessage("Document"), "document_config": MessageLookupByLibrary.simpleMessage("Document Config"), "document_config_hint": MessageLookupByLibrary.simpleMessage( "Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context."), "download": MessageLookupByLibrary.simpleMessage("Download"), "duplicate_api_name": MessageLookupByLibrary.simpleMessage("Duplicate API name"), "duplicate_bot_name": MessageLookupByLibrary.simpleMessage("Duplicate Bot name"), "edit": MessageLookupByLibrary.simpleMessage("Edit"), "embedding_vector": MessageLookupByLibrary.simpleMessage("Embedding Vector"), "embedding_vector_info": MessageLookupByLibrary.simpleMessage( "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."), "empty": MessageLookupByLibrary.simpleMessage("Empty"), "empty_link": MessageLookupByLibrary.simpleMessage("Empty Link"), "enable": MessageLookupByLibrary.simpleMessage("Enable"), "ensure_clear_chat": MessageLookupByLibrary.simpleMessage( "Are you sure to clear the chat?"), "ensure_delete_image": MessageLookupByLibrary.simpleMessage( "Are you sure to delete the image?"), "enter_a_name": MessageLookupByLibrary.simpleMessage("Please enter a name"), "enter_a_title": MessageLookupByLibrary.simpleMessage("Please enter a title"), "enter_message": MessageLookupByLibrary.simpleMessage("Enter your message"), "enter_prompts": MessageLookupByLibrary.simpleMessage("Enter your prompts"), "error": MessageLookupByLibrary.simpleMessage("Error"), "export_chat_as_image": MessageLookupByLibrary.simpleMessage("Export Image"), "export_config": MessageLookupByLibrary.simpleMessage("Export Config"), "exported_successfully": MessageLookupByLibrary.simpleMessage("Exported Successfully"), "exporting": MessageLookupByLibrary.simpleMessage("Exporting..."), "failed_to_export": MessageLookupByLibrary.simpleMessage( "Can\'t write to that directory."), "gallery": MessageLookupByLibrary.simpleMessage("Gallery"), "generate": MessageLookupByLibrary.simpleMessage("Generate"), "image_compress_failed": MessageLookupByLibrary.simpleMessage("Failed to comprese image"), "image_enable_hint": MessageLookupByLibrary.simpleMessage( "The original image will be used if compression fails"), "image_generation": MessageLookupByLibrary.simpleMessage("Image Generation"), "image_hint": MessageLookupByLibrary.simpleMessage( "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."), "image_quality": MessageLookupByLibrary.simpleMessage("Image Quality"), "image_size": MessageLookupByLibrary.simpleMessage("Image Size"), "image_style": MessageLookupByLibrary.simpleMessage("Image Style"), "images": MessageLookupByLibrary.simpleMessage("Images"), "import_config": MessageLookupByLibrary.simpleMessage("Import Config"), "imported_successfully": MessageLookupByLibrary.simpleMessage("Imported Successfully"), "importing": MessageLookupByLibrary.simpleMessage("Importing..."), "invalid_max_tokens": MessageLookupByLibrary.simpleMessage("Invalid Max Tokens"), "invalid_temperature": MessageLookupByLibrary.simpleMessage("Invalid Temperature"), "link": MessageLookupByLibrary.simpleMessage("Link"), "max_tokens": MessageLookupByLibrary.simpleMessage("Max Tokens"), "min_height": MessageLookupByLibrary.simpleMessage("Minimal Height"), "min_width": MessageLookupByLibrary.simpleMessage("Minimal Width"), "min_width_height": MessageLookupByLibrary.simpleMessage("Minimal Size"), "model": MessageLookupByLibrary.simpleMessage("Model"), "model_avatar": MessageLookupByLibrary.simpleMessage("Model Avatar"), "model_list": MessageLookupByLibrary.simpleMessage("Model List"), "model_name": MessageLookupByLibrary.simpleMessage("Model Name"), "name": MessageLookupByLibrary.simpleMessage("Name"), "new_api": MessageLookupByLibrary.simpleMessage("New API"), "new_bot": MessageLookupByLibrary.simpleMessage("New Bot"), "new_chat": MessageLookupByLibrary.simpleMessage("New Chat"), "no_model": MessageLookupByLibrary.simpleMessage("no model"), "not_implemented_yet": MessageLookupByLibrary.simpleMessage("Not implemented yet"), "ok": MessageLookupByLibrary.simpleMessage("Ok"), "open": MessageLookupByLibrary.simpleMessage("Open"), "optional_config": MessageLookupByLibrary.simpleMessage("Optional Config"), "other": MessageLookupByLibrary.simpleMessage("Other"), "play": MessageLookupByLibrary.simpleMessage("Play"), "please_input": MessageLookupByLibrary.simpleMessage("Please Input"), "quality": MessageLookupByLibrary.simpleMessage("Quality"), "reanswer": MessageLookupByLibrary.simpleMessage("Reanswer"), "reset": MessageLookupByLibrary.simpleMessage("Reset"), "restart_app": MessageLookupByLibrary.simpleMessage( "Please restart App to load the new settings."), "save": MessageLookupByLibrary.simpleMessage("Save"), "saved_successfully": MessageLookupByLibrary.simpleMessage("Saved Successfully"), "search_gemini_mode": MessageLookupByLibrary.simpleMessage("Google Search Mode"), "search_general_mode": MessageLookupByLibrary.simpleMessage("General Mode"), "search_n": MessageLookupByLibrary.simpleMessage("Number of Pages"), "search_n_hint": MessageLookupByLibrary.simpleMessage( "Maximum number of web pages to retrieve"), "search_prompt": MessageLookupByLibrary.simpleMessage("Prompt"), "search_prompt_hint": MessageLookupByLibrary.simpleMessage( "Template for context synthesis"), "search_prompt_info": m0, "search_searxng": MessageLookupByLibrary.simpleMessage("SearXNG"), "search_searxng_base": MessageLookupByLibrary.simpleMessage("Base URL"), "search_searxng_extra": MessageLookupByLibrary.simpleMessage("Additional Parameters"), "search_searxng_extra_help": MessageLookupByLibrary.simpleMessage( "For example: engines=google&language=en"), "search_searxng_hint": MessageLookupByLibrary.simpleMessage("SearXNG instance"), "search_timeout": MessageLookupByLibrary.simpleMessage("Timeout"), "search_timeout_fetch": MessageLookupByLibrary.simpleMessage("Fetch Timeout"), "search_timeout_fetch_help": MessageLookupByLibrary.simpleMessage( "Timeout duration for fetching web page content"), "search_timeout_hint": MessageLookupByLibrary.simpleMessage( "Retrieval timeout in milliseconds"), "search_timeout_query": MessageLookupByLibrary.simpleMessage("Query Timeout"), "search_timeout_query_help": MessageLookupByLibrary.simpleMessage( "Timeout duration for SearXNG requests"), "search_vector": MessageLookupByLibrary.simpleMessage("Embedding Vector"), "search_vector_hint": MessageLookupByLibrary.simpleMessage("Recommended to enable"), "select_models": MessageLookupByLibrary.simpleMessage("Select Models"), "settings": MessageLookupByLibrary.simpleMessage("Settings"), "setup_api_model_first": MessageLookupByLibrary.simpleMessage( "Set up the API and Model first"), "setup_searxng_first": MessageLookupByLibrary.simpleMessage("Set up the SearXNG first"), "setup_tts_first": MessageLookupByLibrary.simpleMessage("Set up the TTS first"), "setup_vector_first": MessageLookupByLibrary.simpleMessage( "Set up the embedding vector API and model first"), "share": MessageLookupByLibrary.simpleMessage("Share"), "source": MessageLookupByLibrary.simpleMessage("Source"), "streaming_response": MessageLookupByLibrary.simpleMessage("Streaming Response"), "system_prompts": MessageLookupByLibrary.simpleMessage("System Prompts"), "task": MessageLookupByLibrary.simpleMessage("Task"), "temperature": MessageLookupByLibrary.simpleMessage("Temperature"), "text_to_speech": MessageLookupByLibrary.simpleMessage("Text To Speech"), "title": MessageLookupByLibrary.simpleMessage("ChatBot"), "title_enable_hint": MessageLookupByLibrary.simpleMessage( "If disabled, the user\'s message will be used as the title"), "title_generation": MessageLookupByLibrary.simpleMessage("Title Generation"), "title_generation_hint": m1, "title_prompt": MessageLookupByLibrary.simpleMessage("Prompt"), "title_prompt_hint": MessageLookupByLibrary.simpleMessage( "Template for the title generation prompt"), "up_to_date": MessageLookupByLibrary.simpleMessage("You are up to date"), "vector_batch_size": MessageLookupByLibrary.simpleMessage("Batch Size"), "vector_batch_size_hint": MessageLookupByLibrary.simpleMessage( "Maximum number of chunks that can be submitted in a single request"), "vector_dimensions": MessageLookupByLibrary.simpleMessage("Vector Dimensions"), "vector_dimensions_hint": MessageLookupByLibrary.simpleMessage( "Output dimension of the embedding vector model"), "voice": MessageLookupByLibrary.simpleMessage("Voice"), "web_search": MessageLookupByLibrary.simpleMessage("Web Search"), "workspace": MessageLookupByLibrary.simpleMessage("Workspace") }; } ================================================ FILE: lib/gen/intl/messages_zh_CN.dart ================================================ // DO NOT EDIT. This is code generated via package:intl/generate_localized.dart // This is a library that provides messages for a zh_CN locale. All the // messages from the main program should be duplicated here with the same // function name. // Ignore issues from commonly used lints in this file. // ignore_for_file:unnecessary_brace_in_string_interps, unnecessary_new // ignore_for_file:prefer_single_quotes,comment_references, directives_ordering // ignore_for_file:annotate_overrides,prefer_generic_function_type_aliases // ignore_for_file:unused_import, file_names, avoid_escaping_inner_quotes // ignore_for_file:unnecessary_string_interpolations, unnecessary_string_escapes import 'package:intl/intl.dart'; import 'package:intl/message_lookup_by_library.dart'; final messages = new MessageLookup(); typedef String MessageIfAbsent(String messageStr, List args); class MessageLookup extends MessageLookupByLibrary { String get localeName => 'zh_CN'; static String m0(pages, text) => "提示词模板中的 ${pages} 占位变量会被网页内容替换,${text} 占位变量会被用户消息替换。如不清楚,可留空以使用内置模板。"; static String m1(text) => "提示词模板中的 ${text} 占位变量会被用户消息替换。如不清楚,可留空以使用内置模板。"; final messages = _notInlinedMessages(_notInlinedMessages); static Map _notInlinedMessages(_) => { "all_chats": MessageLookupByLibrary.simpleMessage("所有对话"), "api": MessageLookupByLibrary.simpleMessage("接口"), "api_key": MessageLookupByLibrary.simpleMessage("接口密钥"), "api_type": MessageLookupByLibrary.simpleMessage("接口类型"), "api_url": MessageLookupByLibrary.simpleMessage("接口地址"), "apis": MessageLookupByLibrary.simpleMessage("接口"), "base_config": MessageLookupByLibrary.simpleMessage("基本配置"), "bot": MessageLookupByLibrary.simpleMessage("角色"), "bots": MessageLookupByLibrary.simpleMessage("角色"), "camera": MessageLookupByLibrary.simpleMessage("相机"), "cancel": MessageLookupByLibrary.simpleMessage("取消"), "cannot_open": MessageLookupByLibrary.simpleMessage("无法打开"), "chat_image_compress": MessageLookupByLibrary.simpleMessage("对话图片压缩"), "chat_model": MessageLookupByLibrary.simpleMessage("对话模型"), "chat_model_hint": MessageLookupByLibrary.simpleMessage("是否是对话模型?"), "chat_settings": MessageLookupByLibrary.simpleMessage("对话设置"), "chat_title": MessageLookupByLibrary.simpleMessage("对话标题"), "check_for_updates": MessageLookupByLibrary.simpleMessage("检查更新"), "choose_api": MessageLookupByLibrary.simpleMessage("选择接口"), "choose_bot": MessageLookupByLibrary.simpleMessage("选择角色"), "choose_model": MessageLookupByLibrary.simpleMessage("选择模型"), "chunk_n": MessageLookupByLibrary.simpleMessage("块数量"), "chunk_n_hint": MessageLookupByLibrary.simpleMessage("集成到上下文中的块数量"), "chunk_overlap": MessageLookupByLibrary.simpleMessage("块重叠"), "chunk_overlap_hint": MessageLookupByLibrary.simpleMessage("与上一块重叠部分的大小"), "chunk_size": MessageLookupByLibrary.simpleMessage("块大小"), "chunk_size_hint": MessageLookupByLibrary.simpleMessage("单块能包含的最大字符数"), "citations": MessageLookupByLibrary.simpleMessage("引用"), "clear": MessageLookupByLibrary.simpleMessage("清空"), "clear_chat": MessageLookupByLibrary.simpleMessage("清空对话"), "clear_data": MessageLookupByLibrary.simpleMessage("清理数据"), "clear_data_audio": MessageLookupByLibrary.simpleMessage("所有的 TTS 缓存"), "clear_data_chat": MessageLookupByLibrary.simpleMessage("所有的对话数据"), "clear_data_image": MessageLookupByLibrary.simpleMessage("所有的图片生成结果"), "cleared_successfully": MessageLookupByLibrary.simpleMessage("清理成功"), "clearing": MessageLookupByLibrary.simpleMessage("清理中..."), "clone_chat": MessageLookupByLibrary.simpleMessage("复制对话"), "cloned_successfully": MessageLookupByLibrary.simpleMessage("复制成功"), "complete_all_fields": MessageLookupByLibrary.simpleMessage("请填写所有字段"), "config": MessageLookupByLibrary.simpleMessage("配置"), "config_hint": MessageLookupByLibrary.simpleMessage( "为避免导出失败,建议将配置导出到 Documents 目录,或在 Download 下创建 ChatBot 子目录。"), "config_import_export": MessageLookupByLibrary.simpleMessage("配置导入导出"), "copied_successfully": MessageLookupByLibrary.simpleMessage("拷贝成功"), "copy": MessageLookupByLibrary.simpleMessage("拷贝"), "default_config": MessageLookupByLibrary.simpleMessage("默认配置"), "delete": MessageLookupByLibrary.simpleMessage("删除"), "delete_image": MessageLookupByLibrary.simpleMessage("删除图片"), "document": MessageLookupByLibrary.simpleMessage("文档"), "document_config": MessageLookupByLibrary.simpleMessage("文档配置"), "document_config_hint": MessageLookupByLibrary.simpleMessage( "文档会被划分为若干块,经过搜索比较后,最合适的几个块会被补充进上下文。"), "download": MessageLookupByLibrary.simpleMessage("下载"), "duplicate_api_name": MessageLookupByLibrary.simpleMessage("接口名重复"), "duplicate_bot_name": MessageLookupByLibrary.simpleMessage("角色名重复"), "edit": MessageLookupByLibrary.simpleMessage("编辑"), "embedding_vector": MessageLookupByLibrary.simpleMessage("嵌入向量"), "embedding_vector_info": MessageLookupByLibrary.simpleMessage( "批大小受限于接口服务商,建议查询后修改。向量维度为专业选项,非必要请勿填写。"), "empty": MessageLookupByLibrary.simpleMessage("空"), "empty_link": MessageLookupByLibrary.simpleMessage("空链接"), "enable": MessageLookupByLibrary.simpleMessage("启用"), "ensure_clear_chat": MessageLookupByLibrary.simpleMessage("确定要清空对话?"), "ensure_delete_image": MessageLookupByLibrary.simpleMessage("确定要删除图片?"), "enter_a_name": MessageLookupByLibrary.simpleMessage("请输入名称"), "enter_a_title": MessageLookupByLibrary.simpleMessage("请输入标题"), "enter_message": MessageLookupByLibrary.simpleMessage("输入你的消息"), "enter_prompts": MessageLookupByLibrary.simpleMessage("请输入提示词"), "error": MessageLookupByLibrary.simpleMessage("错误"), "export_chat_as_image": MessageLookupByLibrary.simpleMessage("导出图片"), "export_config": MessageLookupByLibrary.simpleMessage("导出配置"), "exported_successfully": MessageLookupByLibrary.simpleMessage("导出成功"), "exporting": MessageLookupByLibrary.simpleMessage("正在导出..."), "failed_to_export": MessageLookupByLibrary.simpleMessage("无法在该目录下写入文件。"), "gallery": MessageLookupByLibrary.simpleMessage("图库"), "generate": MessageLookupByLibrary.simpleMessage("生成"), "image_compress_failed": MessageLookupByLibrary.simpleMessage("图片压缩失败"), "image_enable_hint": MessageLookupByLibrary.simpleMessage("压缩失败则将使用原图"), "image_generation": MessageLookupByLibrary.simpleMessage("图像生成"), "image_hint": MessageLookupByLibrary.simpleMessage( "质量范围应在 1-100,质量越低压缩率越高。最小宽度与最小高度用于限制图片缩放,如不清楚,请留空。"), "image_quality": MessageLookupByLibrary.simpleMessage("图像质量"), "image_size": MessageLookupByLibrary.simpleMessage("图像尺寸"), "image_style": MessageLookupByLibrary.simpleMessage("图像风格"), "images": MessageLookupByLibrary.simpleMessage("图片"), "import_config": MessageLookupByLibrary.simpleMessage("导入配置"), "imported_successfully": MessageLookupByLibrary.simpleMessage("导入成功"), "importing": MessageLookupByLibrary.simpleMessage("正在导入..."), "invalid_max_tokens": MessageLookupByLibrary.simpleMessage("非法的最大输出"), "invalid_temperature": MessageLookupByLibrary.simpleMessage("非法的温度"), "link": MessageLookupByLibrary.simpleMessage("链接"), "max_tokens": MessageLookupByLibrary.simpleMessage("最大输出"), "min_height": MessageLookupByLibrary.simpleMessage("最小高度"), "min_width": MessageLookupByLibrary.simpleMessage("最小宽度"), "min_width_height": MessageLookupByLibrary.simpleMessage("最小宽高"), "model": MessageLookupByLibrary.simpleMessage("模型"), "model_avatar": MessageLookupByLibrary.simpleMessage("模型头像"), "model_list": MessageLookupByLibrary.simpleMessage("模型列表"), "model_name": MessageLookupByLibrary.simpleMessage("模型名称"), "name": MessageLookupByLibrary.simpleMessage("名称"), "new_api": MessageLookupByLibrary.simpleMessage("新接口"), "new_bot": MessageLookupByLibrary.simpleMessage("新角色"), "new_chat": MessageLookupByLibrary.simpleMessage("新对话"), "no_model": MessageLookupByLibrary.simpleMessage("无模型"), "not_implemented_yet": MessageLookupByLibrary.simpleMessage("还未实现"), "ok": MessageLookupByLibrary.simpleMessage("确定"), "open": MessageLookupByLibrary.simpleMessage("打开"), "optional_config": MessageLookupByLibrary.simpleMessage("可选配置"), "other": MessageLookupByLibrary.simpleMessage("其他"), "play": MessageLookupByLibrary.simpleMessage("播放"), "please_input": MessageLookupByLibrary.simpleMessage("请输入"), "quality": MessageLookupByLibrary.simpleMessage("质量"), "reanswer": MessageLookupByLibrary.simpleMessage("重答"), "reset": MessageLookupByLibrary.simpleMessage("重置"), "restart_app": MessageLookupByLibrary.simpleMessage("请重启应用以加载新配置。"), "save": MessageLookupByLibrary.simpleMessage("保存"), "saved_successfully": MessageLookupByLibrary.simpleMessage("保存成功"), "search_gemini_mode": MessageLookupByLibrary.simpleMessage("Google Search 模式"), "search_general_mode": MessageLookupByLibrary.simpleMessage("通用模式"), "search_n": MessageLookupByLibrary.simpleMessage("网页数量"), "search_n_hint": MessageLookupByLibrary.simpleMessage("检索的网页数量上限"), "search_prompt": MessageLookupByLibrary.simpleMessage("提示词"), "search_prompt_hint": MessageLookupByLibrary.simpleMessage("用于合成上下文的提示词模板"), "search_prompt_info": m0, "search_searxng": MessageLookupByLibrary.simpleMessage("SearXNG"), "search_searxng_base": MessageLookupByLibrary.simpleMessage("根地址"), "search_searxng_extra": MessageLookupByLibrary.simpleMessage("附加参数"), "search_searxng_extra_help": MessageLookupByLibrary.simpleMessage( "例如:engines=google&language=zh"), "search_searxng_hint": MessageLookupByLibrary.simpleMessage("SearXNG 实例"), "search_timeout": MessageLookupByLibrary.simpleMessage("超时时间"), "search_timeout_fetch": MessageLookupByLibrary.simpleMessage("抓取超时"), "search_timeout_fetch_help": MessageLookupByLibrary.simpleMessage("抓取网页内容的超时时间"), "search_timeout_hint": MessageLookupByLibrary.simpleMessage("检索的超时毫秒数"), "search_timeout_query": MessageLookupByLibrary.simpleMessage("检索超时"), "search_timeout_query_help": MessageLookupByLibrary.simpleMessage("请求 SearXNG 的超时时间"), "search_vector": MessageLookupByLibrary.simpleMessage("嵌入向量"), "search_vector_hint": MessageLookupByLibrary.simpleMessage("建议开启"), "select_models": MessageLookupByLibrary.simpleMessage("选择模型"), "settings": MessageLookupByLibrary.simpleMessage("设置"), "setup_api_model_first": MessageLookupByLibrary.simpleMessage("请先配置接口和模型"), "setup_searxng_first": MessageLookupByLibrary.simpleMessage("请先配置 SearXNG 实例"), "setup_tts_first": MessageLookupByLibrary.simpleMessage("请先配置文本转语音"), "setup_vector_first": MessageLookupByLibrary.simpleMessage("请先配置嵌入向量接口和模型"), "share": MessageLookupByLibrary.simpleMessage("分享"), "source": MessageLookupByLibrary.simpleMessage("源码"), "streaming_response": MessageLookupByLibrary.simpleMessage("流式响应"), "system_prompts": MessageLookupByLibrary.simpleMessage("系统提示词"), "task": MessageLookupByLibrary.simpleMessage("任务"), "temperature": MessageLookupByLibrary.simpleMessage("温度"), "text_to_speech": MessageLookupByLibrary.simpleMessage("文本转语音"), "title": MessageLookupByLibrary.simpleMessage("ChatBot"), "title_enable_hint": MessageLookupByLibrary.simpleMessage("禁用则将以用户消息为标题"), "title_generation": MessageLookupByLibrary.simpleMessage("标题生成"), "title_generation_hint": m1, "title_prompt": MessageLookupByLibrary.simpleMessage("提示词"), "title_prompt_hint": MessageLookupByLibrary.simpleMessage("用于生成标题的提示词模板"), "up_to_date": MessageLookupByLibrary.simpleMessage("已是最新版本"), "vector_batch_size": MessageLookupByLibrary.simpleMessage("批大小"), "vector_batch_size_hint": MessageLookupByLibrary.simpleMessage("单次请求能提交的最大块数量"), "vector_dimensions": MessageLookupByLibrary.simpleMessage("向量维度"), "vector_dimensions_hint": MessageLookupByLibrary.simpleMessage("嵌入向量模型输出向量的维度"), "voice": MessageLookupByLibrary.simpleMessage("音色"), "web_search": MessageLookupByLibrary.simpleMessage("联网搜索"), "workspace": MessageLookupByLibrary.simpleMessage("工作空间") }; } ================================================ FILE: lib/gen/l10n.dart ================================================ // GENERATED CODE - DO NOT MODIFY BY HAND import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'intl/messages_all.dart'; // ************************************************************************** // Generator: Flutter Intl IDE plugin // Made by Localizely // ************************************************************************** // ignore_for_file: non_constant_identifier_names, lines_longer_than_80_chars // ignore_for_file: join_return_with_assignment, prefer_final_in_for_each // ignore_for_file: avoid_redundant_argument_values, avoid_escaping_inner_quotes class S { S(); static S? _current; static S get current { assert(_current != null, 'No instance of S was loaded. Try to initialize the S delegate before accessing S.current.'); return _current!; } static const AppLocalizationDelegate delegate = AppLocalizationDelegate(); static Future load(Locale locale) { final name = (locale.countryCode?.isEmpty ?? false) ? locale.languageCode : locale.toString(); final localeName = Intl.canonicalizedLocale(name); return initializeMessages(localeName).then((_) { Intl.defaultLocale = localeName; final instance = S(); S._current = instance; return instance; }); } static S of(BuildContext context) { final instance = S.maybeOf(context); assert(instance != null, 'No instance of S present in the widget tree. Did you add S.delegate in localizationsDelegates?'); return instance!; } static S? maybeOf(BuildContext context) { return Localizations.of(context, S); } /// `ChatBot` String get title { return Intl.message( 'ChatBot', name: 'title', desc: '', args: [], ); } /// `Ok` String get ok { return Intl.message( 'Ok', name: 'ok', desc: '', args: [], ); } /// `Copy` String get copy { return Intl.message( 'Copy', name: 'copy', desc: '', args: [], ); } /// `Edit` String get edit { return Intl.message( 'Edit', name: 'edit', desc: '', args: [], ); } /// `Play` String get play { return Intl.message( 'Play', name: 'play', desc: '', args: [], ); } /// `Source` String get source { return Intl.message( 'Source', name: 'source', desc: '', args: [], ); } /// `Delete` String get delete { return Intl.message( 'Delete', name: 'delete', desc: '', args: [], ); } /// `Images` String get images { return Intl.message( 'Images', name: 'images', desc: '', args: [], ); } /// `Camera` String get camera { return Intl.message( 'Camera', name: 'camera', desc: '', args: [], ); } /// `Gallery` String get gallery { return Intl.message( 'Gallery', name: 'gallery', desc: '', args: [], ); } /// `Settings` String get settings { return Intl.message( 'Settings', name: 'settings', desc: '', args: [], ); } /// `Bot` String get bot { return Intl.message( 'Bot', name: 'bot', desc: '', args: [], ); } /// `Bots` String get bots { return Intl.message( 'Bots', name: 'bots', desc: '', args: [], ); } /// `APIs` String get apis { return Intl.message( 'APIs', name: 'apis', desc: '', args: [], ); } /// `Config` String get config { return Intl.message( 'Config', name: 'config', desc: '', args: [], ); } /// `Open` String get open { return Intl.message( 'Open', name: 'open', desc: '', args: [], ); } /// `Save` String get save { return Intl.message( 'Save', name: 'save', desc: '', args: [], ); } /// `Reset` String get reset { return Intl.message( 'Reset', name: 'reset', desc: '', args: [], ); } /// `Error` String get error { return Intl.message( 'Error', name: 'error', desc: '', args: [], ); } /// `Share` String get share { return Intl.message( 'Share', name: 'share', desc: '', args: [], ); } /// `Clear` String get clear { return Intl.message( 'Clear', name: 'clear', desc: '', args: [], ); } /// `Cancel` String get cancel { return Intl.message( 'Cancel', name: 'cancel', desc: '', args: [], ); } /// `Reanswer` String get reanswer { return Intl.message( 'Reanswer', name: 'reanswer', desc: '', args: [], ); } /// `Citations` String get citations { return Intl.message( 'Citations', name: 'citations', desc: '', args: [], ); } /// `API` String get api { return Intl.message( 'API', name: 'api', desc: '', args: [], ); } /// `Model` String get model { return Intl.message( 'Model', name: 'model', desc: '', args: [], ); } /// `Voice` String get voice { return Intl.message( 'Voice', name: 'voice', desc: '', args: [], ); } /// `Max Tokens` String get max_tokens { return Intl.message( 'Max Tokens', name: 'max_tokens', desc: '', args: [], ); } /// `Temperature` String get temperature { return Intl.message( 'Temperature', name: 'temperature', desc: '', args: [], ); } /// `System Prompts` String get system_prompts { return Intl.message( 'System Prompts', name: 'system_prompts', desc: '', args: [], ); } /// `Streaming Response` String get streaming_response { return Intl.message( 'Streaming Response', name: 'streaming_response', desc: '', args: [], ); } /// `Link` String get link { return Intl.message( 'Link', name: 'link', desc: '', args: [], ); } /// `Name` String get name { return Intl.message( 'Name', name: 'name', desc: '', args: [], ); } /// `New Bot` String get new_bot { return Intl.message( 'New Bot', name: 'new_bot', desc: '', args: [], ); } /// `New API` String get new_api { return Intl.message( 'New API', name: 'new_api', desc: '', args: [], ); } /// `New Chat` String get new_chat { return Intl.message( 'New Chat', name: 'new_chat', desc: '', args: [], ); } /// `API Url` String get api_url { return Intl.message( 'API Url', name: 'api_url', desc: '', args: [], ); } /// `API Key` String get api_key { return Intl.message( 'API Key', name: 'api_key', desc: '', args: [], ); } /// `API Type` String get api_type { return Intl.message( 'API Type', name: 'api_type', desc: '', args: [], ); } /// `Model List` String get model_list { return Intl.message( 'Model List', name: 'model_list', desc: '', args: [], ); } /// `Select Models` String get select_models { return Intl.message( 'Select Models', name: 'select_models', desc: '', args: [], ); } /// `Please enter a name` String get enter_a_name { return Intl.message( 'Please enter a name', name: 'enter_a_name', desc: '', args: [], ); } /// `Please enter a title` String get enter_a_title { return Intl.message( 'Please enter a title', name: 'enter_a_title', desc: '', args: [], ); } /// `Duplicate Bot name` String get duplicate_bot_name { return Intl.message( 'Duplicate Bot name', name: 'duplicate_bot_name', desc: '', args: [], ); } /// `Duplicate API name` String get duplicate_api_name { return Intl.message( 'Duplicate API name', name: 'duplicate_api_name', desc: '', args: [], ); } /// `Please complete all fields` String get complete_all_fields { return Intl.message( 'Please complete all fields', name: 'complete_all_fields', desc: '', args: [], ); } /// `no model` String get no_model { return Intl.message( 'no model', name: 'no_model', desc: '', args: [], ); } /// `All Chats` String get all_chats { return Intl.message( 'All Chats', name: 'all_chats', desc: '', args: [], ); } /// `Chat Title` String get chat_title { return Intl.message( 'Chat Title', name: 'chat_title', desc: '', args: [], ); } /// `Default Config` String get default_config { return Intl.message( 'Default Config', name: 'default_config', desc: '', args: [], ); } /// `Text To Speech` String get text_to_speech { return Intl.message( 'Text To Speech', name: 'text_to_speech', desc: '', args: [], ); } /// `Chat Image Compress` String get chat_image_compress { return Intl.message( 'Chat Image Compress', name: 'chat_image_compress', desc: '', args: [], ); } /// `Config Import and Export` String get config_import_export { return Intl.message( 'Config Import and Export', name: 'config_import_export', desc: '', args: [], ); } /// `Choose Bot` String get choose_bot { return Intl.message( 'Choose Bot', name: 'choose_bot', desc: '', args: [], ); } /// `Choose API` String get choose_api { return Intl.message( 'Choose API', name: 'choose_api', desc: '', args: [], ); } /// `Choose Model` String get choose_model { return Intl.message( 'Choose Model', name: 'choose_model', desc: '', args: [], ); } /// `Quality` String get quality { return Intl.message( 'Quality', name: 'quality', desc: '', args: [], ); } /// `Minimal Width` String get min_width { return Intl.message( 'Minimal Width', name: 'min_width', desc: '', args: [], ); } /// `Minimal Height` String get min_height { return Intl.message( 'Minimal Height', name: 'min_height', desc: '', args: [], ); } /// `Minimal Size` String get min_width_height { return Intl.message( 'Minimal Size', name: 'min_width_height', desc: '', args: [], ); } /// `Export Config` String get export_config { return Intl.message( 'Export Config', name: 'export_config', desc: '', args: [], ); } /// `Import Config` String get import_config { return Intl.message( 'Import Config', name: 'import_config', desc: '', args: [], ); } /// `Exporting...` String get exporting { return Intl.message( 'Exporting...', name: 'exporting', desc: '', args: [], ); } /// `Importing...` String get importing { return Intl.message( 'Importing...', name: 'importing', desc: '', args: [], ); } /// `Empty` String get empty { return Intl.message( 'Empty', name: 'empty', desc: '', args: [], ); } /// `Enable` String get enable { return Intl.message( 'Enable', name: 'enable', desc: '', args: [], ); } /// `Please Input` String get please_input { return Intl.message( 'Please Input', name: 'please_input', desc: '', args: [], ); } /// `The original image will be used if compression fails` String get image_enable_hint { return Intl.message( 'The original image will be used if compression fails', name: 'image_enable_hint', desc: '', args: [], ); } /// `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.` String get image_hint { return Intl.message( '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.', name: 'image_hint', desc: '', args: [], ); } /// `To avoid export failures, it's recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.` String get config_hint { return Intl.message( 'To avoid export failures, it\'s recommended to export the configuration to the Documents directory, or create a ChatBot subdirectory within your Downloads folder.', name: 'config_hint', desc: '', args: [], ); } /// `Exported Successfully` String get exported_successfully { return Intl.message( 'Exported Successfully', name: 'exported_successfully', desc: '', args: [], ); } /// `Imported Successfully` String get imported_successfully { return Intl.message( 'Imported Successfully', name: 'imported_successfully', desc: '', args: [], ); } /// `Please restart App to load the new settings.` String get restart_app { return Intl.message( 'Please restart App to load the new settings.', name: 'restart_app', desc: '', args: [], ); } /// `Can't write to that directory.` String get failed_to_export { return Intl.message( 'Can\'t write to that directory.', name: 'failed_to_export', desc: '', args: [], ); } /// `Generate` String get generate { return Intl.message( 'Generate', name: 'generate', desc: '', args: [], ); } /// `Image Size` String get image_size { return Intl.message( 'Image Size', name: 'image_size', desc: '', args: [], ); } /// `Image Style` String get image_style { return Intl.message( 'Image Style', name: 'image_style', desc: '', args: [], ); } /// `Image Quality` String get image_quality { return Intl.message( 'Image Quality', name: 'image_quality', desc: '', args: [], ); } /// `Base Config` String get base_config { return Intl.message( 'Base Config', name: 'base_config', desc: '', args: [], ); } /// `Optional Config` String get optional_config { return Intl.message( 'Optional Config', name: 'optional_config', desc: '', args: [], ); } /// `Image Generation` String get image_generation { return Intl.message( 'Image Generation', name: 'image_generation', desc: '', args: [], ); } /// `Enter your prompts` String get enter_prompts { return Intl.message( 'Enter your prompts', name: 'enter_prompts', desc: '', args: [], ); } /// `Clone Chat` String get clone_chat { return Intl.message( 'Clone Chat', name: 'clone_chat', desc: '', args: [], ); } /// `Clear Chat` String get clear_chat { return Intl.message( 'Clear Chat', name: 'clear_chat', desc: '', args: [], ); } /// `Chat Settings` String get chat_settings { return Intl.message( 'Chat Settings', name: 'chat_settings', desc: '', args: [], ); } /// `Export Image` String get export_chat_as_image { return Intl.message( 'Export Image', name: 'export_chat_as_image', desc: '', args: [], ); } /// `Cloned Successfully` String get cloned_successfully { return Intl.message( 'Cloned Successfully', name: 'cloned_successfully', desc: '', args: [], ); } /// `Are you sure to clear the chat?` String get ensure_clear_chat { return Intl.message( 'Are you sure to clear the chat?', name: 'ensure_clear_chat', desc: '', args: [], ); } /// `Saved Successfully` String get saved_successfully { return Intl.message( 'Saved Successfully', name: 'saved_successfully', desc: '', args: [], ); } /// `Copied Successfully` String get copied_successfully { return Intl.message( 'Copied Successfully', name: 'copied_successfully', desc: '', args: [], ); } /// `Not implemented yet` String get not_implemented_yet { return Intl.message( 'Not implemented yet', name: 'not_implemented_yet', desc: '', args: [], ); } /// `Empty Link` String get empty_link { return Intl.message( 'Empty Link', name: 'empty_link', desc: '', args: [], ); } /// `Cannot Open` String get cannot_open { return Intl.message( 'Cannot Open', name: 'cannot_open', desc: '', args: [], ); } /// `Invalid Max Tokens` String get invalid_max_tokens { return Intl.message( 'Invalid Max Tokens', name: 'invalid_max_tokens', desc: '', args: [], ); } /// `Invalid Temperature` String get invalid_temperature { return Intl.message( 'Invalid Temperature', name: 'invalid_temperature', desc: '', args: [], ); } /// `Enter your message` String get enter_message { return Intl.message( 'Enter your message', name: 'enter_message', desc: '', args: [], ); } /// `Failed to comprese image` String get image_compress_failed { return Intl.message( 'Failed to comprese image', name: 'image_compress_failed', desc: '', args: [], ); } /// `Set up the TTS first` String get setup_tts_first { return Intl.message( 'Set up the TTS first', name: 'setup_tts_first', desc: '', args: [], ); } /// `Set up the API and Model first` String get setup_api_model_first { return Intl.message( 'Set up the API and Model first', name: 'setup_api_model_first', desc: '', args: [], ); } /// `Other` String get other { return Intl.message( 'Other', name: 'other', desc: '', args: [], ); } /// `Download` String get download { return Intl.message( 'Download', name: 'download', desc: '', args: [], ); } /// `You are up to date` String get up_to_date { return Intl.message( 'You are up to date', name: 'up_to_date', desc: '', args: [], ); } /// `Check for Updates` String get check_for_updates { return Intl.message( 'Check for Updates', name: 'check_for_updates', desc: '', args: [], ); } /// `Delete image` String get delete_image { return Intl.message( 'Delete image', name: 'delete_image', desc: '', args: [], ); } /// `Are you sure to delete the image?` String get ensure_delete_image { return Intl.message( 'Are you sure to delete the image?', name: 'ensure_delete_image', desc: '', args: [], ); } /// `Task` String get task { return Intl.message( 'Task', name: 'task', desc: '', args: [], ); } /// `Document` String get document { return Intl.message( 'Document', name: 'document', desc: '', args: [], ); } /// `Workspace` String get workspace { return Intl.message( 'Workspace', name: 'workspace', desc: '', args: [], ); } /// `Chat Model` String get chat_model { return Intl.message( 'Chat Model', name: 'chat_model', desc: '', args: [], ); } /// `Model Name` String get model_name { return Intl.message( 'Model Name', name: 'model_name', desc: '', args: [], ); } /// `Model Avatar` String get model_avatar { return Intl.message( 'Model Avatar', name: 'model_avatar', desc: '', args: [], ); } /// `Is it a Chat Model?` String get chat_model_hint { return Intl.message( 'Is it a Chat Model?', name: 'chat_model_hint', desc: '', args: [], ); } /// `Title Generation` String get title_generation { return Intl.message( 'Title Generation', name: 'title_generation', desc: '', args: [], ); } /// `If disabled, the user's message will be used as the title` String get title_enable_hint { return Intl.message( 'If disabled, the user\'s message will be used as the title', name: 'title_enable_hint', desc: '', args: [], ); } /// `Prompt` String get title_prompt { return Intl.message( 'Prompt', name: 'title_prompt', desc: '', args: [], ); } /// `Template for the title generation prompt` String get title_prompt_hint { return Intl.message( 'Template for the title generation prompt', name: 'title_prompt_hint', desc: '', args: [], ); } /// `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.` String title_generation_hint(Object text) { return Intl.message( '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.', name: 'title_generation_hint', desc: '', args: [text], ); } /// `Clearing...` String get clearing { return Intl.message( 'Clearing...', name: 'clearing', desc: '', args: [], ); } /// `Clear Data` String get clear_data { return Intl.message( 'Clear Data', name: 'clear_data', desc: '', args: [], ); } /// `Cleared Successfully` String get cleared_successfully { return Intl.message( 'Cleared Successfully', name: 'cleared_successfully', desc: '', args: [], ); } /// `All chat history` String get clear_data_chat { return Intl.message( 'All chat history', name: 'clear_data_chat', desc: '', args: [], ); } /// `All TTS cache files` String get clear_data_audio { return Intl.message( 'All TTS cache files', name: 'clear_data_audio', desc: '', args: [], ); } /// `All generated images` String get clear_data_image { return Intl.message( 'All generated images', name: 'clear_data_image', desc: '', args: [], ); } /// `Set up the embedding vector API and model first` String get setup_vector_first { return Intl.message( 'Set up the embedding vector API and model first', name: 'setup_vector_first', desc: '', args: [], ); } /// `Embedding Vector` String get search_vector { return Intl.message( 'Embedding Vector', name: 'search_vector', desc: '', args: [], ); } /// `Recommended to enable` String get search_vector_hint { return Intl.message( 'Recommended to enable', name: 'search_vector_hint', desc: '', args: [], ); } /// `Timeout` String get search_timeout { return Intl.message( 'Timeout', name: 'search_timeout', desc: '', args: [], ); } /// `Retrieval timeout in milliseconds` String get search_timeout_hint { return Intl.message( 'Retrieval timeout in milliseconds', name: 'search_timeout_hint', desc: '', args: [], ); } /// `Base URL` String get search_searxng_base { return Intl.message( 'Base URL', name: 'search_searxng_base', desc: '', args: [], ); } /// `Additional Parameters` String get search_searxng_extra { return Intl.message( 'Additional Parameters', name: 'search_searxng_extra', desc: '', args: [], ); } /// `For example: engines=google&language=en` String get search_searxng_extra_help { return Intl.message( 'For example: engines=google&language=en', name: 'search_searxng_extra_help', desc: '', args: [], ); } /// `Query Timeout` String get search_timeout_query { return Intl.message( 'Query Timeout', name: 'search_timeout_query', desc: '', args: [], ); } /// `Timeout duration for SearXNG requests` String get search_timeout_query_help { return Intl.message( 'Timeout duration for SearXNG requests', name: 'search_timeout_query_help', desc: '', args: [], ); } /// `Fetch Timeout` String get search_timeout_fetch { return Intl.message( 'Fetch Timeout', name: 'search_timeout_fetch', desc: '', args: [], ); } /// `Timeout duration for fetching web page content` String get search_timeout_fetch_help { return Intl.message( 'Timeout duration for fetching web page content', name: 'search_timeout_fetch_help', desc: '', args: [], ); } /// `Embedding Vector` String get embedding_vector { return Intl.message( 'Embedding Vector', name: 'embedding_vector', desc: '', args: [], ); } /// `Batch Size` String get vector_batch_size { return Intl.message( 'Batch Size', name: 'vector_batch_size', desc: '', args: [], ); } /// `Maximum number of chunks that can be submitted in a single request` String get vector_batch_size_hint { return Intl.message( 'Maximum number of chunks that can be submitted in a single request', name: 'vector_batch_size_hint', desc: '', args: [], ); } /// `Vector Dimensions` String get vector_dimensions { return Intl.message( 'Vector Dimensions', name: 'vector_dimensions', desc: '', args: [], ); } /// `Output dimension of the embedding vector model` String get vector_dimensions_hint { return Intl.message( 'Output dimension of the embedding vector model', name: 'vector_dimensions_hint', desc: '', args: [], ); } /// `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.` String get embedding_vector_info { return Intl.message( '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.', name: 'embedding_vector_info', desc: '', args: [], ); } /// `Document Config` String get document_config { return Intl.message( 'Document Config', name: 'document_config', desc: '', args: [], ); } /// `Number of Chunks` String get chunk_n { return Intl.message( 'Number of Chunks', name: 'chunk_n', desc: '', args: [], ); } /// `Number of chunks to be integrated into the context` String get chunk_n_hint { return Intl.message( 'Number of chunks to be integrated into the context', name: 'chunk_n_hint', desc: '', args: [], ); } /// `Chunk Size` String get chunk_size { return Intl.message( 'Chunk Size', name: 'chunk_size', desc: '', args: [], ); } /// `Maximum number of characters a single chunk can contain` String get chunk_size_hint { return Intl.message( 'Maximum number of characters a single chunk can contain', name: 'chunk_size_hint', desc: '', args: [], ); } /// `Chunk Overlap` String get chunk_overlap { return Intl.message( 'Chunk Overlap', name: 'chunk_overlap', desc: '', args: [], ); } /// `Size of the overlapping portion with the previous chunk` String get chunk_overlap_hint { return Intl.message( 'Size of the overlapping portion with the previous chunk', name: 'chunk_overlap_hint', desc: '', args: [], ); } /// `Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.` String get document_config_hint { return Intl.message( 'Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.', name: 'document_config_hint', desc: '', args: [], ); } /// `Set up the SearXNG first` String get setup_searxng_first { return Intl.message( 'Set up the SearXNG first', name: 'setup_searxng_first', desc: '', args: [], ); } /// `Google Search Mode` String get search_gemini_mode { return Intl.message( 'Google Search Mode', name: 'search_gemini_mode', desc: '', args: [], ); } /// `General Mode` String get search_general_mode { return Intl.message( 'General Mode', name: 'search_general_mode', desc: '', args: [], ); } /// `Web Search` String get web_search { return Intl.message( 'Web Search', name: 'web_search', desc: '', args: [], ); } /// `SearXNG` String get search_searxng { return Intl.message( 'SearXNG', name: 'search_searxng', desc: '', args: [], ); } /// `SearXNG instance` String get search_searxng_hint { return Intl.message( 'SearXNG instance', name: 'search_searxng_hint', desc: '', args: [], ); } /// `Number of Pages` String get search_n { return Intl.message( 'Number of Pages', name: 'search_n', desc: '', args: [], ); } /// `Maximum number of web pages to retrieve` String get search_n_hint { return Intl.message( 'Maximum number of web pages to retrieve', name: 'search_n_hint', desc: '', args: [], ); } /// `Prompt` String get search_prompt { return Intl.message( 'Prompt', name: 'search_prompt', desc: '', args: [], ); } /// `Template for context synthesis` String get search_prompt_hint { return Intl.message( 'Template for context synthesis', name: 'search_prompt_hint', desc: '', args: [], ); } /// `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.` String search_prompt_info(Object pages, Object text) { return Intl.message( '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.', name: 'search_prompt_info', desc: '', args: [pages, text], ); } } class AppLocalizationDelegate extends LocalizationsDelegate { const AppLocalizationDelegate(); List get supportedLocales { return const [ Locale.fromSubtags(languageCode: 'en'), Locale.fromSubtags(languageCode: 'zh', countryCode: 'CN'), ]; } @override bool isSupported(Locale locale) => _isSupported(locale); @override Future load(Locale locale) => S.load(locale); @override bool shouldReload(AppLocalizationDelegate old) => false; bool _isSupported(Locale locale) { for (var supportedLocale in supportedLocales) { if (supportedLocale.languageCode == locale.languageCode) { return true; } } return false; } } ================================================ FILE: lib/image/config.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "../settings/api.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class ConfigTab extends ConsumerStatefulWidget { const ConfigTab({super.key}); @override ConsumerState createState() => _ConfigTabState(); } class _ConfigTabState extends ConsumerState { @override Widget build(BuildContext context) { ref.watch(apisProvider); final s = S.of(context); const padding = EdgeInsets.only(left: 24, right: 24); final primaryColor = Theme.of(context).colorScheme.primary; return ListView( padding: const EdgeInsets.only(top: 16, bottom: 8), children: [ Padding( padding: padding, child: Text( s.base_config, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.api), contentPadding: padding, subtitle: Text(Config.image.api ?? s.empty), onTap: () async { if (Config.apis.isEmpty) return; final api = await Dialogs.select( context: context, list: Config.apis.keys.toList(), selected: Config.image.api, title: s.choose_api, ); if (api == null) return; setState(() => Config.image.api = api); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.model), contentPadding: padding, subtitle: Text(Config.image.model ?? s.empty), onTap: () async { final models = Config.apis[Config.image.api]?.models; if (models == null) return; final model = await Dialogs.select( context: context, selected: Config.image.model, title: s.choose_model, list: models, ); if (model == null) return; setState(() => Config.image.model = model); Config.save(); }, ), Padding( padding: padding, child: Text( s.optional_config, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.image_size), contentPadding: padding, subtitle: Text(Config.image.size ?? s.empty), onTap: () async { final texts = await Dialogs.input( context: context, title: s.image_size, fields: [ InputDialogField( label: s.please_input, text: Config.image.size, ), ], ); if (texts == null) return; final text = texts[0].trim(); final size = text.isEmpty ? null : text; setState(() => Config.image.size = size); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.image_style), contentPadding: padding, subtitle: Text(Config.image.style ?? s.empty), onTap: () async { final texts = await Dialogs.input( context: context, title: s.image_style, fields: [ InputDialogField( label: s.please_input, text: Config.image.style, ), ], ); if (texts == null) return; final text = texts[0].trim(); final style = text.isEmpty ? null : text; setState(() => Config.image.style = style); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.image_quality), contentPadding: padding, subtitle: Text(Config.image.quality ?? s.empty), onTap: () async { final texts = await Dialogs.input( context: context, title: s.image_quality, fields: [ InputDialogField( label: s.please_input, text: Config.image.quality, ), ], ); if (texts == null) return; final text = texts[0].trim(); final quality = text.isEmpty ? null : text; setState(() => Config.image.quality = quality); Config.save(); }, ), ], ); } } ================================================ FILE: lib/image/generate.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "dart:io"; import "dart:convert"; import "package:http/http.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; enum _Status { nothing, loading, generating; bool get isNothing => this == _Status.nothing; bool get isLoading => this == _Status.loading; bool get isGenerating => this == _Status.generating; } class GenerateTab extends ConsumerStatefulWidget { const GenerateTab({super.key}); @override ConsumerState createState() => _GenerateTabState(); } class _GenerateTabState extends ConsumerState with AutomaticKeepAliveClientMixin { final TextEditingController _ctrl = TextEditingController(); final FocusNode _node = FocusNode(); _Status _status = _Status.nothing; final List _images = []; Client? _client; @override void dispose() { _node.dispose(); _ctrl.dispose(); super.dispose(); } @override bool get wantKeepAlive => true; @override Widget build(BuildContext context) { super.build(context); final decoration = BoxDecoration( color: Theme.of(context).colorScheme.surfaceContainerHighest, borderRadius: const BorderRadius.all(Radius.circular(12)), ); return ListView( padding: const EdgeInsets.all(16), children: [ Container( decoration: decoration, padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: TextField( maxLines: 4, focusNode: _node, controller: _ctrl, keyboardType: TextInputType.multiline, decoration: InputDecoration( hintText: S.of(context).enter_prompts, border: InputBorder.none, ), ), ), const SizedBox(height: 12), FilledButton.icon( icon: Icon(_status.isNothing ? Icons.add : Icons.close), label: Text( _status.isNothing ? S.of(context).generate : S.of(context).cancel, ), onPressed: _generate, ), const SizedBox(height: 12), if (!_status.isNothing) LinearProgressIndicator(), if (_images.isNotEmpty) AspectRatio( aspectRatio: _getAspectRatio(), child: Ink( decoration: BoxDecoration( borderRadius: const BorderRadius.all(Radius.circular(12)), image: DecorationImage( image: FileImage(File(_images.first)), fit: BoxFit.fitWidth, ), ), child: InkWell( borderRadius: const BorderRadius.all(Radius.circular(12)), onTap: () => Dialogs.handleImage( context: context, path: _images.first, ), ), ), ), ], ); } Future _generate() async { if (_status.isGenerating) { _status = _Status.nothing; _client?.close(); _client = null; return; } final prompt = _ctrl.text; if (prompt.isEmpty) return; final image = Config.image; final model = image.model; final api = Config.apis[image.api]; if (model == null || api == null) { Util.showSnackBar( context: context, content: Text(S.of(context).setup_api_model_first), ); return; } final apiUrl = api.url; final apiKey = api.key; final endPoint = "$apiUrl/images/generations"; setState(() { _images.clear(); _status = _Status.generating; }); final size = image.size; final style = image.style; final quality = image.quality; final optional = {}; if (size != null) optional["size"] = size; if (style != null) optional["style"] = style; if (quality != null) optional["quality"] = quality; try { _client ??= Client(); final genRes = await _client!.post( Uri.parse(endPoint), headers: { "Authorization": "Bearer $apiKey", "Content-Type": "application/json", }, body: jsonEncode({ ...optional, "model": model, "prompt": prompt, }), ); if (genRes.statusCode != 200) { throw "${genRes.statusCode} ${genRes.body}"; } _status = _Status.loading; final json = jsonDecode(genRes.body); final url = json["data"][0]["url"]; final loadRes = await _client!.get(Uri.parse(url)); if (loadRes.statusCode != 200) { throw "${genRes.statusCode} ${genRes.body}"; } final timestamp = DateTime.now().millisecondsSinceEpoch.toString(); final path = Config.imageFilePath("$timestamp.png"); final file = File(path); await file.writeAsBytes(loadRes.bodyBytes); if (!mounted) return; setState(() => _images.add(path)); } catch (e) { if (!mounted) return; if (_status.isGenerating) { Dialogs.error(context: context, error: e); } } if (!mounted) return; setState(() => _status = _Status.nothing); } double _getAspectRatio() { final size = Config.image.size; if (size == null) return 1; final pos = size.indexOf('x'); if (pos == -1) return 1; final width = size.substring(0, pos); final height = size.substring(pos + 1); final w = int.tryParse(width); final h = int.tryParse(height); if (w == null || h == null) return 1; return w / h; } } ================================================ FILE: lib/image/image.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "config.dart"; import "generate.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class ImagePage extends ConsumerWidget { const ImagePage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return DefaultTabController( length: 2, child: Scaffold( appBar: AppBar( title: Text(S.of(context).image_generation), bottom: TabBar( tabs: [ Tab(text: S.of(context).generate), Tab(text: S.of(context).config), ], ), ), body: TabBarView( children: [ const GenerateTab(), const ConfigTab(), ], ), ), ); } } ================================================ FILE: lib/l10n/intl_en.arb ================================================ { "@@locale": "en", "title": "ChatBot", "ok": "Ok", "copy": "Copy", "edit": "Edit", "play": "Play", "source": "Source", "delete": "Delete", "images": "Images", "camera": "Camera", "gallery": "Gallery", "settings": "Settings", "bot": "Bot", "bots": "Bots", "apis": "APIs", "config": "Config", "open": "Open", "save": "Save", "reset": "Reset", "error": "Error", "share": "Share", "clear": "Clear", "cancel": "Cancel", "reanswer": "Reanswer", "citations": "Citations", "api": "API", "model": "Model", "voice": "Voice", "max_tokens": "Max Tokens", "temperature": "Temperature", "system_prompts": "System Prompts", "streaming_response": "Streaming Response", "link": "Link", "name": "Name", "new_bot": "New Bot", "new_api": "New API", "new_chat": "New Chat", "api_url": "API Url", "api_key": "API Key", "api_type": "API Type", "model_list": "Model List", "select_models": "Select Models", "enter_a_name": "Please enter a name", "enter_a_title": "Please enter a title", "duplicate_bot_name": "Duplicate Bot name", "duplicate_api_name": "Duplicate API name", "complete_all_fields": "Please complete all fields", "no_model": "no model", "all_chats": "All Chats", "chat_title": "Chat Title", "default_config": "Default Config", "text_to_speech": "Text To Speech", "chat_image_compress": "Chat Image Compress", "config_import_export": "Config Import and Export", "choose_bot": "Choose Bot", "choose_api": "Choose API", "choose_model": "Choose Model", "quality": "Quality", "min_width": "Minimal Width", "min_height": "Minimal Height", "min_width_height": "Minimal Size", "export_config": "Export Config", "import_config": "Import Config", "exporting": "Exporting...", "importing": "Importing...", "empty": "Empty", "enable": "Enable", "please_input": "Please Input", "image_enable_hint": "The original image will be used if compression fails", "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.", "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.", "exported_successfully": "Exported Successfully", "imported_successfully": "Imported Successfully", "restart_app": "Please restart App to load the new settings.", "failed_to_export": "Can't write to that directory.", "generate": "Generate", "image_size": "Image Size", "image_style": "Image Style", "image_quality": "Image Quality", "base_config": "Base Config", "optional_config": "Optional Config", "image_generation": "Image Generation", "enter_prompts": "Enter your prompts", "clone_chat": "Clone Chat", "clear_chat": "Clear Chat", "chat_settings": "Chat Settings", "export_chat_as_image": "Export Image", "cloned_successfully": "Cloned Successfully", "ensure_clear_chat": "Are you sure to clear the chat?", "saved_successfully": "Saved Successfully", "copied_successfully": "Copied Successfully", "not_implemented_yet": "Not implemented yet", "empty_link": "Empty Link", "cannot_open": "Cannot Open", "invalid_max_tokens": "Invalid Max Tokens", "invalid_temperature": "Invalid Temperature", "enter_message": "Enter your message", "image_compress_failed": "Failed to comprese image", "setup_tts_first": "Set up the TTS first", "setup_api_model_first": "Set up the API and Model first", "other": "Other", "download": "Download", "up_to_date": "You are up to date", "check_for_updates": "Check for Updates", "delete_image": "Delete image", "ensure_delete_image": "Are you sure to delete the image?", "task": "Task", "document": "Document", "workspace": "Workspace", "chat_model": "Chat Model", "model_name": "Model Name", "model_avatar": "Model Avatar", "chat_model_hint": "Is it a Chat Model?", "title_generation": "Title Generation", "title_enable_hint": "If disabled, the user's message will be used as the title", "title_prompt": "Prompt", "title_prompt_hint": "Template for the title generation prompt", "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.", "clearing": "Clearing...", "clear_data": "Clear Data", "cleared_successfully": "Cleared Successfully", "clear_data_chat": "All chat history", "clear_data_audio": "All TTS cache files", "clear_data_image": "All generated images", "setup_vector_first": "Set up the embedding vector API and model first", "search_vector": "Embedding Vector", "search_vector_hint": "Recommended to enable", "search_timeout": "Timeout", "search_timeout_hint": "Retrieval timeout in milliseconds", "search_searxng_base": "Base URL", "search_searxng_extra": "Additional Parameters", "search_searxng_extra_help": "For example: engines=google&language=en", "search_timeout_query": "Query Timeout", "search_timeout_query_help": "Timeout duration for SearXNG requests", "search_timeout_fetch": "Fetch Timeout", "search_timeout_fetch_help": "Timeout duration for fetching web page content", "embedding_vector": "Embedding Vector", "vector_batch_size": "Batch Size", "vector_batch_size_hint": "Maximum number of chunks that can be submitted in a single request", "vector_dimensions": "Vector Dimensions", "vector_dimensions_hint": "Output dimension of the embedding vector model", "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.", "document_config": "Document Config", "chunk_n": "Number of Chunks", "chunk_n_hint": "Number of chunks to be integrated into the context", "chunk_size": "Chunk Size", "chunk_size_hint": "Maximum number of characters a single chunk can contain", "chunk_overlap": "Chunk Overlap", "chunk_overlap_hint": "Size of the overlapping portion with the previous chunk", "document_config_hint": "Documents are divided into multiple chunks. After search and comparison, the most relevant chunks will be added to the context.", "setup_searxng_first": "Set up the SearXNG first", "search_gemini_mode": "Google Search Mode", "search_general_mode": "General Mode", "web_search": "Web Search", "search_searxng": "SearXNG", "search_searxng_hint": "SearXNG instance", "search_n": "Number of Pages", "search_n_hint": "Maximum number of web pages to retrieve", "search_prompt": "Prompt", "search_prompt_hint": "Template for context synthesis", "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." } ================================================ FILE: lib/l10n/intl_zh_CN.arb ================================================ { "@@locale": "zh_CN", "title": "ChatBot", "ok": "确定", "copy": "拷贝", "edit": "编辑", "play": "播放", "source": "源码", "delete": "删除", "images": "图片", "camera": "相机", "gallery": "图库", "settings": "设置", "bot": "角色", "bots": "角色", "apis": "接口", "config": "配置", "open": "打开", "save": "保存", "reset": "重置", "error": "错误", "share": "分享", "clear": "清空", "cancel": "取消", "reanswer": "重答", "citations": "引用", "api": "接口", "model": "模型", "voice": "音色", "max_tokens": "最大输出", "temperature": "温度", "system_prompts": "系统提示词", "streaming_response": "流式响应", "link": "链接", "name": "名称", "new_bot": "新角色", "new_api": "新接口", "new_chat": "新对话", "api_url": "接口地址", "api_key": "接口密钥", "api_type": "接口类型", "model_list": "模型列表", "select_models": "选择模型", "enter_a_name": "请输入名称", "enter_a_title": "请输入标题", "duplicate_bot_name": "角色名重复", "duplicate_api_name": "接口名重复", "complete_all_fields": "请填写所有字段", "no_model": "无模型", "all_chats": "所有对话", "chat_title": "对话标题", "default_config": "默认配置", "text_to_speech": "文本转语音", "chat_image_compress": "对话图片压缩", "config_import_export": "配置导入导出", "choose_bot": "选择角色", "choose_api": "选择接口", "choose_model": "选择模型", "quality": "质量", "min_width": "最小宽度", "min_height": "最小高度", "min_width_height": "最小宽高", "export_config": "导出配置", "import_config": "导入配置", "exporting": "正在导出...", "importing": "正在导入...", "empty": "空", "enable": "启用", "please_input": "请输入", "image_enable_hint": "压缩失败则将使用原图", "image_hint": "质量范围应在 1-100,质量越低压缩率越高。最小宽度与最小高度用于限制图片缩放,如不清楚,请留空。", "config_hint": "为避免导出失败,建议将配置导出到 Documents 目录,或在 Download 下创建 ChatBot 子目录。", "exported_successfully": "导出成功", "imported_successfully": "导入成功", "restart_app": "请重启应用以加载新配置。", "failed_to_export": "无法在该目录下写入文件。", "generate": "生成", "image_size": "图像尺寸", "image_style": "图像风格", "image_quality": "图像质量", "base_config": "基本配置", "optional_config": "可选配置", "image_generation": "图像生成", "enter_prompts": "请输入提示词", "clone_chat": "复制对话", "clear_chat": "清空对话", "chat_settings": "对话设置", "export_chat_as_image": "导出图片", "cloned_successfully": "复制成功", "ensure_clear_chat": "确定要清空对话?", "saved_successfully": "保存成功", "copied_successfully": "拷贝成功", "not_implemented_yet": "还未实现", "empty_link": "空链接", "cannot_open": "无法打开", "invalid_max_tokens": "非法的最大输出", "invalid_temperature": "非法的温度", "enter_message": "输入你的消息", "image_compress_failed": "图片压缩失败", "setup_tts_first": "请先配置文本转语音", "setup_api_model_first": "请先配置接口和模型", "other": "其他", "download": "下载", "up_to_date": "已是最新版本", "check_for_updates": "检查更新", "delete_image": "删除图片", "ensure_delete_image": "确定要删除图片?", "task": "任务", "document": "文档", "workspace": "工作空间", "chat_model": "对话模型", "model_name": "模型名称", "model_avatar": "模型头像", "chat_model_hint": "是否是对话模型?", "title_generation": "标题生成", "title_enable_hint": "禁用则将以用户消息为标题", "title_prompt": "提示词", "title_prompt_hint": "用于生成标题的提示词模板", "title_generation_hint": "提示词模板中的 {text} 占位变量会被用户消息替换。如不清楚,可留空以使用内置模板。", "clearing": "清理中...", "clear_data": "清理数据", "cleared_successfully": "清理成功", "clear_data_chat": "所有的对话数据", "clear_data_audio": "所有的 TTS 缓存", "clear_data_image": "所有的图片生成结果", "setup_vector_first": "请先配置嵌入向量接口和模型", "search_vector": "嵌入向量", "search_vector_hint": "建议开启", "search_timeout": "超时时间", "search_timeout_hint": "检索的超时毫秒数", "search_searxng_base": "根地址", "search_searxng_extra": "附加参数", "search_searxng_extra_help": "例如:engines=google&language=zh", "search_timeout_query": "检索超时", "search_timeout_query_help": "请求 SearXNG 的超时时间", "search_timeout_fetch": "抓取超时", "search_timeout_fetch_help": "抓取网页内容的超时时间", "embedding_vector": "嵌入向量", "vector_batch_size": "批大小", "vector_batch_size_hint": "单次请求能提交的最大块数量", "vector_dimensions": "向量维度", "vector_dimensions_hint": "嵌入向量模型输出向量的维度", "embedding_vector_info": "批大小受限于接口服务商,建议查询后修改。向量维度为专业选项,非必要请勿填写。", "document_config": "文档配置", "chunk_n": "块数量", "chunk_n_hint": "集成到上下文中的块数量", "chunk_size": "块大小", "chunk_size_hint": "单块能包含的最大字符数", "chunk_overlap": "块重叠", "chunk_overlap_hint": "与上一块重叠部分的大小", "document_config_hint": "文档会被划分为若干块,经过搜索比较后,最合适的几个块会被补充进上下文。", "setup_searxng_first": "请先配置 SearXNG 实例", "search_gemini_mode": "Google Search 模式", "search_general_mode": "通用模式", "web_search": "联网搜索", "search_searxng": "SearXNG", "search_searxng_hint": "SearXNG 实例", "search_n": "网页数量", "search_n_hint": "检索的网页数量上限", "search_prompt": "提示词", "search_prompt_hint": "用于合成上下文的提示词模板", "search_prompt_info": "提示词模板中的 {pages} 占位变量会被网页内容替换,{text} 占位变量会被用户消息替换。如不清楚,可留空以使用内置模板。" } ================================================ FILE: lib/llm/llm.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "web.dart"; import "../config.dart"; import "../chat/chat.dart"; import "../chat/current.dart"; import "../chat/message.dart"; import "../markdown/util.dart"; import "dart:io"; import "dart:math"; import "dart:isolate"; import "dart:convert"; import "package:http/http.dart"; import "package:langchain/langchain.dart"; import "package:audioplayers/audioplayers.dart"; import "package:langchain_openai/langchain_openai.dart"; import "package:langchain_google/langchain_google.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; final llmProvider = AutoDisposeNotifierProvider(LlmNotifier.new); class LlmNotifier extends AutoDisposeNotifier { Client? _ttsClient; Client? _chatClient; AudioPlayer? _player; @override void build() {} void notify() => ref.notifyListeners(); void updateMessage(Message message) => ref.read(messageProvider(message).notifier).notify(); Future tts(Message message) async { dynamic error; final tts = Config.tts; final model = tts.model!; final voice = tts.voice!; final api = Config.apis[tts.api]!; final apiUrl = api.url; final apiKey = api.key; final endPoint = "$apiUrl/audio/speech"; Current.ttsStatus = TtsStatus.loading; updateMessage(message); try { _ttsClient ??= Client(); _player ??= AudioPlayer(); final response = await _ttsClient!.post( Uri.parse(endPoint), headers: { "Authorization": "Bearer $apiKey", "Content-Type": "application/json", }, body: jsonEncode({ "model": model, "voice": voice, "stream": false, "input": markdownToText(message.item.text), }), ); if (response.statusCode != 200) { throw "${response.statusCode} ${response.body}"; } final timestamp = DateTime.now().millisecondsSinceEpoch.toString(); final path = Config.audioFilePath("$timestamp.mp3"); final file = File(path); await file.writeAsBytes(response.bodyBytes); Current.ttsStatus = TtsStatus.playing; updateMessage(message); await _player!.play(DeviceFileSource(path)); await _player!.onPlayerStateChanged.first; } catch (e) { if (!Current.ttsStatus.isNothing) error = e; } Current.ttsStatus = TtsStatus.nothing; updateMessage(message); return error; } void stopTts() { Current.ttsStatus = TtsStatus.nothing; _ttsClient?.close(); _ttsClient = null; _player?.stop(); } Future chat(Message message) async { dynamic error; final item = message.item; final model = Current.model!; final apiUrl = Current.apiUrl!; final apiKey = Current.apiKey!; final apiType = Current.apiType; final messages = Current.messages; Current.chatStatus = ChatStatus.responding; updateMessage(message); notify(); try { final context = await _buildContext(messages); _chatClient = switch (apiType) { "google" => _GoogleClient(baseUrl: apiUrl), _ => Client(), }; BaseChatModel llm = switch (apiType) { "google" => ChatGoogleGenerativeAI( apiKey: apiKey, baseUrl: apiUrl, client: _chatClient, defaultOptions: ChatGoogleGenerativeAIOptions( model: model, temperature: Current.temperature, maxOutputTokens: Current.maxTokens, ), ), _ => ChatOpenAI( apiKey: apiKey, baseUrl: apiUrl, client: _chatClient, defaultOptions: ChatOpenAIOptions( model: model, maxTokens: Current.maxTokens, temperature: Current.temperature, ), ), }; if (Current.stream ?? true) { final stream = llm.stream(context); await for (final chunk in stream) { item.text += chunk.output.content; updateMessage(message); } } else { final result = await llm.invoke(context); item.text += result.output.content; updateMessage(message); } } catch (e) { if (!Current.chatStatus.isNothing) error = e; if (item.text.isEmpty) { if (message.list.length == 1) { messages.length -= 2; ref.read(messagesProvider.notifier).notify(); } else { message.list.removeAt(message.index--); updateMessage(message); } } } Current.chatStatus = ChatStatus.nothing; updateMessage(message); notify(); return error; } void stopChat() { Current.chatStatus = ChatStatus.nothing; _chatClient?.close(); _chatClient = null; } Future _buildContext(List messages) async { final context = []; final system = Current.systemPrompts; final items = messages.map((it) => it.item).toList(); if (items.last.role.isAssistant) items.removeLast(); if (Preferences.search && !Preferences.googleSearch) { items.last = await _buildWebContext(items.last); messages.last.item.citations = items.last.citations; } if (system != null) context.add(ChatMessage.system(system)); for (final item in items) { switch (item.role) { case MessageRole.assistant: context.add(ChatMessage.ai(item.text)); break; case MessageRole.user: if (item.images.isEmpty) { context.add(ChatMessage.humanText(item.text)); break; } context.add(ChatMessage.human(ChatMessageContent.multiModal([ ChatMessageContent.text(item.text), for (final image in item.images) ChatMessageContent.image( mimeType: "image/jpeg", data: image.base64, ), ]))); break; } } return PromptValue.chat(context); } Future _buildWebContext(MessageItem origin) async { final text = origin.text; _chatClient = Client(); final urls = await _getWebPageUrls( text, Config.search.n ?? 64, ); if (urls.isEmpty) throw "No web page found."; final duration = Duration(milliseconds: Config.search.fetchTime ?? 2000); var docs = await Isolate.run(() async { final loader = WebLoader(urls, timeout: duration); return await loader.load(); }); if (docs.isEmpty) throw "No web content retrieved."; if (Config.search.vector ?? false) { final vector = Config.vector; final document = Config.document; final api = Config.apis[vector.api]!; final apiUrl = api.url; final apiKey = api.key; final apiType = api.type; final model = vector.model!; final dimensions = vector.dimensions; final batchSize = vector.batchSize ?? 64; final topK = document.n ?? 8; final chunkSize = document.size ?? 2000; final chunkOverlap = document.overlap ?? 100; final splitter = RecursiveCharacterTextSplitter( chunkSize: chunkSize, chunkOverlap: chunkOverlap, ); _chatClient = switch (apiType) { "google" => _GoogleClient( baseUrl: apiUrl, enableSearch: false, ), _ => _chatClient, }; final embeddings = switch (apiType) { "google" => GoogleGenerativeAIEmbeddings( model: model, apiKey: apiKey, baseUrl: apiUrl, client: _chatClient, batchSize: batchSize, dimensions: dimensions, ), _ => OpenAIEmbeddings( model: model, apiKey: apiKey, baseUrl: apiUrl, client: _chatClient, batchSize: batchSize, dimensions: dimensions, ), }; final vectorStore = MemoryVectorStore( embeddings: embeddings, ); docs = await Isolate.run(() => splitter.splitDocuments(docs)); await vectorStore.addDocuments(documents: docs); docs = await vectorStore.search( query: text, searchType: VectorStoreSearchType.similarity( k: topK, ), ); } final pages = docs.map((it) => "\n${it.pageContent}\n"); final template = Config.search.prompt ?? """ You are now an AI model with internet search capabilities. You can answer user questions based on content from the internet. I will provide you with some information from web pages on the internet. Each tag below contains the content of a web page: {pages} You need to answer the user's question based on the above content: {text} """ .trim(); final context = PromptTemplate.fromTemplate(template).format({ "pages": pages.join("\n\n"), "text": text, }); final item = MessageItem( role: MessageRole.user, text: context, ); for (final doc in docs) { item.citations.add(( type: CitationType.web, content: doc.pageContent, source: doc.metadata["source"], )); } return item; } Future> _getWebPageUrls(String query, int n) async { final searxng = Config.search.searxng!; final baseUrl = searxng.replaceFirst("{text}", query); final badResponse = Response("Request Timeout", 408); final duration = Duration(milliseconds: Config.search.queryTime ?? 3000); Uri uriOf(int i) => Uri.parse("$baseUrl&pageno=$i"); final responses = await Future.wait(List.generate( (n / 16).ceil(), (i) => _chatClient! .get(uriOf(i)) .timeout(duration) .catchError((_) => badResponse), )); final urls = []; for (final res in responses) { if (res.statusCode != 200) continue; final json = jsonDecode(res.body); final results = json["results"]; for (final it in results) { urls.add(it["url"]); } } n = min(n, urls.length); return urls.sublist(0, n); } } Future generateTitle(String text) async { if (!(Config.title.enable ?? false)) return text; final model = Config.title.model; final api = Config.apis[Config.title.api]; if (api == null || model == null) return text; final prompt = Config.title.prompt ?? """ Based on the user input below, generate a concise and relevant title. Note: Only return the title text, without any additional content! Output examples: 1. C Language Discussion 2. 数学问题解答 3. 電影推薦 User input: {text} """ .trim(); final apiUrl = api.url; final apiKey = api.key; final apiType = api.type; final client = switch (apiType) { "google" => _GoogleClient( baseUrl: apiUrl, enableSearch: false, ), _ => Client(), }; BaseChatModel llm = switch (apiType) { "google" => ChatGoogleGenerativeAI( apiKey: apiKey, client: client, baseUrl: apiUrl, defaultOptions: ChatGoogleGenerativeAIOptions( model: model, ), ), _ => ChatOpenAI( apiKey: apiKey, client: client, baseUrl: apiUrl, defaultOptions: ChatOpenAIOptions( model: model, ), ), }; final chain = ChatPromptTemplate.fromTemplate(prompt).pipe(llm); final res = await chain.invoke({"text": text}); return res.output.content.trim(); } class _GoogleClient extends BaseClient { final String baseUrl; final bool enableSearch; final Client _client = Client(); _GoogleClient({ required this.baseUrl, this.enableSearch = true, }); BaseRequest _hook(BaseRequest origin) { if (origin is! Request) { return origin; } final request = Request( origin.method, Uri.parse("${origin.url}".replaceFirst( "https://generativelanguage.googleapis.com/v1beta", baseUrl, )), ); request.headers.addAll(origin.headers); final bodyJson = jsonDecode(origin.body); if (enableSearch && Preferences.search && Preferences.googleSearch) { bodyJson["tools"] = const [ {"google_search": {}}, ]; } request.body = jsonEncode(bodyJson); return request; } @override Future send(BaseRequest request) async { request = _hook(request); return _client.send(request); } @override void close() { super.close(); _client.close(); } } ================================================ FILE: lib/llm/web.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "package:http/http.dart"; import "package:langchain_core/documents.dart"; import "package:langchain_core/document_loaders.dart"; import "package:beautiful_soup_dart/beautiful_soup.dart"; class WebLoader extends BaseDocumentLoader { const WebLoader( this.urls, { this.client, this.requestHeaders, this.timeout = const Duration(seconds: 10), }); final Client? client; final Duration timeout; final List urls; final Map? requestHeaders; @override Future> load() async { const badDocument = Document(pageContent: ""); final docs = await Future.wait(urls.map( (it) => _scrape(it).timeout(timeout).catchError((_) => badDocument))); docs.removeWhere((it) => it.pageContent.isEmpty); return docs; } @override Stream lazyLoad() async* { for (final url in urls) { final doc = await _scrape(url); yield doc; } } Future _scrape(final String url) async { final html = await _fetchUrl(url); final soup = BeautifulSoup(html); final body = soup.body!; body.findAll("script").forEach((e) => e.extract()); body.findAll("style").forEach((e) => e.extract()); final content = body.getText(strip: true); return Document( pageContent: content, metadata: _buildMetadata(url, soup), ); } Future _fetchUrl(final String url) async { final clnt = client ?? Client(); final res = await clnt.get( Uri.parse(url), headers: requestHeaders, ); return res.body; } Map _buildMetadata( final String url, final BeautifulSoup soup, ) { final title = soup.title; final language = soup.find("html")?.getAttrValue("lang"); final description = soup .find("meta", attrs: {"name": "description"})?.getAttrValue("content"); return { "source": url, if (title != null) "title": title.text, if (language != null) "language": language, if (description != null) "description": description.trim(), }; } } ================================================ FILE: lib/main.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "config.dart"; import "gen/l10n.dart"; import "chat/chat.dart"; import "image/image.dart"; import "settings/settings.dart"; import "workspace/workspace.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; import "package:flutter_localizations/flutter_localizations.dart"; void main() { WidgetsFlutterBinding.ensureInitialized(); Config.init().then((_) => runApp(const ProviderScope(child: App()))); } class App extends StatelessWidget { const App({super.key}); @override Widget build(BuildContext context) { return MaterialApp( title: "ChatBot", theme: lightTheme, darkTheme: darkTheme, themeMode: ThemeMode.system, routes: { "/": (context) => ChatPage(), "/image": (context) => ImagePage(), "/settings": (context) => SettingsPage(), "/workspace": (context) => WorkspacePage(), }, localizationsDelegates: const [ S.delegate, GlobalWidgetsLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: S.delegate.supportedLocales, ); } } ================================================ FILE: lib/markdown/code.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:markdown/markdown.dart" as md; import "package:flutter_markdown/flutter_markdown.dart"; import "package:flutter_highlighter/flutter_highlighter.dart"; import "package:flutter_highlighter/themes/atom-one-dark.dart"; import "package:flutter_highlighter/themes/atom-one-light.dart"; final codeDarkTheme = Map.of(atomOneDarkTheme) ..["root"] = TextStyle( color: Colors.white.withOpacity(0.7), backgroundColor: Colors.transparent); final codeLightTheme = Map.of(atomOneLightTheme) ..["root"] = TextStyle( color: Colors.black.withOpacity(0.7), backgroundColor: Colors.transparent); class CodeBlockBuilder extends MarkdownElementBuilder { var language = ""; final BuildContext context; CodeBlockBuilder({required this.context}); @override void visitElementBefore(md.Element element) { final code = element.children?.first; if (code is md.Element) { final lang = code.attributes["class"]; if (lang != null) language = lang.substring(9); } super.visitElementBefore(element); } @override Widget? visitText(md.Text text, TextStyle? preferredStyle) { final colorScheme = Theme.of(context).colorScheme; final theme = switch (colorScheme.brightness) { Brightness.light => codeLightTheme, Brightness.dark => codeDarkTheme, }; final content = text.textContent.trim(); return IntrinsicWidth( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Card.filled( margin: EdgeInsets.zero, color: theme == codeDarkTheme ? Colors.black.withOpacity(0.3) : Colors.blueGrey.withOpacity(0.3), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.zero, ), child: Row( children: [ const SizedBox(width: 16), Text(language), const Expanded(child: SizedBox()), const SizedBox(width: 8), InkWell( onTap: () => Util.copyText( context: context, text: content, ), child: Padding( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: Text( S.of(context).copy, style: Theme.of(context).textTheme.labelSmall, ), ), ), ], ), ), SingleChildScrollView( scrollDirection: Axis.horizontal, child: HighlightView( content, tabSize: 2, theme: theme, language: language, padding: const EdgeInsets.all(8), ), ), ], ), ); } } class CodeBlockBuilder2 extends MarkdownElementBuilder { var language = ""; final BuildContext context; CodeBlockBuilder2({required this.context}); @override void visitElementBefore(md.Element element) { final code = element.children?.first; if (code is md.Element) { final lang = code.attributes["class"]; if (lang != null) language = lang.substring(9); } super.visitElementBefore(element); } @override Widget? visitText(md.Text text, TextStyle? preferredStyle) { final colorScheme = Theme.of(context).colorScheme; final theme = switch (colorScheme.brightness) { Brightness.light => codeLightTheme, Brightness.dark => codeDarkTheme, }; final content = text.textContent.trim(); return IntrinsicWidth( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ ColoredBox( color: theme == codeDarkTheme ? Colors.black.withOpacity(0.3) : Colors.blueGrey.withOpacity(0.3), child: Row( children: [ const SizedBox(width: 16), Text(language), const Expanded(child: SizedBox()), const SizedBox(width: 8), Padding( padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 16), child: Text( S.current.copy, style: Theme.of(context).textTheme.labelSmall, ), ), ], ), ), HighlightView( content, tabSize: 2, theme: theme, language: language, padding: const EdgeInsets.all(8), ), ], ), ); } } ================================================ FILE: lib/markdown/latex.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "package:markdown/markdown.dart"; import "package:flutter/material.dart" hide Element; import "package:flutter_math_fork/flutter_math.dart"; import "package:flutter_markdown/flutter_markdown.dart"; class LatexElementBuilder extends MarkdownElementBuilder { final TextStyle? textStyle; final double? textScaleFactor; LatexElementBuilder({ this.textStyle, this.textScaleFactor, }); @override Widget visitElementAfterWithContext( BuildContext context, Element element, TextStyle? preferredStyle, TextStyle? parentStyle, ) { final String text = element.textContent.trim(); if (text.isEmpty) return const SizedBox(); final mathStyle = switch (element.attributes["MathStyle"]) { "display" => MathStyle.display, _ => MathStyle.text, }; return SingleChildScrollView( scrollDirection: Axis.horizontal, clipBehavior: Clip.antiAlias, child: Math.tex( text, mathStyle: mathStyle, textStyle: textStyle, textScaleFactor: textScaleFactor, ), ); } } class LatexElementBuilder2 extends MarkdownElementBuilder { final TextStyle? textStyle; final double? textScaleFactor; LatexElementBuilder2({ this.textStyle, this.textScaleFactor, }); @override Widget visitElementAfterWithContext( BuildContext context, Element element, TextStyle? preferredStyle, TextStyle? parentStyle, ) { final String text = element.textContent.trim(); if (text.isEmpty) return const SizedBox(); final mathStyle = switch (element.attributes["MathStyle"]) { "display" => MathStyle.display, _ => MathStyle.text, }; return Wrap( runSpacing: 8, crossAxisAlignment: WrapCrossAlignment.center, children: Math.tex( text, mathStyle: mathStyle, textStyle: textStyle, textScaleFactor: textScaleFactor, ).texBreak().parts, ); } } class _LatexDelimiter { final String left; final String right; final bool display; const _LatexDelimiter({ required this.left, required this.right, required this.display, }); } class LatexInlineSyntax extends InlineSyntax { static const _delimiters = [ _LatexDelimiter(left: r"$$", right: r"$$", display: true), _LatexDelimiter(left: r"$", right: r"$", display: false), _LatexDelimiter(left: r"\[", right: r"\]", display: true), _LatexDelimiter(left: r"\(", right: r"\)", display: false), _LatexDelimiter(left: r"\ce{", right: "}", display: false), _LatexDelimiter(left: r"\pu{", right: "}", display: false), ]; static String _buildPattern() => _delimiters.map((d) { final right = RegExp.escape(d.right); final left = RegExp.escape(d.left); return "$left([\\s\\S]+?)$right"; }).join("|"); LatexInlineSyntax() : super(_buildPattern()); @override bool onMatch(InlineParser parser, Match match) { final fullMatch = match[0]!; final delimiter = _delimiters.firstWhere( (d) => fullMatch.startsWith(d.left) && fullMatch.endsWith(d.right), orElse: () => _delimiters[1], ); final content = fullMatch.substring( delimiter.left.length, fullMatch.length - delimiter.right.length, ); final text = Element.text("latex", content) ..attributes["MathStyle"] = delimiter.display ? "display" : "text"; parser.addNode(text); return true; } } class LatexBlockSyntax extends BlockSyntax { static final dollarPattern = RegExp(r"^\$\$\s*$"); static final bracketPattern = RegExp(r"^\\\[\s*$"); static final endDollarPattern = RegExp(r"^\$\$\s*$"); static final endBracketPattern = RegExp(r"^\\\]\s*$"); @override RegExp get pattern => RegExp(r"^\$\$|^\\\["); @override bool canParse(BlockParser parser) { return dollarPattern.hasMatch(parser.current.content) || bracketPattern.hasMatch(parser.current.content); } @override Node parse(BlockParser parser) { final lines = []; final start = parser.current.content; final isDollar = dollarPattern.hasMatch(start); parser.advance(); while (!parser.isDone) { final line = parser.current.content; if ((isDollar && endDollarPattern.hasMatch(line)) || (!isDollar && endBracketPattern.hasMatch(line))) { parser.advance(); break; } lines.add(line); parser.advance(); } final text = Element.text("latex", lines.join("\n").trim()); text.attributes["MathStyle"] = "display"; return Element("p", [text]); } } ================================================ FILE: lib/markdown/util.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "latex.dart"; import "package:markdown/markdown.dart"; final mdExtensionSet = ExtensionSet( [ LatexBlockSyntax(), const TableSyntax(), const FootnoteDefSyntax(), const FencedCodeBlockSyntax(), const OrderedListWithCheckboxSyntax(), const UnorderedListWithCheckboxSyntax(), ], [ InlineHtmlSyntax(), LatexInlineSyntax(), StrikethroughSyntax(), AutolinkExtensionSyntax() ], ); String markdownToText(String markdown) { final doc = Document( extensionSet: mdExtensionSet, ); final buff = StringBuffer(); final nodes = doc.parse(markdown); for (final node in nodes) { if (node is Element) { buff.write(_elementToText(node)); } } return buff.toString().trim(); } String _elementToText(Element element) { final buff = StringBuffer(); final nodes = element.children ?? []; if (element.tag == "ul") { for (final node in nodes) { if (node is Element && node.tag == "li") { buff.write(_elementToText(node)); } } } else if (element.tag == "ol") { int index = 1; for (final node in nodes) { if (node is Element && node.tag == "li") { buff.write("${index++}. ${_elementToText(node)}"); } } } else { for (final node in nodes) { if (node is Text) { buff.write(node.text); } else if (node is Element) { final tag = node.tag; if (tag == "code") continue; if (tag == "latex") continue; if (tag == "th" || tag == "td") continue; buff.write(_elementToText(node)); } buff.write("\n"); } } return buff.toString(); } ================================================ FILE: lib/settings/api.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "dart:convert"; import "package:http/http.dart"; import "package:flutter/material.dart"; import "package:animate_do/animate_do.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; final apisProvider = NotifierProvider.autoDispose(ApisNotifier.new); class ApisNotifier extends AutoDisposeNotifier { @override void build() {} void notify() => ref.notifyListeners(); } class ApisTab extends ConsumerWidget { const ApisTab({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(apisProvider); final apis = Config.apis.keys.toList(); return Stack( children: [ ListView.separated( padding: const EdgeInsets.all(16), separatorBuilder: (context, index) => const SizedBox(height: 12), itemCount: apis.length, itemBuilder: (context, index) => Card.filled( margin: EdgeInsets.zero, child: ListTile( title: Text( apis[index], overflow: TextOverflow.ellipsis, ), leading: const Icon(Icons.api), contentPadding: const EdgeInsets.only(left: 16, right: 8), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => ApiSettings(api: apis[index]), )), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(12)), ), ), ), ), Positioned( right: 16, bottom: 16, child: FloatingActionButton.extended( heroTag: "api", icon: const Icon(Icons.api), label: Text(S.of(context).new_api), onPressed: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => ApiSettings(), )), ), ), ], ); } } class ApiSettings extends ConsumerStatefulWidget { final String? api; const ApiSettings({ super.key, this.api, }); @override ConsumerState createState() => _ApiSettingsState(); } class _ApiSettingsState extends ConsumerState { String? _type; Client? _client; bool _isFetching = false; late final TextEditingController _nameCtrl; late final TextEditingController _modelsCtrl; late final TextEditingController _apiUrlCtrl; late final TextEditingController _apiKeyCtrl; @override void initState() { super.initState(); final api = widget.api; final config = Config.apis[api]; _type = config?.type; _nameCtrl = TextEditingController(text: api); _apiUrlCtrl = TextEditingController(text: config?.url); _apiKeyCtrl = TextEditingController(text: config?.key); _modelsCtrl = TextEditingController(text: config?.models.join(", ")); } @override void dispose() { _modelsCtrl.dispose(); _apiKeyCtrl.dispose(); _apiUrlCtrl.dispose(); _nameCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final api = widget.api; return Scaffold( appBar: AppBar( title: Text(S.of(context).api), ), body: ListView( padding: const EdgeInsets.only(left: 16, right: 16), children: [ const SizedBox(height: 16), Row( children: [ Expanded( child: DropdownButtonFormField( value: _type, items: >[ DropdownMenuItem( value: "openai", child: const Text("OpenAI"), ), DropdownMenuItem( value: "google", child: const Text("Google"), ), ], isExpanded: true, hint: Text(S.of(context).api_type), onChanged: (it) => setState(() => _type = it), decoration: const InputDecoration( border: OutlineInputBorder(), ), ), ), const SizedBox(width: 12), Expanded( child: TextField( controller: _nameCtrl, decoration: InputDecoration( labelText: S.of(context).name, border: const OutlineInputBorder(), ), ), ), ], ), const SizedBox(height: 16), TextField( controller: _apiUrlCtrl, decoration: InputDecoration( labelText: S.of(context).api_url, border: const OutlineInputBorder(), ), ), const SizedBox(height: 16), TextField( controller: _apiKeyCtrl, decoration: InputDecoration( labelText: S.of(context).api_key, border: const OutlineInputBorder(), ), ), const SizedBox(height: 16), Row( children: [ Expanded( child: TextField( maxLines: 4, controller: _modelsCtrl, decoration: InputDecoration( labelText: S.of(context).model_list, alignLabelWithHint: true, border: const OutlineInputBorder(), ), ), ), const SizedBox(width: 12), Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Spin( infinite: true, animate: _isFetching, duration: Duration(seconds: 1), child: IconButton.outlined( icon: const Icon(Icons.sync), onPressed: _fetchModels, ), ), const SizedBox(height: 16), IconButton.outlined( icon: const Icon(Icons.edit), onPressed: _editModels, ), ], ) ], ), const SizedBox(height: 12), Row( children: [ Expanded( flex: 1, child: FilledButton.tonal( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), ), const SizedBox(width: 6), if (api != null) ...[ const SizedBox(width: 6), Expanded( flex: 1, child: FilledButton( style: FilledButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.error, foregroundColor: Theme.of(context).colorScheme.onError, ), child: Text(S.of(context).delete), onPressed: () { Config.apis.remove(api); Config.save(); ref.read(apisProvider.notifier).notify(); Navigator.of(context).pop(); }, ), ), const SizedBox(width: 6), ], const SizedBox(width: 6), Expanded( flex: 1, child: FilledButton( onPressed: _save, child: Text(S.of(context).save), ), ), ], ), const SizedBox(height: 16), ], ), ); } Future _fetchModels() async { if (_isFetching) { _isFetching = false; _client?.close(); _client = null; return; } final url = _apiUrlCtrl.text; final key = _apiKeyCtrl.text; final endPoint = switch (_type) { "google" => "$url/models?key=$key", _ => "$url/models", }; if (url.isEmpty || key.isEmpty) { Util.showSnackBar( context: context, content: Text(S.of(context).complete_all_fields), ); return; } setState(() => _isFetching = true); try { _client ??= Client(); final response = await _client!.get( Uri.parse(endPoint), headers: switch (_type) { "google" => null, _ => {"Authorization": "Bearer $key"}, }, ); if (response.statusCode != 200) { throw "${response.statusCode} ${response.body}"; } final json = jsonDecode(response.body); List models = switch (_type) { "google" => [ for (final cell in json["models"]) cell["name"].substring(7), ], _ => [for (final cell in json["data"]) cell["id"]], }; _modelsCtrl.text = models.join(", "); } catch (e) { if (_isFetching && mounted) { Dialogs.error(context: context, error: e); } } setState(() => _isFetching = false); } Future _editModels() async { final text = _modelsCtrl.text; if (text.isEmpty) return; final models = text.split(',').map((it) => it.trim()).toList(); models.removeWhere((e) => e.isEmpty); final chosen = {for (final it in models) it: true}; if (chosen.isEmpty) return; final result = await showModalBottomSheet( context: context, scrollControlDisabledMaxHeightRatio: 0.7, builder: (context) => StatefulBuilder( builder: (context, setState) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DialogHeader(title: S.of(context).select_models), const Divider(height: 1), Flexible( child: ListView.builder( shrinkWrap: true, itemCount: chosen.length, itemBuilder: (context, index) => CheckboxListTile( title: Text(models[index]), value: chosen[models[index]], contentPadding: const EdgeInsets.only(left: 24, right: 16), onChanged: (value) => setState(() => chosen[models[index]] = value ?? false), ), ), ), const Divider(height: 1), DialogFooter( children: [ TextButton( child: Text(S.of(context).ok), onPressed: () => Navigator.of(context).pop(true), ), TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( child: Text(S.of(context).clear), onPressed: () => setState( () => chosen.forEach((it, _) => chosen[it] = false)), ), ], ), ], ), ), ); if (!(result ?? false)) return; _modelsCtrl.text = [ for (final pair in chosen.entries) if (pair.value) pair.key ].join(", "); } void _save() { final name = _nameCtrl.text; final models = _modelsCtrl.text; final apiUrl = _apiUrlCtrl.text; final apiKey = _apiKeyCtrl.text; if (name.isEmpty || models.isEmpty || apiUrl.isEmpty || apiKey.isEmpty) { Util.showSnackBar( context: context, content: Text(S.of(context).complete_all_fields), ); return; } final api = widget.api; if (Config.apis.containsKey(name) && (api == null || name != api)) { Util.showSnackBar( context: context, content: Text(S.of(context).duplicate_api_name), ); return; } if (api != null) Config.apis.remove(api); final modelList = models.split(',').map((e) => e.trim()).toList(); modelList.removeWhere((e) => e.isEmpty); Config.apis[name] = ApiConfig( url: apiUrl, key: apiKey, type: _type, models: modelList, ); Config.save(); ref.read(apisProvider.notifier).notify(); Navigator.of(context).pop(); } } ================================================ FILE: lib/settings/bot.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; final botsProvider = NotifierProvider.autoDispose(BotsNotifier.new); class BotsNotifier extends AutoDisposeNotifier { @override void build() {} void notify() => ref.notifyListeners(); } class BotsTab extends ConsumerWidget { const BotsTab({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(botsProvider); final bots = Config.bots.keys.toList(); return Stack( children: [ ListView.separated( padding: const EdgeInsets.all(16), separatorBuilder: (context, index) => const SizedBox(height: 12), itemCount: bots.length, itemBuilder: (context, index) => Card.filled( margin: EdgeInsets.zero, child: ListTile( title: Text( bots[index], overflow: TextOverflow.ellipsis, ), leading: const Icon(Icons.smart_toy), contentPadding: const EdgeInsets.only(left: 16, right: 8), onTap: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => BotSettings(bot: bots[index]), )), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(12)), ), ), ), ), Positioned( right: 16, bottom: 16, child: FloatingActionButton.extended( heroTag: "bot", icon: const Icon(Icons.smart_toy), label: Text(S.of(context).new_bot), onPressed: () => Navigator.of(context).push(MaterialPageRoute( builder: (context) => BotSettings(), )), ), ), ], ); } } class BotSettings extends ConsumerStatefulWidget { final String? bot; const BotSettings({ super.key, this.bot, }); @override ConsumerState createState() => _BotSettingsState(); } class _BotSettingsState extends ConsumerState { bool? _stream; late final TextEditingController _nameCtrl; late final TextEditingController _maxTokensCtrl; late final TextEditingController _temperatureCtrl; late final TextEditingController _systemPromptsCtrl; @override void initState() { super.initState(); final bot = widget.bot; final config = Config.bots[bot]; _stream = config?.stream; _nameCtrl = TextEditingController(text: bot); _maxTokensCtrl = TextEditingController(text: config?.maxTokens?.toString()); _temperatureCtrl = TextEditingController(text: config?.temperature?.toString()); _systemPromptsCtrl = TextEditingController(text: config?.systemPrompts); } @override void dispose() { _systemPromptsCtrl.dispose(); _temperatureCtrl.dispose(); _maxTokensCtrl.dispose(); _nameCtrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { final bot = widget.bot; return Scaffold( appBar: AppBar( title: Text(S.of(context).bot), ), body: ListView( padding: const EdgeInsets.only(left: 16, right: 16), children: [ const SizedBox(height: 16), TextField( controller: _nameCtrl, decoration: InputDecoration( labelText: S.of(context).name, border: const OutlineInputBorder(), ), ), const SizedBox(height: 16), Row( children: [ Expanded( child: TextField( controller: _temperatureCtrl, keyboardType: TextInputType.number, decoration: InputDecoration( labelText: S.of(context).temperature, border: const OutlineInputBorder(), ), ), ), const SizedBox(width: 12), Expanded( child: TextField( controller: _maxTokensCtrl, keyboardType: TextInputType.number, decoration: InputDecoration( labelText: S.of(context).max_tokens, border: const OutlineInputBorder(), ), ), ), ], ), const SizedBox(height: 16), TextField( maxLines: 4, controller: _systemPromptsCtrl, decoration: InputDecoration( alignLabelWithHint: true, labelText: S.of(context).system_prompts, border: const OutlineInputBorder(), ), ), const SizedBox(height: 12), Row( children: [ Flexible( child: SwitchListTile( value: _stream ?? true, title: Text(S.of(context).streaming_response), onChanged: (value) => setState(() => _stream = value), contentPadding: const EdgeInsets.only(left: 8, right: 8), ), ), ], ), const SizedBox(height: 12), Row( children: [ Expanded( child: FilledButton.tonal( child: Text(S.of(context).reset), onPressed: () { _maxTokensCtrl.text = ""; _temperatureCtrl.text = ""; _systemPromptsCtrl.text = ""; setState(() => _stream = null); }, ), ), const SizedBox(width: 6), if (bot != null) ...[ const SizedBox(width: 6), Expanded( child: FilledButton( style: FilledButton.styleFrom( backgroundColor: Theme.of(context).colorScheme.error, foregroundColor: Theme.of(context).colorScheme.onError, ), child: Text(S.of(context).delete), onPressed: () async { Config.bots.remove(bot); Config.save(); ref.read(botsProvider.notifier).notify(); Navigator.of(context).pop(); }, ), ), const SizedBox(width: 6), ], const SizedBox(width: 6), Expanded( child: FilledButton( onPressed: _save, child: Text(S.of(context).save), ), ), ], ), const SizedBox(height: 16), ], ), ); } void _save() { final name = _nameCtrl.text; if (name.isEmpty) { Util.showSnackBar( context: context, content: Text(S.of(context).enter_a_name), ); return; } final bot = widget.bot; if (Config.bots.containsKey(name) && (bot == null || name != bot)) { Util.showSnackBar( context: context, content: Text(S.of(context).duplicate_bot_name), ); return; } final maxTokens = int.tryParse(_maxTokensCtrl.text); final temperature = double.tryParse(_temperatureCtrl.text); if (_maxTokensCtrl.text.isNotEmpty && maxTokens == null) { Util.showSnackBar( context: context, content: Text(S.of(context).invalid_max_tokens), ); return; } if (_temperatureCtrl.text.isNotEmpty && temperature == null) { Util.showSnackBar( context: context, content: Text(S.of(context).invalid_temperature), ); return; } if (bot != null) Config.bots.remove(bot); final text = _systemPromptsCtrl.text; final systemPrompts = text.isEmpty ? null : text; Config.bots[name] = BotConfig( stream: _stream, maxTokens: maxTokens, temperature: temperature, systemPrompts: systemPrompts, ); Config.save(); ref.read(botsProvider.notifier).notify(); Navigator.of(context).pop(); } } ================================================ FILE: lib/settings/config.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "bot.dart"; import "api.dart"; import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "../chat/chat.dart"; import "../chat/current.dart"; import "dart:io"; import "package:flutter/services.dart"; import "package:flutter/material.dart"; import "package:file_picker/file_picker.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class ConfigTab extends ConsumerStatefulWidget { const ConfigTab({super.key}); @override ConsumerState createState() => _ConfigTabState(); } class _ConfigTabState extends ConsumerState { @override Widget build(BuildContext context) { ref.watch(botsProvider); ref.watch(apisProvider); final s = S.of(context); const padding = EdgeInsets.only(left: 24, right: 24); final primaryColor = Theme.of(context).colorScheme.primary; return ListView( padding: const EdgeInsets.only(top: 16, bottom: 8), children: [ Padding( padding: padding, child: Text( s.default_config, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.bot), contentPadding: padding, subtitle: Text(Config.core.bot ?? s.empty), onTap: () async { if (Config.bots.isEmpty) return; final bot = await Dialogs.select( context: context, list: Config.bots.keys.toList(), selected: Config.core.bot, title: s.choose_bot, ); if (bot == null) return; setState(() => Config.core.bot = bot); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.api), contentPadding: padding, subtitle: Text(Config.core.api ?? s.empty), onTap: () async { if (Config.apis.isEmpty) return; final api = await Dialogs.select( context: context, list: Config.apis.keys.toList(), selected: Config.core.api, title: s.choose_api, ); if (api == null) return; setState(() => Config.core.api = api); ref.read(chatProvider.notifier).notify(); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.model), contentPadding: padding, subtitle: Text(Config.core.model ?? s.empty), onTap: () async { final models = Config.apis[Config.core.api]?.models; if (models == null) return; final model = await Dialogs.select( context: context, selected: Config.core.model, title: s.choose_model, list: models, ); if (model == null) return; setState(() => Config.core.model = model); ref.read(chatProvider.notifier).notify(); Config.save(); }, ), Padding( padding: padding, child: Text( s.text_to_speech, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.api), contentPadding: padding, subtitle: Text(Config.tts.api ?? s.empty), onTap: () async { if (Config.apis.isEmpty) return; final api = await Dialogs.select( context: context, list: Config.apis.keys.toList(), selected: Config.tts.api, title: s.choose_api, ); if (api == null) return; setState(() => Config.tts.api = api); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.model), contentPadding: padding, subtitle: Text(Config.tts.model ?? s.empty), onTap: () async { final models = Config.apis[Config.tts.api]?.models; if (models == null) return; final model = await Dialogs.select( context: context, selected: Config.tts.model, title: s.choose_model, list: models, ); if (model == null) return; setState(() => Config.tts.model = model); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.voice), contentPadding: padding, subtitle: Text(Config.tts.voice ?? s.empty), onTap: () async { final texts = await Dialogs.input( context: context, title: s.voice, fields: [ InputDialogField( label: s.please_input, text: Config.tts.voice, ), ], ); if (texts == null) return; String? voice; final text = texts[0].trim(); if (text.isNotEmpty) voice = text; setState(() => Config.tts.voice = voice); Config.save(); }, ), Padding( padding: padding, child: Text( s.chat_image_compress, style: TextStyle(color: primaryColor), ), ), CheckboxListTile( title: Text(s.enable), contentPadding: const EdgeInsets.only(left: 24, right: 16), value: Config.cic.enable ?? true, subtitle: Text(s.image_enable_hint), onChanged: (value) { setState(() => Config.cic.enable = value); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.quality), contentPadding: padding, subtitle: Text(Config.cic.quality?.toString() ?? s.empty), onTap: () async { final texts = await Dialogs.input( context: context, title: s.quality, fields: [ InputDialogField( label: s.please_input, text: Config.cic.quality?.toString(), ), ], ); if (texts == null) return; int? quality; final text = texts[0].trim(); if (text.isNotEmpty) { quality = int.tryParse(text); if (quality == null) return; } setState(() => Config.cic.quality = quality); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.min_width_height), contentPadding: padding, subtitle: Text( "${Config.cic.minWidth ?? s.empty} x " "${Config.cic.minHeight ?? s.empty}", ), onTap: () async { final texts = await Dialogs.input( context: context, title: s.min_width_height, fields: [ InputDialogField( label: s.min_width, text: Config.cic.minWidth?.toString(), ), InputDialogField( label: s.min_height, text: Config.cic.minHeight?.toString(), ), ], ); if (texts == null) return; int? minWidth; int? minHeight; final text1 = texts[0].trim(); final text2 = texts[1].trim(); if (text1.isNotEmpty) { minWidth = int.tryParse(text1); if (minWidth == null) return; } if (text2.isNotEmpty) { minHeight = int.tryParse(text2); if (minHeight == null) return; } setState(() { Config.cic.minWidth = minWidth; Config.cic.minHeight = minHeight; }); Config.save(); }, ), const SizedBox(height: 4), InfoCard(info: s.image_hint), const SizedBox(height: 16), Padding( padding: padding, child: Text( s.config_import_export, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.import_config), contentPadding: padding, onTap: () async { try { final result = await FilePicker.platform.pickFiles(); if (result == null || !context.mounted) return; Dialogs.loading(context: context, hint: s.importing); final from = result.files.single.path!; await Backup.importConfig(from); if (!context.mounted) return; Navigator.of(context).pop(); await showDialog( context: context, builder: (context) => AlertDialog( title: Text(s.imported_successfully), content: Text(s.restart_app), actions: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(s.ok), ) ], ), ); SystemNavigator.pop(); } catch (e) { if (!context.mounted) return; Navigator.of(context).pop(); Dialogs.error(context: context, error: e); } }, ), const Divider(height: 1), ListTile( title: Text(s.export_config), contentPadding: padding, onTap: () async { try { final to = await FilePicker.platform.getDirectoryPath(); if (to == null || !context.mounted) return; Dialogs.loading(context: context, hint: s.exporting); await Backup.exportConfig(to); if (!context.mounted) return; Navigator.of(context).pop(); Util.showSnackBar( context: context, content: Text(s.exported_successfully), ); } on PathAccessException { Navigator.of(context).pop(); showDialog( context: context, builder: (context) => AlertDialog( title: Text(s.error), content: Text(s.failed_to_export), actions: [ TextButton( child: Text(s.ok), onPressed: () => Navigator.of(context).pop(), ), ], ), ); } catch (e) { Navigator.of(context).pop(); Dialogs.error(context: context, error: e); } }, ), const SizedBox(height: 4), InfoCard(info: s.config_hint), const SizedBox(height: 16), Padding( padding: padding, child: Text( s.other, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.clear_data), onTap: _clearData, contentPadding: padding, ), const Divider(height: 1), ListTile( title: Text(s.check_for_updates), onTap: () => Util.checkUpdate( context: context, notify: true, ), contentPadding: padding, ), ], ); } Future _clearData() async { bool chat = false; bool audio = false; bool image = false; final s = S.of(context); final result = await showModalBottomSheet( context: context, builder: (context) => StatefulBuilder( builder: (context, setState) => Column( mainAxisSize: MainAxisSize.min, children: [ DialogHeader(title: s.clear_data), const Divider(height: 1), CheckboxListTile( value: chat, title: Text("Chat"), subtitle: Text(s.clear_data_chat), onChanged: (it) => setState(() => chat = it ?? false), contentPadding: const EdgeInsets.only(left: 24, right: 16), ), CheckboxListTile( value: audio, title: Text("Audio"), subtitle: Text(s.clear_data_audio), onChanged: (it) => setState(() => audio = it ?? false), contentPadding: const EdgeInsets.only(left: 24, right: 16), ), CheckboxListTile( value: image, title: Text("Image"), subtitle: Text(s.clear_data_image), onChanged: (it) => setState(() => image = it ?? false), contentPadding: const EdgeInsets.only(left: 24, right: 16), ), const Divider(height: 1), DialogFooter( children: [ TextButton( child: Text(s.ok), onPressed: () => Navigator.of(context).pop(true), ), TextButton( onPressed: Navigator.of(context).pop, child: Text(s.cancel), ), ], ), ], ), ), ); if (!(result ?? false)) return; if (!mounted) return; Dialogs.loading(context: context, hint: s.clearing); await Backup.clearData([ "avatar", if (chat) "chat", if (audio) "audio", if (image) "image", ]); if (chat) { Config.chats.clear(); Current.clear(); Config.save(); ref.read(chatProvider.notifier).notify(); ref.read(chatsProvider.notifier).notify(); ref.read(messagesProvider.notifier).notify(); } if (!mounted) return; Navigator.of(context).pop(); Util.showSnackBar( context: context, content: Text(S.of(context).cleared_successfully), ); } } ================================================ FILE: lib/settings/settings.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "bot.dart"; import "api.dart"; import "config.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; class SettingsPage extends StatefulWidget { const SettingsPage({super.key}); @override State createState() => _SettingsPageState(); } class _SettingsPageState extends State { @override Widget build(BuildContext context) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text(S.of(context).settings), bottom: TabBar( tabs: [ Tab(text: S.of(context).config), Tab(text: S.of(context).bots), Tab(text: S.of(context).apis), ], ), ), body: TabBarView( children: [ const ConfigTab(), const BotsTab(), const ApisTab(), ], ), ), ); } } ================================================ FILE: lib/util.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "config.dart"; import "../gen/l10n.dart"; import "chat/current.dart"; import "dart:io"; import "package:flutter/services.dart"; import "package:flutter/material.dart"; import "package:share_plus/share_plus.dart"; import "package:flutter_svg/flutter_svg.dart"; import "package:url_launcher/url_launcher.dart"; import "package:image_gallery_saver_plus/image_gallery_saver_plus.dart"; class Util { static Future copyText({ required BuildContext context, required String text, }) async { await Clipboard.setData(ClipboardData(text: text)); if (!context.mounted) return; Util.showSnackBar( context: context, content: Text(S.of(context).copied_successfully), ); } static Future checkUpdate({ required BuildContext context, required bool notify, }) async { try { final info = await Updater.check(); if (!context.mounted) return; if (info == null) { if (notify) { showSnackBar( context: context, content: Text(S.of(context).up_to_date), ); } return; } String changeLog = info["body"]; String newVersion = info["tag_name"]; showDialog( context: context, builder: (context) => AlertDialog( title: Text(newVersion), content: SingleChildScrollView(child: Text(changeLog)), actions: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( child: Text(S.of(context).download), onPressed: () { launchUrl(Uri.parse(Updater.latestUrl)); Navigator.of(context).pop(); }, ), ], ), ); } catch (e) { if (notify) Dialogs.error(context: context, error: e); } } static bool checkChat(BuildContext context) { final core = Current.core; final coreOk = core.api != null && core.model != null; if (!coreOk) { showSnackBar( context: context, content: Text(S.of(context).setup_api_model_first), ); return false; } if (Preferences.search) { final search = Config.search; final vector = Config.vector; final vectorOk = vector.api != null && vector.model != null; final searchOk = Preferences.googleSearch || search.searxng != null; if (!searchOk) { showSnackBar( context: context, content: Text(S.of(context).setup_searxng_first), ); return false; } if ((search.vector ?? false) && !vectorOk) { showSnackBar( context: context, content: Text(S.of(context).setup_vector_first), ); return false; } } return true; } static void showSnackBar({ required Text content, required BuildContext context, Duration duration = const Duration(milliseconds: 800), SnackBarBehavior behavior = SnackBarBehavior.floating, }) { ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: content, duration: duration, behavior: behavior, dismissDirection: DismissDirection.down, ), ); } static String formatDateTime(DateTime time) { String two(int n) => n.toString().padLeft(2, '0'); return "${two(time.month)}-${two(time.day)} " "${two(time.hour)}:${two(time.minute)}"; } } class Dialogs { static Future?> input({ required BuildContext context, required String title, required List fields, }) async { return await showModalBottomSheet>( context: context, useSafeArea: true, isScrollControlled: true, builder: (context) => Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), child: InputDialog( title: title, fields: fields, ), ), ); } static void error({ required BuildContext context, required dynamic error, }) { final info = error.toString(); showDialog( context: context, builder: (context) => AlertDialog( title: Text(S.of(context).error), content: SingleChildScrollView(child: SelectableText(info)), actions: [ TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), TextButton( onPressed: () { Util.copyText(context: context, text: info); Navigator.of(context).pop(); }, child: Text(S.of(context).copy), ), ], ), ); } static Future select({ required BuildContext context, required List list, required String title, String? selected, }) async { return await showModalBottomSheet( context: context, useSafeArea: true, scrollControlDisabledMaxHeightRatio: 0.7, builder: (context) => StatefulBuilder( builder: (context, setState) => Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DialogHeader(title: title), const Divider(height: 1), Flexible( child: ListView.builder( shrinkWrap: true, itemCount: list.length, itemBuilder: (context, index) => RadioListTile( value: list[index], groupValue: selected, title: Text(list[index]), contentPadding: const EdgeInsets.only(left: 16, right: 24), onChanged: (value) => setState(() => selected = value), ), ), ), const Divider(height: 1), DialogFooter( children: [ TextButton( onPressed: () => Navigator.of(context).pop(selected), child: Text(S.of(context).ok), ), TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), ], ), ], ), ), ); } static void loading({ required BuildContext context, required String hint, bool canPop = false, }) { showDialog( context: context, barrierDismissible: canPop, builder: (context) => PopScope( canPop: canPop, child: AlertDialog( contentPadding: const EdgeInsets.all(24), content: Row( children: [ const CircularProgressIndicator(), const SizedBox(width: 24), Text(hint), ], ), ), ), ); } static Future openLink({ required BuildContext context, required String? link, }) async { if (link == null) { Util.showSnackBar( context: context, content: Text(S.of(context).empty_link), ); return; } final result = await showDialog( context: context, builder: (context) => AlertDialog( title: Text(S.of(context).link), content: Text(link), actions: [ TextButton( onPressed: () => Navigator.of(context).pop(1), child: Text(S.of(context).copy), ), TextButton( onPressed: () => Navigator.of(context).pop(2), child: Text(S.of(context).open), ), ], ), ); switch (result) { case 1: if (!context.mounted) return; Util.copyText(context: context, text: link); break; case 2: final uri = Uri.parse(link); if (await canLaunchUrl(uri)) { launchUrl(uri, mode: LaunchMode.platformDefault); } else { if (!context.mounted) return; Util.showSnackBar( context: context, content: Text(S.of(context).cannot_open), ); } break; } } static Future handleImage({ required BuildContext context, required String path, }) async { final action = await showModalBottomSheet( context: context, builder: (context) => Padding( padding: const EdgeInsets.only(left: 8, right: 8, bottom: 8), child: Column( mainAxisSize: MainAxisSize.min, children: [ const DragHandle(), ListTile( minTileHeight: 48, shape: StadiumBorder(), title: Text(S.of(context).share), onTap: () => Navigator.pop(context, 1), leading: const Icon(Icons.share_outlined), ), ListTile( minTileHeight: 48, shape: StadiumBorder(), title: Text(S.of(context).save), onTap: () => Navigator.pop(context, 2), leading: const Icon(Icons.save_outlined), ), ], ), ), ); if (action == null) return; if (!Platform.isAndroid) { final uri = Uri.file(path); launchUrl(uri); return; } switch (action) { case 1: Share.shareXFiles([XFile(path)]); break; case 2: final result = await ImageGallerySaverPlus.saveFile(path); if (!context.mounted) return; if (result is Map && result["isSuccess"] == true) { Util.showSnackBar( context: context, content: Text(S.of(context).saved_successfully), ); } break; } } } class InputDialogField { final String? text; final String? hint; final String? help; final String? label; final int? maxLines; const InputDialogField({ this.hint, this.text, this.help, this.label, this.maxLines = 1, }); } class InputDialog extends StatefulWidget { final String title; final List fields; const InputDialog({ required this.title, required this.fields, super.key, }); @override State createState() => _InputDialogState(); } class _InputDialogState extends State { late final List _ctrls; @override void initState() { super.initState(); _ctrls = [ for (final field in widget.fields) TextEditingController(text: field.text), ]; } @override void dispose() { for (final ctrl in _ctrls) { ctrl.dispose(); } super.dispose(); } @override Widget build(BuildContext context) { final fields = widget.fields; return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DialogHeader( title: widget.title, padding: const EdgeInsets.only(top: 16), ), Flexible( child: ListView.separated( shrinkWrap: true, padding: const EdgeInsets.only(left: 24, right: 24), itemCount: fields.length, itemBuilder: (context, index) => TextField( controller: _ctrls[index], maxLines: fields[index].maxLines, decoration: InputDecoration( hintText: fields[index].hint, labelText: fields[index].label, helperText: fields[index].help, border: const UnderlineInputBorder(), ), ), separatorBuilder: (context, index) => const SizedBox(height: 8), ), ), DialogFooter( padding: const EdgeInsets.only(top: 16, bottom: 16), children: [ TextButton( onPressed: () => Navigator.of(context).pop([ for (final ctrl in _ctrls) ctrl.text, ]), child: Text(S.of(context).ok), ), TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), ], ), ], ); } } class InfoCard extends StatelessWidget { final String info; const InfoCard({ required this.info, super.key, }); @override Widget build(BuildContext context) { return Card.outlined( margin: const EdgeInsets.only(left: 16, right: 16), child: Padding( padding: const EdgeInsets.only(top: 8, left: 12, right: 12, bottom: 8), child: Row( children: [ Icon( Icons.info_outlined, color: Theme.of(context).colorScheme.primary, size: 20, ), const SizedBox(width: 8), Expanded( child: Text( info, style: Theme.of(context).textTheme.labelMedium, ), ), ], ), ), ); } } class ModelAvatar extends StatelessWidget { final String? id; static const String _prefix = "assets/images"; static const Map _mappings = { "o1": "openai.svg", "gpt": "openai.svg", "claude": "claude.svg", "gemini": "gemini.svg", "grok": "grok.svg", "qwen": "qwen.svg", "llama": "ollama.svg", "deepseek": "deepseek.svg", }; static final Map _caches = {}; const ModelAvatar({ required this.id, super.key, }); @override Widget build(BuildContext context) { final image = _getImage(context); if (image == null) { return const CircleAvatar( child: Icon(Icons.smart_toy), ); } return CircleAvatar( child: image, ); } SvgPicture? _getImage(BuildContext context) { if (id == null) return null; final brightness = Theme.of(context).brightness; final key = "$id.${brightness.index}"; return _caches.putIfAbsent(key, () { String? fileName; final modelId = id!.toLowerCase(); for (final pair in _mappings.entries) { if (modelId.contains(pair.key)) { fileName = pair.value; break; } } if (fileName == null) return null; return SvgPicture.asset( "$_prefix/$fileName", colorFilter: ColorFilter.mode( Theme.of(context).iconTheme.color!, BlendMode.srcIn, ), ); }); } } class DragHandle extends StatelessWidget { final Size size; final EdgeInsets margin; const DragHandle({ this.size = const Size(32, 4), this.margin = const EdgeInsets.only( top: 16, bottom: 8, ), super.key, }); @override Widget build(BuildContext context) { return Center( child: Padding( padding: margin, child: DecoratedBox( decoration: BoxDecoration( color: Theme.of(context).colorScheme.onSurfaceVariant, borderRadius: BorderRadius.all(Radius.circular(2)), ), child: SizedBox.fromSize(size: size), ), ), ); } } class DialogHeader extends StatelessWidget { final String title; final EdgeInsets padding; const DialogHeader({ required this.title, this.padding = const EdgeInsets.only( top: 16, bottom: 16, ), super.key, }); @override Widget build(BuildContext context) { return Padding( padding: padding, child: Row( children: [ const SizedBox(width: 24), Expanded( child: Text( title, style: Theme.of(context).textTheme.headlineSmall, ), ), IconButton( icon: const Icon(Icons.close), onPressed: Navigator.of(context).pop, ), const SizedBox(width: 12), ], ), ); } } class DialogFooter extends StatelessWidget { final EdgeInsets padding; final List children; const DialogFooter({ required this.children, this.padding = const EdgeInsets.only( top: 12, bottom: 12, ), super.key, }); @override Widget build(BuildContext context) { final child1 = children.elementAt(0); final child2 = children.elementAtOrNull(1); final child3 = children.elementAtOrNull(2); return Padding( padding: padding, child: Row( textDirection: TextDirection.rtl, children: [ const SizedBox(width: 24), child1, const SizedBox(width: 8), if (child2 != null) child2, const Expanded(child: SizedBox()), if (child3 != null) child3, const SizedBox(width: 24), ], ), ); } } ================================================ FILE: lib/workspace/document.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class DocumentTab extends ConsumerStatefulWidget { const DocumentTab({super.key}); @override ConsumerState createState() => _DocumentTabState(); } class _DocumentTabState extends ConsumerState { @override Widget build(BuildContext context) { final s = S.of(context); const padding = EdgeInsets.only(left: 24, right: 24); final primaryColor = Theme.of(context).colorScheme.primary; return ListView( padding: const EdgeInsets.only(top: 16, bottom: 8), children: [ Padding( padding: padding, child: Text( s.embedding_vector, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.api), contentPadding: padding, subtitle: Text(Config.vector.api ?? s.empty), onTap: () async { if (Config.apis.isEmpty) return; final api = await Dialogs.select( context: context, list: Config.apis.keys.toList(), selected: Config.vector.api, title: s.choose_api, ); if (api == null) return; setState(() => Config.vector.api = api); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.model), contentPadding: padding, subtitle: Text(Config.vector.model ?? s.empty), onTap: () async { final models = Config.apis[Config.vector.api]?.models; if (models == null) return; final model = await Dialogs.select( context: context, selected: Config.vector.model, title: s.choose_model, list: models, ); if (model == null) return; setState(() => Config.vector.model = model); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.vector_batch_size), contentPadding: padding, subtitle: Text(s.vector_batch_size_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.vector_batch_size, fields: [ InputDialogField( label: s.please_input, hint: "64", text: Config.vector.batchSize?.toString(), ), ], ); if (texts == null) return; int? value; final text = texts[0].trim(); if (text.isNotEmpty) { value = int.tryParse(text); if (value == null) return; } Config.vector.batchSize = value; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.vector_dimensions), contentPadding: padding, subtitle: Text(s.vector_dimensions_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.vector_dimensions, fields: [ InputDialogField( label: s.please_input, text: Config.vector.dimensions?.toString(), ), ], ); if (texts == null) return; int? value; final text = texts[0].trim(); if (text.isNotEmpty) { value = int.tryParse(text); if (value == null) return; } Config.vector.dimensions = value; Config.save(); }, ), const SizedBox(height: 4), InfoCard(info: s.embedding_vector_info), const SizedBox(height: 16), Padding( padding: padding, child: Text( s.document_config, style: TextStyle(color: primaryColor), ), ), ListTile( title: Text(s.chunk_n), contentPadding: padding, subtitle: Text(s.chunk_n_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.chunk_n, fields: [ InputDialogField( label: s.please_input, hint: "8", text: Config.document.n?.toString(), ), ], ); if (texts == null) return; int? value; final text = texts[0].trim(); if (text.isNotEmpty) { value = int.tryParse(text); if (value == null) return; } Config.document.n = value; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.chunk_size), contentPadding: padding, subtitle: Text(s.chunk_size_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.chunk_size, fields: [ InputDialogField( label: s.please_input, hint: "2000", text: Config.document.size?.toString(), ), ], ); if (texts == null) return; int? value; final text = texts[0].trim(); if (text.isNotEmpty) { value = int.tryParse(text); if (value == null) return; } Config.document.size = value; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.chunk_overlap), contentPadding: padding, subtitle: Text(s.chunk_overlap_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.chunk_overlap, fields: [ InputDialogField( label: s.please_input, hint: "100", text: Config.document.overlap?.toString(), ), ], ); if (texts == null) return; int? value; final text = texts[0].trim(); if (text.isNotEmpty) { value = int.tryParse(text); if (value == null) return; } Config.document.overlap = value; Config.save(); }, ), const SizedBox(height: 4), InfoCard(info: s.document_config_hint), const SizedBox(height: 8), ], ); } } ================================================ FILE: lib/workspace/model.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../gen/l10n.dart"; import "../chat/chat.dart"; import "package:chatbot/config.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class ModelTab extends ConsumerWidget { const ModelTab({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { ref.watch(chatProvider); final modelSet = {}; for (final api in Config.apis.values) { modelSet.addAll(api.models); } final modelList = modelSet.toList(); return ListView.separated( key: ValueKey(Theme.of(context).brightness), padding: const EdgeInsets.all(16), itemCount: modelList.length, itemBuilder: (context, index) { final id = modelList[index]; return Card.filled( color: Theme.of(context).colorScheme.surfaceContainer, margin: EdgeInsets.zero, child: ListTile( leading: ModelAvatar(id: id), shape: const RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(12)), ), title: Text( Config.models[id]?.name ?? id, overflow: TextOverflow.ellipsis, ), subtitle: Text( id, overflow: TextOverflow.ellipsis, ), titleTextStyle: Theme.of(context).textTheme.titleMedium, subtitleTextStyle: Theme.of(context).textTheme.bodySmall, onTap: () => showModalBottomSheet( context: context, useSafeArea: true, isScrollControlled: true, builder: (context) => Padding( padding: EdgeInsets.only( bottom: MediaQuery.of(context).viewInsets.bottom, ), child: ModelSettings(id: id), ), ), ), ); }, separatorBuilder: (context, index) => const SizedBox(height: 12), ); } } class ModelSettings extends ConsumerStatefulWidget { final String id; const ModelSettings({ required this.id, super.key, }); @override ConsumerState createState() => _ModelEditorState(); } class _ModelEditorState extends ConsumerState { late String _id; late bool? _chat; late final ModelConfig? _model; late final TextEditingController _ctrl; @override void initState() { super.initState(); _id = widget.id; _model = Config.models[_id]; _chat = _model?.chat; _ctrl = TextEditingController( text: _model?.name ?? _id, ); } @override void dispose() { _ctrl.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ DialogHeader(title: S.of(context).model), const Divider(height: 1), const SizedBox(height: 8), Row( children: [ const SizedBox(width: 24), Expanded( child: TextField( controller: _ctrl, decoration: InputDecoration( labelText: S.of(context).model_name, border: const UnderlineInputBorder(), ), ), ), IconButton( icon: const Icon(Icons.transform), onPressed: _idToName, ), const SizedBox(width: 12), ], ), const SizedBox(height: 8), CheckboxListTile( value: _chat ?? true, title: Text(S.of(context).chat_model), subtitle: Text(S.of(context).chat_model_hint), onChanged: (value) => setState(() => _chat = value), contentPadding: const EdgeInsets.only(left: 24, right: 16), ), const Divider(height: 1), DialogFooter( children: [ TextButton( onPressed: _save, child: Text(S.of(context).ok), ), TextButton( onPressed: Navigator.of(context).pop, child: Text(S.of(context).cancel), ), ], ), ], ); } void _idToName() { String name = _id; final slash = name.indexOf('/'); if (slash != -1) name = name.substring(slash + 1); var parts = name.split('-'); parts.removeWhere((it) => it.isEmpty); parts = parts.map((it) => "${it[0].toUpperCase()}${it.substring(1)}").toList(); _ctrl.text = parts.join(' '); } Future _save() async { final name = _ctrl.text; if (name.isEmpty) return; final chat = _chat ?? true; Config.models[_id] = ModelConfig( name: name, chat: chat, ); Config.save(); ref.read(messagesProvider.notifier).notify(); ref.read(chatProvider.notifier).notify(); if (mounted) Navigator.of(context).pop(); } } ================================================ FILE: lib/workspace/task.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "../util.dart"; import "../config.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class TaskTab extends ConsumerStatefulWidget { const TaskTab({super.key}); @override ConsumerState createState() => _TaskTabState(); } class _TaskTabState extends ConsumerState { @override Widget build(BuildContext context) { final s = S.of(context); const padding = EdgeInsets.only(left: 24, right: 24); final primaryColor = Theme.of(context).colorScheme.primary; return ListView( padding: const EdgeInsets.only(top: 16, bottom: 8), children: [ Padding( padding: padding, child: Text( s.title_generation, style: TextStyle(color: primaryColor), ), ), CheckboxListTile( title: Text(s.enable), subtitle: Text(s.title_enable_hint), contentPadding: const EdgeInsets.only(left: 24, right: 16), value: Config.title.enable ?? false, onChanged: (value) { setState(() => Config.title.enable = value); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.api), contentPadding: padding, subtitle: Text(Config.title.api ?? s.empty), onTap: () async { if (Config.apis.isEmpty) return; final api = await Dialogs.select( context: context, list: Config.apis.keys.toList(), selected: Config.title.api, title: s.choose_api, ); if (api == null) return; setState(() => Config.title.api = api); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.model), contentPadding: padding, subtitle: Text(Config.title.model ?? s.empty), onTap: () async { final models = Config.apis[Config.title.api]?.models; if (models == null) return; final model = await Dialogs.select( context: context, selected: Config.title.model, title: s.choose_model, list: models, ); if (model == null) return; setState(() => Config.title.model = model); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.title_prompt), contentPadding: padding, subtitle: Text(s.title_prompt_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.title_prompt, fields: [ InputDialogField( label: s.please_input, text: Config.title.prompt, maxLines: null, ), ], ); if (texts == null) return; String? prompt; final text = texts[0].trim(); if (text.isNotEmpty) prompt = text; Config.title.prompt = prompt; Config.save(); }, ), const SizedBox(height: 4), InfoCard(info: s.title_generation_hint("{text}")), const SizedBox(height: 16), Padding( padding: padding, child: Text( s.web_search, style: TextStyle(color: primaryColor), ), ), CheckboxListTile( title: Text(s.search_vector), subtitle: Text(s.search_vector_hint), contentPadding: const EdgeInsets.only(left: 24, right: 16), value: Config.search.vector ?? false, onChanged: (value) { setState(() => Config.search.vector = value); Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.search_searxng), contentPadding: padding, subtitle: Text(s.search_searxng_hint), onTap: () async { String? base; String? extra; final searxng = Config.search.searxng; const fixedPart = "q={text}&format=json"; if (searxng != null) { final uri = Uri.parse(searxng); base = "${uri.scheme}://${uri.host}"; extra = uri.queryParameters.entries .map((it) => "${it.key}=${it.value}") .join('&'); extra = extra.replaceFirst(fixedPart, ""); if (extra.startsWith('&')) extra = extra.replaceFirst('&', ""); } final texts = await Dialogs.input( context: context, title: s.search_searxng, fields: [ InputDialogField( text: base, label: s.search_searxng_base, hint: "https://your.searxng.com", ), InputDialogField( text: extra, label: s.search_searxng_extra, help: s.search_searxng_extra_help, ), ], ); if (texts == null) return; String? newBase; String? newExtra; final text1 = texts[0].trim(); final text2 = texts[1].trim(); if (text1.isNotEmpty) newBase = text1; if (text2.isNotEmpty) newExtra = text2; String? full; if (newBase != null) { full = "$newBase/search?$fixedPart"; if (newExtra != null) full += "&$newExtra"; } Config.search.searxng = full; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.search_timeout), contentPadding: padding, subtitle: Text(s.search_timeout_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.search_timeout, fields: [ InputDialogField( hint: "3000", label: s.search_timeout_query, help: s.search_timeout_query_help, text: Config.search.queryTime?.toString(), ), InputDialogField( hint: "2000", label: s.search_timeout_fetch, help: s.search_timeout_fetch_help, text: Config.search.fetchTime?.toString(), ), ], ); if (texts == null) return; int? query; int? fetch; final text1 = texts[0].trim(); final text2 = texts[1].trim(); if (text1.isNotEmpty) { query = int.tryParse(text1); if (query == null) return; } if (text2.isNotEmpty) { fetch = int.tryParse(text2); if (fetch == null) return; } Config.search.queryTime = query; Config.search.fetchTime = fetch; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.search_n), contentPadding: padding, subtitle: Text(s.search_n_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.search_n, fields: [ InputDialogField( label: s.please_input, hint: "64", text: Config.search.n?.toString(), ), ], ); if (texts == null) return; int? n; final text = texts[0].trim(); if (text.isNotEmpty) { n = int.tryParse(text); if (n == null) return; } Config.search.n = n; Config.save(); }, ), const Divider(height: 1), ListTile( title: Text(s.search_prompt), contentPadding: padding, subtitle: Text(s.search_prompt_hint), onTap: () async { final texts = await Dialogs.input( context: context, title: s.search_prompt, fields: [ InputDialogField( label: s.please_input, text: Config.search.prompt, ), ], ); if (texts == null) return; String? prompt; final text = texts[0].trim(); if (text.isNotEmpty) prompt = text; Config.search.prompt = prompt; Config.save(); }, ), const SizedBox(height: 4), InfoCard(info: s.search_prompt_info("{pages}", "{text}")), const SizedBox(height: 8), ], ); } } ================================================ FILE: lib/workspace/workspace.dart ================================================ // This file is part of ChatBot. // // ChatBot is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // ChatBot is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with ChatBot. If not, see . import "task.dart"; import "model.dart"; import "document.dart"; import "../gen/l10n.dart"; import "package:flutter/material.dart"; import "package:flutter_riverpod/flutter_riverpod.dart"; class WorkspacePage extends ConsumerWidget { const WorkspacePage({super.key}); @override Widget build(BuildContext context, WidgetRef ref) { return DefaultTabController( length: 3, child: Scaffold( appBar: AppBar( title: Text(S.of(context).workspace), bottom: TabBar( tabs: [ Tab(text: S.of(context).model), Tab(text: S.of(context).task), Tab(text: S.of(context).document), ], ), ), body: TabBarView( children: [ const ModelTab(), const TaskTab(), const DocumentTab(), ], ), ), ); } } ================================================ FILE: linux/.gitignore ================================================ flutter/ephemeral ================================================ FILE: linux/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.10) project(runner LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "chatbot") # The unique GTK application identifier for this application. See: # https://wiki.gnome.org/HowDoI/ChooseApplicationID set(APPLICATION_ID "cc.arthur63.chatbot") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(SET CMP0063 NEW) # Load bundled libraries from the lib/ directory relative to the binary. set(CMAKE_INSTALL_RPATH "$ORIGIN/lib") # Root filesystem for cross-building. if(FLUTTER_TARGET_PLATFORM_SYSROOT) set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT}) set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT}) set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER) set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY) set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY) endif() # Define build configuration options. if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_14) target_compile_options(${TARGET} PRIVATE -Wall -Werror) target_compile_options(${TARGET} PRIVATE "$<$>:-O3>") target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}") # Define the application target. To change its name, change BINARY_NAME above, # not the value here, or `flutter run` will no longer work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} "main.cc" "my_application.cc" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add dependency libraries. Add any application-specific dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter) target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK) # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) # Only the install-generated bundle's copy of the executable will launch # correctly, since the resources must in the right relative locations. To avoid # people trying to run the unbundled copy, put it in a subdirectory instead of # the default top-level location. set_target_properties(${BINARY_NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run" ) # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # By default, "installing" just makes a relocatable bundle in the build # directory. set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle") if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() # Start with a clean build bundle directory every time. install(CODE " file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\") " COMPONENT Runtime) set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES}) install(FILES "${bundled_library}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endforeach(bundled_library) # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. if(NOT CMAKE_BUILD_TYPE MATCHES "Debug") install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() ================================================ FILE: linux/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.10) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. # Serves the same purpose as list(TRANSFORM ... PREPEND ...), # which isn't available in 3.10. function(list_prepend LIST_NAME PREFIX) set(NEW_LIST "") foreach(element ${${LIST_NAME}}) list(APPEND NEW_LIST "${PREFIX}${element}") endforeach(element) set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) endfunction() # === Flutter Library === # System-level dependencies. find_package(PkgConfig REQUIRED) pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "fl_basic_message_channel.h" "fl_binary_codec.h" "fl_binary_messenger.h" "fl_dart_project.h" "fl_engine.h" "fl_json_message_codec.h" "fl_json_method_codec.h" "fl_message_codec.h" "fl_method_call.h" "fl_method_channel.h" "fl_method_codec.h" "fl_method_response.h" "fl_plugin_registrar.h" "fl_plugin_registry.h" "fl_standard_message_codec.h" "fl_standard_method_codec.h" "fl_string_codec.h" "fl_value.h" "fl_view.h" "flutter_linux.h" ) list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") target_link_libraries(flutter INTERFACE PkgConfig::GTK PkgConfig::GLIB PkgConfig::GIO ) add_dependencies(flutter flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CMAKE_CURRENT_BINARY_DIR}/_phony_ COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ) ================================================ FILE: linux/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include #include #include #include void fl_register_plugins(FlPluginRegistry* registry) { g_autoptr(FlPluginRegistrar) audioplayers_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "AudioplayersLinuxPlugin"); audioplayers_linux_plugin_register_with_registrar(audioplayers_linux_registrar); g_autoptr(FlPluginRegistrar) file_selector_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin"); file_selector_plugin_register_with_registrar(file_selector_linux_registrar); g_autoptr(FlPluginRegistrar) objectbox_flutter_libs_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "ObjectboxFlutterLibsPlugin"); objectbox_flutter_libs_plugin_register_with_registrar(objectbox_flutter_libs_registrar); g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); } ================================================ FILE: linux/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void fl_register_plugins(FlPluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: linux/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST audioplayers_linux file_selector_linux objectbox_flutter_libs url_launcher_linux ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: linux/main.cc ================================================ #include "my_application.h" int main(int argc, char** argv) { g_autoptr(MyApplication) app = my_application_new(); return g_application_run(G_APPLICATION(app), argc, argv); } ================================================ FILE: linux/my_application.cc ================================================ #include "my_application.h" #include #ifdef GDK_WINDOWING_X11 #include #endif #include "flutter/generated_plugin_registrant.h" struct _MyApplication { GtkApplication parent_instance; char** dart_entrypoint_arguments; }; G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) // Implements GApplication::activate. static void my_application_activate(GApplication* application) { MyApplication* self = MY_APPLICATION(application); GtkWindow* window = GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); // Use a header bar when running in GNOME as this is the common style used // by applications and is the setup most users will be using (e.g. Ubuntu // desktop). // If running on X and not using GNOME then just use a traditional title bar // in case the window manager does more exotic layout, e.g. tiling. // If running on Wayland assume the header bar will work (may need changing // if future cases occur). gboolean use_header_bar = TRUE; #ifdef GDK_WINDOWING_X11 GdkScreen* screen = gtk_window_get_screen(window); if (GDK_IS_X11_SCREEN(screen)) { const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); if (g_strcmp0(wm_name, "GNOME Shell") != 0) { use_header_bar = FALSE; } } #endif if (use_header_bar) { GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); gtk_widget_show(GTK_WIDGET(header_bar)); gtk_header_bar_set_title(header_bar, "chatbot"); gtk_header_bar_set_show_close_button(header_bar, TRUE); gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); } else { gtk_window_set_title(window, "chatbot"); } gtk_window_set_default_size(window, 1280, 720); gtk_widget_show(GTK_WIDGET(window)); g_autoptr(FlDartProject) project = fl_dart_project_new(); fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); FlView* view = fl_view_new(project); gtk_widget_show(GTK_WIDGET(view)); gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); fl_register_plugins(FL_PLUGIN_REGISTRY(view)); gtk_widget_grab_focus(GTK_WIDGET(view)); } // Implements GApplication::local_command_line. static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { MyApplication* self = MY_APPLICATION(application); // Strip out the first argument as it is the binary name. self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); g_autoptr(GError) error = nullptr; if (!g_application_register(application, nullptr, &error)) { g_warning("Failed to register: %s", error->message); *exit_status = 1; return TRUE; } g_application_activate(application); *exit_status = 0; return TRUE; } // Implements GApplication::startup. static void my_application_startup(GApplication* application) { //MyApplication* self = MY_APPLICATION(object); // Perform any actions required at application startup. G_APPLICATION_CLASS(my_application_parent_class)->startup(application); } // Implements GApplication::shutdown. static void my_application_shutdown(GApplication* application) { //MyApplication* self = MY_APPLICATION(object); // Perform any actions required at application shutdown. G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application); } // Implements GObject::dispose. static void my_application_dispose(GObject* object) { MyApplication* self = MY_APPLICATION(object); g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); G_OBJECT_CLASS(my_application_parent_class)->dispose(object); } static void my_application_class_init(MyApplicationClass* klass) { G_APPLICATION_CLASS(klass)->activate = my_application_activate; G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; G_APPLICATION_CLASS(klass)->startup = my_application_startup; G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown; G_OBJECT_CLASS(klass)->dispose = my_application_dispose; } static void my_application_init(MyApplication* self) {} MyApplication* my_application_new() { return MY_APPLICATION(g_object_new(my_application_get_type(), "application-id", APPLICATION_ID, "flags", G_APPLICATION_NON_UNIQUE, nullptr)); } ================================================ FILE: linux/my_application.h ================================================ #ifndef FLUTTER_MY_APPLICATION_H_ #define FLUTTER_MY_APPLICATION_H_ #include G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, GtkApplication) /** * my_application_new: * * Creates a new Flutter-based application. * * Returns: a new #MyApplication. */ MyApplication* my_application_new(); #endif // FLUTTER_MY_APPLICATION_H_ ================================================ FILE: pubspec.yaml ================================================ name: chatbot version: 0.3.5+15 description: ChatBot environment: sdk: ^3.5.4 dependencies: flutter: sdk: flutter flutter_localizations: sdk: flutter http: ^1.2.2 intl: ^0.19.0 archive: ^4.0.2 animate_do: ^3.3.4 flutter_svg: ^2.0.16 flutter_spinkit: ^5.2.1 flutter_riverpod: ^2.6.1 markdown: ^7.2.2 flutter_math_fork: ^0.7.2 flutter_markdown: ^0.7.4+2 flutter_highlighter: ^0.1.1 file_picker: ^8.1.4 image_picker: ^1.1.2 path_provider: ^2.1.5 shared_preferences: ^2.3.4 flutter_image_compress: ^2.3.0 langchain: ^0.7.7+2 langchain_core: ^0.3.6+1 langchain_openai: ^0.7.3 langchain_google: ^0.6.4+2 langchain_community: ^0.3.3 objectbox: ^4.0.3 objectbox_flutter_libs: ^4.0.3 screenshot: ^3.0.0 share_plus: ^10.1.2 url_launcher: ^6.3.1 audioplayers: ^6.1.0 package_info_plus: ^8.1.2 beautiful_soup_dart: ^0.3.0 image_gallery_saver_plus: ^3.0.5 dependency_overrides: path: 1.9.1 dev_dependencies: intl_utils: ^2.8.8 build_runner: ^2.4.13 flutter_lints: ^5.0.0 objectbox_generator: ^4.0.3 flutter: assets: - assets/images/ uses-material-design: true flutter_intl: enabled: true class_name: S main_locale: en arb_dir: lib/l10n output_dir: lib/gen ================================================ FILE: windows/.gitignore ================================================ flutter/ephemeral/ # Visual Studio user-specific files. *.suo *.user *.userosscache *.sln.docstates # Visual Studio build-related files. x64/ x86/ # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !*.[Cc]ache/ ================================================ FILE: windows/CMakeLists.txt ================================================ # Project-level configuration. cmake_minimum_required(VERSION 3.14) project(chatbot LANGUAGES CXX) # The name of the executable created for the application. Change this to change # the on-disk name of your application. set(BINARY_NAME "chatbot") # Explicitly opt in to modern CMake behaviors to avoid warnings with recent # versions of CMake. cmake_policy(VERSION 3.14...3.25) # Define build configuration option. get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) if(IS_MULTICONFIG) set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" CACHE STRING "" FORCE) else() if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) set(CMAKE_BUILD_TYPE "Debug" CACHE STRING "Flutter build mode" FORCE) set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Profile" "Release") endif() endif() # Define settings for the Profile build mode. set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") # Use Unicode for all projects. add_definitions(-DUNICODE -D_UNICODE) # Compilation settings that should be applied to most targets. # # Be cautious about adding new options here, as plugins use this function by # default. In most cases, you should add new options to specific targets instead # of modifying this function. function(APPLY_STANDARD_SETTINGS TARGET) target_compile_features(${TARGET} PUBLIC cxx_std_17) target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") target_compile_options(${TARGET} PRIVATE /EHsc) target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") endfunction() # Flutter library and tool build rules. set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") add_subdirectory(${FLUTTER_MANAGED_DIR}) # Application build; see runner/CMakeLists.txt. add_subdirectory("runner") # Generated plugin build rules, which manage building the plugins and adding # them to the application. include(flutter/generated_plugins.cmake) # === Installation === # Support files are copied into place next to the executable, so that it can # run in place. This is done instead of making a separate bundle (as on Linux) # so that building and running from within Visual Studio will work. set(BUILD_BUNDLE_DIR "$") # Make the "install" step default, as it's required to run. set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) endif() set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" COMPONENT Runtime) install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) if(PLUGIN_BUNDLED_LIBRARIES) install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) endif() # Copy the native assets provided by the build.dart from all packages. set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/") install(DIRECTORY "${NATIVE_ASSETS_DIR}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" COMPONENT Runtime) # Fully re-copy the assets directory on each build to avoid having stale files # from a previous install. set(FLUTTER_ASSET_DIR_NAME "flutter_assets") install(CODE " file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") " COMPONENT Runtime) install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) # Install the AOT library on non-Debug builds only. install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" CONFIGURATIONS Profile;Release COMPONENT Runtime) ================================================ FILE: windows/flutter/CMakeLists.txt ================================================ # This file controls Flutter-level build steps. It should not be edited. cmake_minimum_required(VERSION 3.14) set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") # Configuration provided via flutter tool. include(${EPHEMERAL_DIR}/generated_config.cmake) # TODO: Move the rest of this into files in ephemeral. See # https://github.com/flutter/flutter/issues/57146. set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") # Set fallback configurations for older versions of the flutter tool. if (NOT DEFINED FLUTTER_TARGET_PLATFORM) set(FLUTTER_TARGET_PLATFORM "windows-x64") endif() # === Flutter Library === set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") # Published to parent scope for install step. set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) list(APPEND FLUTTER_LIBRARY_HEADERS "flutter_export.h" "flutter_windows.h" "flutter_messenger.h" "flutter_plugin_registrar.h" "flutter_texture_registrar.h" ) list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") add_library(flutter INTERFACE) target_include_directories(flutter INTERFACE "${EPHEMERAL_DIR}" ) target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") add_dependencies(flutter flutter_assemble) # === Wrapper === list(APPEND CPP_WRAPPER_SOURCES_CORE "core_implementations.cc" "standard_codec.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_PLUGIN "plugin_registrar.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") list(APPEND CPP_WRAPPER_SOURCES_APP "flutter_engine.cc" "flutter_view_controller.cc" ) list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") # Wrapper sources needed for a plugin. add_library(flutter_wrapper_plugin STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ) apply_standard_settings(flutter_wrapper_plugin) set_target_properties(flutter_wrapper_plugin PROPERTIES POSITION_INDEPENDENT_CODE ON) set_target_properties(flutter_wrapper_plugin PROPERTIES CXX_VISIBILITY_PRESET hidden) target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) target_include_directories(flutter_wrapper_plugin PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_plugin flutter_assemble) # Wrapper sources needed for the runner. add_library(flutter_wrapper_app STATIC ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_APP} ) apply_standard_settings(flutter_wrapper_app) target_link_libraries(flutter_wrapper_app PUBLIC flutter) target_include_directories(flutter_wrapper_app PUBLIC "${WRAPPER_ROOT}/include" ) add_dependencies(flutter_wrapper_app flutter_assemble) # === Flutter tool backend === # _phony_ is a non-existent file to force this command to run every time, # since currently there's no way to get a full input/output list from the # flutter tool. set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) add_custom_command( OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ${PHONY_OUTPUT} COMMAND ${CMAKE_COMMAND} -E env ${FLUTTER_TOOL_ENVIRONMENT} "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" ${FLUTTER_TARGET_PLATFORM} $ VERBATIM ) add_custom_target(flutter_assemble DEPENDS "${FLUTTER_LIBRARY}" ${FLUTTER_LIBRARY_HEADERS} ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} ${CPP_WRAPPER_SOURCES_APP} ) ================================================ FILE: windows/flutter/generated_plugin_registrant.cc ================================================ // // Generated file. Do not edit. // // clang-format off #include "generated_plugin_registrant.h" #include #include #include #include #include void RegisterPlugins(flutter::PluginRegistry* registry) { AudioplayersWindowsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("AudioplayersWindowsPlugin")); FileSelectorWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("FileSelectorWindows")); ObjectboxFlutterLibsPluginRegisterWithRegistrar( registry->GetRegistrarForPlugin("ObjectboxFlutterLibsPlugin")); SharePlusWindowsPluginCApiRegisterWithRegistrar( registry->GetRegistrarForPlugin("SharePlusWindowsPluginCApi")); UrlLauncherWindowsRegisterWithRegistrar( registry->GetRegistrarForPlugin("UrlLauncherWindows")); } ================================================ FILE: windows/flutter/generated_plugin_registrant.h ================================================ // // Generated file. Do not edit. // // clang-format off #ifndef GENERATED_PLUGIN_REGISTRANT_ #define GENERATED_PLUGIN_REGISTRANT_ #include // Registers Flutter plugins. void RegisterPlugins(flutter::PluginRegistry* registry); #endif // GENERATED_PLUGIN_REGISTRANT_ ================================================ FILE: windows/flutter/generated_plugins.cmake ================================================ # # Generated file, do not edit. # list(APPEND FLUTTER_PLUGIN_LIST audioplayers_windows file_selector_windows objectbox_flutter_libs share_plus url_launcher_windows ) list(APPEND FLUTTER_FFI_PLUGIN_LIST ) set(PLUGIN_BUNDLED_LIBRARIES) foreach(plugin ${FLUTTER_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) list(APPEND PLUGIN_BUNDLED_LIBRARIES $) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) endforeach(plugin) foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) endforeach(ffi_plugin) ================================================ FILE: windows/runner/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.14) project(runner LANGUAGES CXX) # Define the application target. To change its name, change BINARY_NAME in the # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer # work. # # Any new source files that you add to the application should be added here. add_executable(${BINARY_NAME} WIN32 "flutter_window.cpp" "main.cpp" "utils.cpp" "win32_window.cpp" "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" "Runner.rc" "runner.exe.manifest" ) # Apply the standard set of build settings. This can be removed for applications # that need different build settings. apply_standard_settings(${BINARY_NAME}) # Add preprocessor definitions for the build version. target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") # Disable Windows macros that collide with C++ standard library functions. target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") # Add dependency libraries and include directories. Add any application-specific # dependencies here. target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib") target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") # Run the Flutter tool portions of the build. This must not be removed. add_dependencies(${BINARY_NAME} flutter_assemble) ================================================ FILE: windows/runner/Runner.rc ================================================ // Microsoft Visual C++ generated resource script. // #pragma code_page(65001) #include "resource.h" #define APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 2 resource. // #include "winres.h" ///////////////////////////////////////////////////////////////////////////// #undef APSTUDIO_READONLY_SYMBOLS ///////////////////////////////////////////////////////////////////////////// // English (United States) resources #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US #ifdef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // TEXTINCLUDE // 1 TEXTINCLUDE BEGIN "resource.h\0" END 2 TEXTINCLUDE BEGIN "#include ""winres.h""\r\n" "\0" END 3 TEXTINCLUDE BEGIN "\r\n" "\0" END #endif // APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Icon // // Icon with lowest ID value placed first to ensure application icon // remains consistent on all systems. IDI_APP_ICON ICON "resources\\app_icon.ico" ///////////////////////////////////////////////////////////////////////////// // // Version // #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD #else #define VERSION_AS_NUMBER 1,0,0,0 #endif #if defined(FLUTTER_VERSION) #define VERSION_AS_STRING FLUTTER_VERSION #else #define VERSION_AS_STRING "1.0.0" #endif VS_VERSION_INFO VERSIONINFO FILEVERSION VERSION_AS_NUMBER PRODUCTVERSION VERSION_AS_NUMBER FILEFLAGSMASK VS_FFI_FILEFLAGSMASK #ifdef _DEBUG FILEFLAGS VS_FF_DEBUG #else FILEFLAGS 0x0L #endif FILEOS VOS__WINDOWS32 FILETYPE VFT_APP FILESUBTYPE 0x0L BEGIN BLOCK "StringFileInfo" BEGIN BLOCK "040904e4" BEGIN VALUE "CompanyName", "cc.arthur63" "\0" VALUE "FileDescription", "chatbot" "\0" VALUE "FileVersion", VERSION_AS_STRING "\0" VALUE "InternalName", "chatbot" "\0" VALUE "LegalCopyright", "Copyright (C) 2024 cc.arthur63. All rights reserved." "\0" VALUE "OriginalFilename", "chatbot.exe" "\0" VALUE "ProductName", "chatbot" "\0" VALUE "ProductVersion", VERSION_AS_STRING "\0" END END BLOCK "VarFileInfo" BEGIN VALUE "Translation", 0x409, 1252 END END #endif // English (United States) resources ///////////////////////////////////////////////////////////////////////////// #ifndef APSTUDIO_INVOKED ///////////////////////////////////////////////////////////////////////////// // // Generated from the TEXTINCLUDE 3 resource. // ///////////////////////////////////////////////////////////////////////////// #endif // not APSTUDIO_INVOKED ================================================ FILE: windows/runner/flutter_window.cpp ================================================ #include "flutter_window.h" #include #include "flutter/generated_plugin_registrant.h" FlutterWindow::FlutterWindow(const flutter::DartProject& project) : project_(project) {} FlutterWindow::~FlutterWindow() {} bool FlutterWindow::OnCreate() { if (!Win32Window::OnCreate()) { return false; } RECT frame = GetClientArea(); // The size here must match the window dimensions to avoid unnecessary surface // creation / destruction in the startup path. flutter_controller_ = std::make_unique( frame.right - frame.left, frame.bottom - frame.top, project_); // Ensure that basic setup of the controller was successful. if (!flutter_controller_->engine() || !flutter_controller_->view()) { return false; } RegisterPlugins(flutter_controller_->engine()); SetChildContent(flutter_controller_->view()->GetNativeWindow()); flutter_controller_->engine()->SetNextFrameCallback([&]() { this->Show(); }); // Flutter can complete the first frame before the "show window" callback is // registered. The following call ensures a frame is pending to ensure the // window is shown. It is a no-op if the first frame hasn't completed yet. flutter_controller_->ForceRedraw(); return true; } void FlutterWindow::OnDestroy() { if (flutter_controller_) { flutter_controller_ = nullptr; } Win32Window::OnDestroy(); } LRESULT FlutterWindow::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { // Give Flutter, including plugins, an opportunity to handle window messages. if (flutter_controller_) { std::optional result = flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, lparam); if (result) { return *result; } } switch (message) { case WM_FONTCHANGE: flutter_controller_->engine()->ReloadSystemFonts(); break; } return Win32Window::MessageHandler(hwnd, message, wparam, lparam); } ================================================ FILE: windows/runner/flutter_window.h ================================================ #ifndef RUNNER_FLUTTER_WINDOW_H_ #define RUNNER_FLUTTER_WINDOW_H_ #include #include #include #include "win32_window.h" // A window that does nothing but host a Flutter view. class FlutterWindow : public Win32Window { public: // Creates a new FlutterWindow hosting a Flutter view running |project|. explicit FlutterWindow(const flutter::DartProject& project); virtual ~FlutterWindow(); protected: // Win32Window: bool OnCreate() override; void OnDestroy() override; LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept override; private: // The project to run. flutter::DartProject project_; // The Flutter instance hosted by this window. std::unique_ptr flutter_controller_; }; #endif // RUNNER_FLUTTER_WINDOW_H_ ================================================ FILE: windows/runner/main.cpp ================================================ #include #include #include #include "flutter_window.h" #include "utils.h" int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, _In_ wchar_t *command_line, _In_ int show_command) { // Attach to console when present (e.g., 'flutter run') or create a // new console when running with a debugger. if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { CreateAndAttachConsole(); } // Initialize COM, so that it is available for use in the library and/or // plugins. ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); flutter::DartProject project(L"data"); std::vector command_line_arguments = GetCommandLineArguments(); project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); FlutterWindow window(project); Win32Window::Point origin(10, 10); Win32Window::Size size(1280, 720); if (!window.Create(L"chatbot", origin, size)) { return EXIT_FAILURE; } window.SetQuitOnClose(true); ::MSG msg; while (::GetMessage(&msg, nullptr, 0, 0)) { ::TranslateMessage(&msg); ::DispatchMessage(&msg); } ::CoUninitialize(); return EXIT_SUCCESS; } ================================================ FILE: windows/runner/resource.h ================================================ //{{NO_DEPENDENCIES}} // Microsoft Visual C++ generated include file. // Used by Runner.rc // #define IDI_APP_ICON 101 // Next default values for new objects // #ifdef APSTUDIO_INVOKED #ifndef APSTUDIO_READONLY_SYMBOLS #define _APS_NEXT_RESOURCE_VALUE 102 #define _APS_NEXT_COMMAND_VALUE 40001 #define _APS_NEXT_CONTROL_VALUE 1001 #define _APS_NEXT_SYMED_VALUE 101 #endif #endif ================================================ FILE: windows/runner/runner.exe.manifest ================================================ PerMonitorV2 ================================================ FILE: windows/runner/utils.cpp ================================================ #include "utils.h" #include #include #include #include #include void CreateAndAttachConsole() { if (::AllocConsole()) { FILE *unused; if (freopen_s(&unused, "CONOUT$", "w", stdout)) { _dup2(_fileno(stdout), 1); } if (freopen_s(&unused, "CONOUT$", "w", stderr)) { _dup2(_fileno(stdout), 2); } std::ios::sync_with_stdio(); FlutterDesktopResyncOutputStreams(); } } std::vector GetCommandLineArguments() { // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. int argc; wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); if (argv == nullptr) { return std::vector(); } std::vector command_line_arguments; // Skip the first argument as it's the binary name. for (int i = 1; i < argc; i++) { command_line_arguments.push_back(Utf8FromUtf16(argv[i])); } ::LocalFree(argv); return command_line_arguments; } std::string Utf8FromUtf16(const wchar_t* utf16_string) { if (utf16_string == nullptr) { return std::string(); } unsigned int target_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, -1, nullptr, 0, nullptr, nullptr) -1; // remove the trailing null character int input_length = (int)wcslen(utf16_string); std::string utf8_string; if (target_length == 0 || target_length > utf8_string.max_size()) { return utf8_string; } utf8_string.resize(target_length); int converted_length = ::WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, input_length, utf8_string.data(), target_length, nullptr, nullptr); if (converted_length == 0) { return std::string(); } return utf8_string; } ================================================ FILE: windows/runner/utils.h ================================================ #ifndef RUNNER_UTILS_H_ #define RUNNER_UTILS_H_ #include #include // Creates a console for the process, and redirects stdout and stderr to // it for both the runner and the Flutter library. void CreateAndAttachConsole(); // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string // encoded in UTF-8. Returns an empty std::string on failure. std::string Utf8FromUtf16(const wchar_t* utf16_string); // Gets the command line arguments passed in as a std::vector, // encoded in UTF-8. Returns an empty std::vector on failure. std::vector GetCommandLineArguments(); #endif // RUNNER_UTILS_H_ ================================================ FILE: windows/runner/win32_window.cpp ================================================ #include "win32_window.h" #include #include #include "resource.h" namespace { /// Window attribute that enables dark mode window decorations. /// /// Redefined in case the developer's machine has a Windows SDK older than /// version 10.0.22000.0. /// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute #ifndef DWMWA_USE_IMMERSIVE_DARK_MODE #define DWMWA_USE_IMMERSIVE_DARK_MODE 20 #endif constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; /// Registry key for app theme preference. /// /// A value of 0 indicates apps should use dark mode. A non-zero or missing /// value indicates apps should use light mode. constexpr const wchar_t kGetPreferredBrightnessRegKey[] = L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"; constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme"; // The number of Win32Window objects that currently exist. static int g_active_window_count = 0; using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); // Scale helper to convert logical scaler values to physical using passed in // scale factor int Scale(int source, double scale_factor) { return static_cast(source * scale_factor); } // Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. // This API is only needed for PerMonitor V1 awareness mode. void EnableFullDpiSupportIfAvailable(HWND hwnd) { HMODULE user32_module = LoadLibraryA("User32.dll"); if (!user32_module) { return; } auto enable_non_client_dpi_scaling = reinterpret_cast( GetProcAddress(user32_module, "EnableNonClientDpiScaling")); if (enable_non_client_dpi_scaling != nullptr) { enable_non_client_dpi_scaling(hwnd); } FreeLibrary(user32_module); } } // namespace // Manages the Win32Window's window class registration. class WindowClassRegistrar { public: ~WindowClassRegistrar() = default; // Returns the singleton registrar instance. static WindowClassRegistrar* GetInstance() { if (!instance_) { instance_ = new WindowClassRegistrar(); } return instance_; } // Returns the name of the window class, registering the class if it hasn't // previously been registered. const wchar_t* GetWindowClass(); // Unregisters the window class. Should only be called if there are no // instances of the window. void UnregisterWindowClass(); private: WindowClassRegistrar() = default; static WindowClassRegistrar* instance_; bool class_registered_ = false; }; WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; const wchar_t* WindowClassRegistrar::GetWindowClass() { if (!class_registered_) { WNDCLASS window_class{}; window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); window_class.lpszClassName = kWindowClassName; window_class.style = CS_HREDRAW | CS_VREDRAW; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = GetModuleHandle(nullptr); window_class.hIcon = LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); window_class.hbrBackground = 0; window_class.lpszMenuName = nullptr; window_class.lpfnWndProc = Win32Window::WndProc; RegisterClass(&window_class); class_registered_ = true; } return kWindowClassName; } void WindowClassRegistrar::UnregisterWindowClass() { UnregisterClass(kWindowClassName, nullptr); class_registered_ = false; } Win32Window::Win32Window() { ++g_active_window_count; } Win32Window::~Win32Window() { --g_active_window_count; Destroy(); } bool Win32Window::Create(const std::wstring& title, const Point& origin, const Size& size) { Destroy(); const wchar_t* window_class = WindowClassRegistrar::GetInstance()->GetWindowClass(); const POINT target_point = {static_cast(origin.x), static_cast(origin.y)}; HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); double scale_factor = dpi / 96.0; HWND window = CreateWindow( window_class, title.c_str(), WS_OVERLAPPEDWINDOW, Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), Scale(size.width, scale_factor), Scale(size.height, scale_factor), nullptr, nullptr, GetModuleHandle(nullptr), this); if (!window) { return false; } UpdateTheme(window); return OnCreate(); } bool Win32Window::Show() { return ShowWindow(window_handle_, SW_SHOWNORMAL); } // static LRESULT CALLBACK Win32Window::WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { if (message == WM_NCCREATE) { auto window_struct = reinterpret_cast(lparam); SetWindowLongPtr(window, GWLP_USERDATA, reinterpret_cast(window_struct->lpCreateParams)); auto that = static_cast(window_struct->lpCreateParams); EnableFullDpiSupportIfAvailable(window); that->window_handle_ = window; } else if (Win32Window* that = GetThisFromHandle(window)) { return that->MessageHandler(window, message, wparam, lparam); } return DefWindowProc(window, message, wparam, lparam); } LRESULT Win32Window::MessageHandler(HWND hwnd, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept { switch (message) { case WM_DESTROY: window_handle_ = nullptr; Destroy(); if (quit_on_close_) { PostQuitMessage(0); } return 0; case WM_DPICHANGED: { auto newRectSize = reinterpret_cast(lparam); LONG newWidth = newRectSize->right - newRectSize->left; LONG newHeight = newRectSize->bottom - newRectSize->top; SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, newHeight, SWP_NOZORDER | SWP_NOACTIVATE); return 0; } case WM_SIZE: { RECT rect = GetClientArea(); if (child_content_ != nullptr) { // Size and position the child window. MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE); } return 0; } case WM_ACTIVATE: if (child_content_ != nullptr) { SetFocus(child_content_); } return 0; case WM_DWMCOLORIZATIONCOLORCHANGED: UpdateTheme(hwnd); return 0; } return DefWindowProc(window_handle_, message, wparam, lparam); } void Win32Window::Destroy() { OnDestroy(); if (window_handle_) { DestroyWindow(window_handle_); window_handle_ = nullptr; } if (g_active_window_count == 0) { WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); } } Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { return reinterpret_cast( GetWindowLongPtr(window, GWLP_USERDATA)); } void Win32Window::SetChildContent(HWND content) { child_content_ = content; SetParent(content, window_handle_); RECT frame = GetClientArea(); MoveWindow(content, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, true); SetFocus(child_content_); } RECT Win32Window::GetClientArea() { RECT frame; GetClientRect(window_handle_, &frame); return frame; } HWND Win32Window::GetHandle() { return window_handle_; } void Win32Window::SetQuitOnClose(bool quit_on_close) { quit_on_close_ = quit_on_close; } bool Win32Window::OnCreate() { // No-op; provided for subclasses. return true; } void Win32Window::OnDestroy() { // No-op; provided for subclasses. } void Win32Window::UpdateTheme(HWND const window) { DWORD light_mode; DWORD light_mode_size = sizeof(light_mode); LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey, kGetPreferredBrightnessRegValue, RRF_RT_REG_DWORD, nullptr, &light_mode, &light_mode_size); if (result == ERROR_SUCCESS) { BOOL enable_dark_mode = light_mode == 0; DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE, &enable_dark_mode, sizeof(enable_dark_mode)); } } ================================================ FILE: windows/runner/win32_window.h ================================================ #ifndef RUNNER_WIN32_WINDOW_H_ #define RUNNER_WIN32_WINDOW_H_ #include #include #include #include // A class abstraction for a high DPI-aware Win32 Window. Intended to be // inherited from by classes that wish to specialize with custom // rendering and input handling class Win32Window { public: struct Point { unsigned int x; unsigned int y; Point(unsigned int x, unsigned int y) : x(x), y(y) {} }; struct Size { unsigned int width; unsigned int height; Size(unsigned int width, unsigned int height) : width(width), height(height) {} }; Win32Window(); virtual ~Win32Window(); // Creates a win32 window with |title| that is positioned and sized using // |origin| and |size|. New windows are created on the default monitor. Window // sizes are specified to the OS in physical pixels, hence to ensure a // consistent size this function will scale the inputted width and height as // as appropriate for the default monitor. The window is invisible until // |Show| is called. Returns true if the window was created successfully. bool Create(const std::wstring& title, const Point& origin, const Size& size); // Show the current window. Returns true if the window was successfully shown. bool Show(); // Release OS resources associated with window. void Destroy(); // Inserts |content| into the window tree. void SetChildContent(HWND content); // Returns the backing Window handle to enable clients to set icon and other // window properties. Returns nullptr if the window has been destroyed. HWND GetHandle(); // If true, closing this window will quit the application. void SetQuitOnClose(bool quit_on_close); // Return a RECT representing the bounds of the current client area. RECT GetClientArea(); protected: // Processes and route salient window messages for mouse handling, // size change and DPI. Delegates handling of these to member overloads that // inheriting classes can handle. virtual LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Called when CreateAndShow is called, allowing subclass window-related // setup. Subclasses should return false if setup fails. virtual bool OnCreate(); // Called when Destroy is called. virtual void OnDestroy(); private: friend class WindowClassRegistrar; // OS callback called by message pump. Handles the WM_NCCREATE message which // is passed when the non-client area is being created and enables automatic // non-client DPI scaling so that the non-client area automatically // responds to changes in DPI. All other messages are handled by // MessageHandler. static LRESULT CALLBACK WndProc(HWND const window, UINT const message, WPARAM const wparam, LPARAM const lparam) noexcept; // Retrieves a class instance pointer for |window| static Win32Window* GetThisFromHandle(HWND const window) noexcept; // Update the window frame's theme to match the system theme. static void UpdateTheme(HWND const window); bool quit_on_close_ = false; // window handle for top level window. HWND window_handle_ = nullptr; // window handle for hosted content. HWND child_content_ = nullptr; }; #endif // RUNNER_WIN32_WINDOW_H_