├── .gitignore ├── .metadata ├── LICENSE ├── README-zh-CN.md ├── README.md ├── analysis_options.yaml ├── android ├── .gitignore ├── app │ ├── build.gradle │ └── src │ │ ├── debug │ │ └── AndroidManifest.xml │ │ ├── main │ │ ├── AndroidManifest.xml │ │ ├── kotlin │ │ │ └── com │ │ │ │ └── app2m │ │ │ │ └── chatgpt │ │ │ │ └── hao_chatgpt │ │ │ │ └── MainActivity.kt │ │ └── res │ │ │ ├── drawable-v21 │ │ │ └── launch_background.xml │ │ │ ├── drawable │ │ │ └── launch_background.xml │ │ │ ├── mipmap-hdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-mdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── mipmap-xxxhdpi │ │ │ └── ic_launcher.png │ │ │ ├── values-night │ │ │ └── styles.xml │ │ │ └── values │ │ │ └── styles.xml │ │ └── profile │ │ └── AndroidManifest.xml ├── build.gradle ├── gradle.properties ├── gradle │ └── wrapper │ │ └── gradle-wrapper.properties └── settings.gradle ├── assets └── images │ └── openai.png ├── build_runner.bat ├── ios ├── .gitignore ├── Flutter │ ├── AppFrameworkInfo.plist │ ├── Debug.xcconfig │ └── Release.xcconfig ├── Podfile ├── Runner.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ ├── contents.xcworkspacedata │ │ └── xcshareddata │ │ │ ├── IDEWorkspaceChecks.plist │ │ │ └── WorkspaceSettings.xcsettings │ └── xcshareddata │ │ └── xcschemes │ │ └── Runner.xcscheme ├── Runner.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ ├── IDEWorkspaceChecks.plist │ │ └── WorkspaceSettings.xcsettings └── Runner │ ├── AppDelegate.swift │ ├── Assets.xcassets │ ├── AppIcon.appiconset │ │ ├── Contents.json │ │ ├── Icon-App-1024x1024@1x.png │ │ ├── Icon-App-20x20@1x.png │ │ ├── Icon-App-20x20@2x.png │ │ ├── Icon-App-20x20@3x.png │ │ ├── Icon-App-29x29@1x.png │ │ ├── Icon-App-29x29@2x.png │ │ ├── Icon-App-29x29@3x.png │ │ ├── Icon-App-40x40@1x.png │ │ ├── Icon-App-40x40@2x.png │ │ ├── Icon-App-40x40@3x.png │ │ ├── Icon-App-60x60@2x.png │ │ ├── Icon-App-60x60@3x.png │ │ ├── Icon-App-76x76@1x.png │ │ ├── Icon-App-76x76@2x.png │ │ └── Icon-App-83.5x83.5@2x.png │ └── LaunchImage.imageset │ │ ├── Contents.json │ │ ├── LaunchImage.png │ │ ├── LaunchImage@2x.png │ │ ├── LaunchImage@3x.png │ │ └── README.md │ ├── Base.lproj │ ├── LaunchScreen.storyboard │ └── Main.storyboard │ ├── Info.plist │ └── Runner-Bridging-Header.h ├── l10n.bat ├── l10n.yaml ├── lib ├── l10n │ ├── generated │ │ ├── l10n.dart │ │ ├── l10n_en.dart │ │ └── l10n_zh.dart │ ├── intl_en.arb │ └── intl_zh.arb ├── main.dart └── src │ ├── app_config.dart │ ├── app_manager.dart │ ├── app_router.dart │ ├── app_shortcuts.dart │ ├── constants.dart │ ├── db │ ├── hao_database.dart │ └── hao_database.g.dart │ ├── extensions.dart │ ├── my_colors.dart │ ├── network │ ├── entity │ │ ├── api_key_entity.dart │ │ ├── api_key_entity.g.dart │ │ ├── dio_error_entity.dart │ │ ├── dio_error_entity.g.dart │ │ └── openai │ │ │ ├── chat_entity.dart │ │ │ ├── chat_entity.g.dart │ │ │ ├── chat_message_entity.dart │ │ │ ├── chat_message_entity.g.dart │ │ │ ├── chat_query_entity.dart │ │ │ ├── chat_query_entity.g.dart │ │ │ ├── completion_usage_entity.dart │ │ │ ├── completion_usage_entity.g.dart │ │ │ ├── completions_entity.dart │ │ │ ├── completions_entity.g.dart │ │ │ ├── completions_query_entity.dart │ │ │ ├── completions_query_entity.g.dart │ │ │ ├── model_entity.dart │ │ │ └── model_entity.g.dart │ ├── openai_client.dart │ ├── openai_service.dart │ └── openai_service.g.dart │ └── screens │ ├── chat.dart │ ├── chat │ ├── chat_drawer.dart │ └── no_key_view.dart │ ├── chat_turbo.dart │ ├── chat_turbo │ ├── chat_turbo_content.dart │ ├── chat_turbo_menu.dart │ └── chat_turbo_system.dart │ ├── home.dart │ ├── settings.dart │ ├── settings │ ├── settings_apikey.dart │ ├── settings_gpt3.dart │ ├── settings_gpt35turbo.dart │ └── settings_proxy.dart │ └── webview.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 ├── macos ├── .gitignore ├── Flutter │ ├── Flutter-Debug.xcconfig │ ├── Flutter-Release.xcconfig │ └── GeneratedPluginRegistrant.swift ├── Podfile ├── Runner.xcodeproj │ ├── project.pbxproj │ ├── project.xcworkspace │ │ └── xcshareddata │ │ │ └── IDEWorkspaceChecks.plist │ └── xcshareddata │ │ └── xcschemes │ │ └── Runner.xcscheme ├── Runner.xcworkspace │ ├── contents.xcworkspacedata │ └── xcshareddata │ │ └── IDEWorkspaceChecks.plist └── Runner │ ├── AppDelegate.swift │ ├── Assets.xcassets │ └── AppIcon.appiconset │ │ ├── Contents.json │ │ ├── app_icon_1024.png │ │ ├── app_icon_128.png │ │ ├── app_icon_16.png │ │ ├── app_icon_256.png │ │ ├── app_icon_32.png │ │ ├── app_icon_512.png │ │ └── app_icon_64.png │ ├── Base.lproj │ └── MainMenu.xib │ ├── Configs │ ├── AppInfo.xcconfig │ ├── Debug.xcconfig │ ├── Release.xcconfig │ └── Warnings.xcconfig │ ├── DebugProfile.entitlements │ ├── Info.plist │ ├── MainFlutterWindow.swift │ └── Release.entitlements ├── pubspec.yaml ├── release_apk.bat ├── release_windows.bat ├── screenshots ├── en │ ├── gpt35turbo.jpg │ ├── home.jpg │ ├── leftmenu01.jpg │ ├── leftmenu02.jpg │ ├── nokey.jpg │ ├── screenshot01.jpg │ ├── screenshot02.jpg │ ├── screenshot03.jpg │ ├── screenshot04.jpg │ ├── screenshot05.jpg │ ├── screenshot06.jpg │ ├── setsystem01.jpg │ ├── setsystem02.jpg │ └── settings.jpg ├── flutter_logo.png ├── openai.png ├── openai_logo.png └── zh │ ├── gpt35turbo.jpg │ ├── home.jpg │ ├── leftmenu01.jpg │ ├── leftmenu02.jpg │ ├── nokey.jpg │ ├── screenshot01.jpg │ ├── screenshot02.jpg │ ├── screenshot03.jpg │ ├── screenshot04.jpg │ ├── screenshot05.jpg │ ├── screenshot06.jpg │ ├── setsystem01.jpg │ ├── setsystem02.jpg │ └── settings.jpg ├── test ├── api_test.dart └── widget_test.dart ├── web ├── favicon.png ├── icons │ ├── Icon-192.png │ ├── Icon-512.png │ ├── Icon-maskable-192.png │ └── Icon-maskable-512.png ├── index.html └── manifest.json └── 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 ├── resources └── app_icon.ico ├── runner.exe.manifest ├── utils.cpp ├── utils.h ├── win32_window.cpp └── win32_window.h /.gitignore: -------------------------------------------------------------------------------- 1 | # Miscellaneous 2 | *.class 3 | *.log 4 | *.pyc 5 | *.swp 6 | .DS_Store 7 | .atom/ 8 | .buildlog/ 9 | .history 10 | .svn/ 11 | migrate_working_dir/ 12 | 13 | # IntelliJ related 14 | *.iml 15 | *.ipr 16 | *.iws 17 | .idea/ 18 | 19 | # The .vscode folder contains launch configuration and tasks you configure in 20 | # VS Code which you may wish to be included in version control, so this line 21 | # is commented out by default. 22 | #.vscode/ 23 | 24 | # Flutter/Dart/Pub related 25 | **/doc/api/ 26 | **/ios/Flutter/.last_build_id 27 | .dart_tool/ 28 | .flutter-plugins 29 | .flutter-plugins-dependencies 30 | .packages 31 | .pub-cache/ 32 | .pub/ 33 | /build/ 34 | 35 | # Symbolication related 36 | app.*.symbols 37 | 38 | # Obfuscation related 39 | app.*.map.json 40 | 41 | # Android Studio will place build artifacts here 42 | /android/app/debug 43 | /android/app/profile 44 | /android/app/release 45 | /pubspec.lock 46 | /openai.yaml -------------------------------------------------------------------------------- /.metadata: -------------------------------------------------------------------------------- 1 | # This file tracks properties of this Flutter project. 2 | # Used by Flutter tool to assess capabilities and perform upgrades etc. 3 | # 4 | # This file should be version controlled. 5 | 6 | version: 7 | revision: 135454af32477f815a7525073027a3ff9eff1bfd 8 | channel: stable 9 | 10 | project_type: app 11 | 12 | # Tracks metadata for the flutter migrate command 13 | migration: 14 | platforms: 15 | - platform: root 16 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 17 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 18 | - platform: android 19 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 20 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 21 | - platform: ios 22 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 23 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 24 | - platform: linux 25 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 26 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 27 | - platform: macos 28 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 29 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 30 | - platform: web 31 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 32 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 33 | - platform: windows 34 | create_revision: 135454af32477f815a7525073027a3ff9eff1bfd 35 | base_revision: 135454af32477f815a7525073027a3ff9eff1bfd 36 | 37 | # User provided section 38 | 39 | # List of Local paths (relative to this file) that should be 40 | # ignored by the migrate tool. 41 | # 42 | # Files that are not part of the templates will be ignored by default. 43 | unmanaged_files: 44 | - 'lib/main.dart' 45 | - 'ios/Runner.xcodeproj/project.pbxproj' 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Conghaonet 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README-zh-CN.md: -------------------------------------------------------------------------------- 1 | [English](README.md) | 简体中文 2 | 3 | # HaoChat 4 | 5 | 一款用Flutter开发的非官方的 ChatGPT 应用。 6 | 如果这个库对你有帮助,请给它一个star来支持我们! 7 | 8 |    9 | 10 | ## 支持的模型: 11 | * [gpt-3.5-turbo](https://platform.openai.com/docs/models/gpt-3-5) 12 | * text-davinci-003 13 | * text-curie-001 14 | * text-babbage-001 15 | * text-ada-001 16 | 17 | ## 支持的平台: 18 | * iOS 19 | * Android 20 | * macOS 21 | * Windows 22 | * Linux (未测试) 23 | 24 | ## 开发中的特性 25 | - [x] GPT-4 26 | 27 | ## 设置你自己的 OpenAI API key 28 | 29 | 在工程根目录下创建文件 **openai.yaml**,并填入你自己的 [**OpenAI API key**](https://beta.openai.com/account/api-keys)。 30 | ```yaml 31 | # 默认 API key 32 | api_key: 'YOUR-API-KEY' 33 | ``` 34 | 出于安全原因, 我不能上传 **openai.yaml**。 35 | 36 | 注:_注册OpenAI账号需要科学上网,并有境外手机号用于接收短信验证码,如没有境外手机号,建议通过短信接码平台接收短信,以完成注册。_ 37 | 38 | ## 小提示 39 | Set the task or role of the AI in this **SYSTEM** input box. 40 | For example: You are a helpful assistant that translates Chinese to English to. 41 | 42 | ![](https://github.com/conghaonet/hao_chatgpt/blob/master/screenshots/zh/setsystem01.jpg) ![](https://github.com/conghaonet/hao_chatgpt/blob/master/screenshots/zh/setsystem02.jpg) 43 | 44 | ## 截图 45 | 46 | 47 | 50 | 53 | 54 | 55 | 58 | 61 | 62 | 63 | 66 | 69 | 70 | 71 | 74 | 77 | 78 | 79 | 82 | 85 | 86 | 87 | 90 | 93 | 94 |
48 | 49 | 51 | 52 |
56 | 57 | 59 | 60 |
64 | 65 | 67 | 68 |
72 | 73 | 75 | 76 |
80 | 81 | 83 | 84 |
88 | 89 | 91 | 92 |
95 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | English | [简体中文](README-zh-CN.md) 2 | 3 | # HaoChat 4 | 5 | An unofficial ChatGPT application developed with Flutter. 6 | If this repository has been helpful to you, please support us by giving it a star! 7 | 8 |    9 | 10 | ## Supported models 11 | * [gpt-3.5-turbo](https://platform.openai.com/docs/models/gpt-3-5) 12 | * text-davinci-003 13 | * text-curie-001 14 | * text-babbage-001 15 | * text-ada-001 16 | 17 | ## Supported platforms 18 | * iOS 19 | * Android 20 | * macOS 21 | * Windows 22 | * Linux (untested) 23 | 24 | ## Setup your OpenAI API key 25 | 26 | Create a file named **openai.yaml** in the root directory of the project and fill it with your [**OpenAI API key**](https://beta.openai.com/account/api-keys). 27 | ```yaml 28 | # default API key 29 | api_key: 'YOUR-API-KEY' 30 | ``` 31 | For security reasons, I cannot upload my **openai.yaml**. 32 | 33 | ## Under development 34 | - [x] GPT-4 35 | 36 | ## Tips 37 | Set the task or role of the AI in this **System prompt** input field. 38 | For example: You are a helpful assistant that translates Chinese to English to. 39 | 40 | ![](https://github.com/conghaonet/hao_chatgpt/blob/master/screenshots/en/setsystem01.jpg) ![](https://github.com/conghaonet/hao_chatgpt/blob/master/screenshots/en/setsystem02.jpg) 41 | 42 | ## Screenshots 43 | 44 | 45 | 48 | 51 | 52 | 53 | 56 | 59 | 60 | 61 | 64 | 67 | 68 | 69 | 72 | 75 | 76 | 77 | 80 | 83 | 84 | 85 | 88 | 91 | 92 |
46 | 47 | 49 | 50 |
54 | 55 | 57 | 58 |
62 | 63 | 65 | 66 |
70 | 71 | 73 | 74 |
78 | 79 | 81 | 82 |
86 | 87 | 89 | 90 |
93 | -------------------------------------------------------------------------------- /analysis_options.yaml: -------------------------------------------------------------------------------- 1 | # This file configures the analyzer, which statically analyzes Dart code to 2 | # check for errors, warnings, and lints. 3 | # 4 | # The issues identified by the analyzer are surfaced in the UI of Dart-enabled 5 | # IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be 6 | # invoked from the command line by running `flutter analyze`. 7 | 8 | # The following line activates a set of recommended lints for Flutter apps, 9 | # packages, and plugins designed to encourage good coding practices. 10 | include: package:flutter_lints/flutter.yaml 11 | 12 | linter: 13 | # The lint rules applied to this project can be customized in the 14 | # section below to disable rules from the `package:flutter_lints/flutter.yaml` 15 | # included above or to enable additional rules. A list of all available lints 16 | # and their documentation is published at 17 | # https://dart-lang.github.io/linter/lints/index.html. 18 | # 19 | # Instead of disabling a lint rule for the entire project in the 20 | # section below, it can also be suppressed for a single line of code 21 | # or a specific dart file by using the `// ignore: name_of_lint` and 22 | # `// ignore_for_file: name_of_lint` syntax on the line or in the file 23 | # producing the lint. 24 | rules: 25 | # avoid_print: false # Uncomment to disable the `avoid_print` rule 26 | # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule 27 | 28 | # Additional information about this file can be found at 29 | # https://dart.dev/guides/language/analysis-options 30 | -------------------------------------------------------------------------------- /android/.gitignore: -------------------------------------------------------------------------------- 1 | gradle-wrapper.jar 2 | /.gradle 3 | /captures/ 4 | /gradlew 5 | /gradlew.bat 6 | /local.properties 7 | GeneratedPluginRegistrant.java 8 | 9 | # Remember to never publicly share your keystore. 10 | # See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app 11 | key.properties 12 | **/*.keystore 13 | **/*.jks 14 | -------------------------------------------------------------------------------- /android/app/build.gradle: -------------------------------------------------------------------------------- 1 | def localProperties = new Properties() 2 | def localPropertiesFile = rootProject.file('local.properties') 3 | if (localPropertiesFile.exists()) { 4 | localPropertiesFile.withReader('UTF-8') { reader -> 5 | localProperties.load(reader) 6 | } 7 | } 8 | def keyProperties = new Properties() 9 | def keyPropertiesFile = rootProject.file('aakey.properties') 10 | if (keyPropertiesFile.exists()) { 11 | keyPropertiesFile.withReader('UTF-8') { reader -> 12 | keyProperties.load(reader) 13 | } 14 | } 15 | 16 | 17 | def flutterRoot = localProperties.getProperty('flutter.sdk') 18 | if (flutterRoot == null) { 19 | throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") 20 | } 21 | 22 | def flutterVersionCode = localProperties.getProperty('flutter.versionCode') 23 | if (flutterVersionCode == null) { 24 | flutterVersionCode = '1' 25 | } 26 | 27 | def flutterVersionName = localProperties.getProperty('flutter.versionName') 28 | if (flutterVersionName == null) { 29 | flutterVersionName = '1.0' 30 | } 31 | 32 | apply plugin: 'com.android.application' 33 | apply plugin: 'kotlin-android' 34 | apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" 35 | 36 | android { 37 | compileSdkVersion 33 38 | ndkVersion flutter.ndkVersion 39 | 40 | compileOptions { 41 | sourceCompatibility JavaVersion.VERSION_1_8 42 | targetCompatibility JavaVersion.VERSION_1_8 43 | } 44 | 45 | kotlinOptions { 46 | jvmTarget = '1.8' 47 | } 48 | 49 | sourceSets { 50 | main.java.srcDirs += 'src/main/kotlin' 51 | } 52 | 53 | defaultConfig { 54 | // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). 55 | applicationId "com.app2m.chatgpt.hao_chatgpt" 56 | // You can update the following values to match your application needs. 57 | // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. 58 | minSdkVersion 19 59 | targetSdkVersion 33 60 | versionCode flutterVersionCode.toInteger() 61 | versionName flutterVersionName 62 | } 63 | 64 | if (!keyProperties.isEmpty()) { 65 | signingConfigs { 66 | release { 67 | keyAlias keyProperties['keyAlias'] 68 | keyPassword keyProperties['keyPassword'] 69 | storeFile file(keyProperties['storeFile']) 70 | storePassword keyProperties['storePassword'] 71 | } 72 | } 73 | } 74 | 75 | buildTypes { 76 | release { 77 | // TODO: Add your own signing config for the release build. 78 | // Signing with the debug keys for now, so `flutter run --release` works. 79 | signingConfig keyProperties.isEmpty() ? signingConfigs.debug : signingConfigs.release 80 | } 81 | } 82 | } 83 | 84 | flutter { 85 | source '../..' 86 | } 87 | 88 | dependencies { 89 | implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" 90 | } 91 | -------------------------------------------------------------------------------- /android/app/src/debug/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /android/app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 14 | 22 | 26 | 30 | 31 | 32 | 33 | 34 | 35 | 37 | 40 | 41 | 42 | -------------------------------------------------------------------------------- /android/app/src/main/kotlin/com/app2m/chatgpt/hao_chatgpt/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.app2m.chatgpt.hao_chatgpt 2 | 3 | import io.flutter.embedding.android.FlutterActivity 4 | 5 | class MainActivity: FlutterActivity() { 6 | } 7 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable-v21/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /android/app/src/main/res/drawable/launch_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 12 | 13 | -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/android/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/android/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /android/app/src/main/res/values-night/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /android/app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 9 | 15 | 18 | 19 | -------------------------------------------------------------------------------- /android/app/src/profile/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /android/build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | ext.kotlin_version = '1.6.10' 3 | repositories { 4 | google() 5 | mavenCentral() 6 | } 7 | 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:7.1.2' 10 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" 11 | } 12 | } 13 | 14 | allprojects { 15 | repositories { 16 | google() 17 | mavenCentral() 18 | } 19 | } 20 | 21 | rootProject.buildDir = '../build' 22 | subprojects { 23 | project.buildDir = "${rootProject.buildDir}/${project.name}" 24 | } 25 | subprojects { 26 | project.evaluationDependsOn(':app') 27 | } 28 | 29 | task clean(type: Delete) { 30 | delete rootProject.buildDir 31 | } 32 | -------------------------------------------------------------------------------- /android/gradle.properties: -------------------------------------------------------------------------------- 1 | org.gradle.jvmargs=-Xmx1536M 2 | android.useAndroidX=true 3 | android.enableJetifier=true 4 | -------------------------------------------------------------------------------- /android/gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | zipStoreBase=GRADLE_USER_HOME 4 | zipStorePath=wrapper/dists 5 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip 6 | -------------------------------------------------------------------------------- /android/settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app' 2 | 3 | def localPropertiesFile = new File(rootProject.projectDir, "local.properties") 4 | def properties = new Properties() 5 | 6 | assert localPropertiesFile.exists() 7 | localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } 8 | 9 | def flutterSdkPath = properties.getProperty("flutter.sdk") 10 | assert flutterSdkPath != null, "flutter.sdk not set in local.properties" 11 | apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" 12 | -------------------------------------------------------------------------------- /assets/images/openai.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/assets/images/openai.png -------------------------------------------------------------------------------- /build_runner.bat: -------------------------------------------------------------------------------- 1 | flutter pub run build_runner build --delete-conflicting-outputs -------------------------------------------------------------------------------- /ios/.gitignore: -------------------------------------------------------------------------------- 1 | **/dgph 2 | *.mode1v3 3 | *.mode2v3 4 | *.moved-aside 5 | *.pbxuser 6 | *.perspectivev3 7 | **/*sync/ 8 | .sconsign.dblite 9 | .tags* 10 | **/.vagrant/ 11 | **/DerivedData/ 12 | Icon? 13 | **/Pods/ 14 | **/.symlinks/ 15 | profile 16 | xcuserdata 17 | **/.generated/ 18 | Flutter/App.framework 19 | Flutter/Flutter.framework 20 | Flutter/Flutter.podspec 21 | Flutter/Generated.xcconfig 22 | Flutter/ephemeral/ 23 | Flutter/app.flx 24 | Flutter/app.zip 25 | Flutter/flutter_assets/ 26 | Flutter/flutter_export_environment.sh 27 | ServiceDefinitions.json 28 | Runner/GeneratedPluginRegistrant.* 29 | 30 | # Exceptions to above rules. 31 | !default.mode1v3 32 | !default.mode2v3 33 | !default.pbxuser 34 | !default.perspectivev3 35 | /Podfile.lock 36 | -------------------------------------------------------------------------------- /ios/Flutter/AppFrameworkInfo.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | en 7 | CFBundleExecutable 8 | App 9 | CFBundleIdentifier 10 | io.flutter.flutter.app 11 | CFBundleInfoDictionaryVersion 12 | 6.0 13 | CFBundleName 14 | App 15 | CFBundlePackageType 16 | FMWK 17 | CFBundleShortVersionString 18 | 1.0 19 | CFBundleSignature 20 | ???? 21 | CFBundleVersion 22 | 1.0 23 | MinimumOSVersion 24 | 11.0 25 | 26 | 27 | -------------------------------------------------------------------------------- /ios/Flutter/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /ios/Flutter/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /ios/Podfile: -------------------------------------------------------------------------------- 1 | # Uncomment this line to define a global platform for your project 2 | # platform :ios, '11.0' 3 | 4 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 5 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 6 | 7 | project 'Runner', { 8 | 'Debug' => :debug, 9 | 'Profile' => :release, 10 | 'Release' => :release, 11 | } 12 | 13 | def flutter_root 14 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) 15 | unless File.exist?(generated_xcode_build_settings_path) 16 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" 17 | end 18 | 19 | File.foreach(generated_xcode_build_settings_path) do |line| 20 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 21 | return matches[1].strip if matches 22 | end 23 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" 24 | end 25 | 26 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 27 | 28 | flutter_ios_podfile_setup 29 | 30 | target 'Runner' do 31 | use_frameworks! 32 | use_modular_headers! 33 | 34 | flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) 35 | end 36 | 37 | post_install do |installer| 38 | installer.pods_project.targets.each do |target| 39 | flutter_additional_ios_build_settings(target) 40 | end 41 | end 42 | -------------------------------------------------------------------------------- /ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 52 | 54 | 60 | 61 | 62 | 63 | 69 | 71 | 77 | 78 | 79 | 80 | 82 | 83 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /ios/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PreviewsEnabled 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /ios/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import UIKit 2 | import Flutter 3 | 4 | @UIApplicationMain 5 | @objc class AppDelegate: FlutterAppDelegate { 6 | override func application( 7 | _ application: UIApplication, 8 | didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? 9 | ) -> Bool { 10 | GeneratedPluginRegistrant.register(with: self) 11 | return super.application(application, didFinishLaunchingWithOptions: launchOptions) 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "20x20", 5 | "idiom" : "iphone", 6 | "filename" : "Icon-App-20x20@2x.png", 7 | "scale" : "2x" 8 | }, 9 | { 10 | "size" : "20x20", 11 | "idiom" : "iphone", 12 | "filename" : "Icon-App-20x20@3x.png", 13 | "scale" : "3x" 14 | }, 15 | { 16 | "size" : "29x29", 17 | "idiom" : "iphone", 18 | "filename" : "Icon-App-29x29@1x.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "29x29", 23 | "idiom" : "iphone", 24 | "filename" : "Icon-App-29x29@2x.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "29x29", 29 | "idiom" : "iphone", 30 | "filename" : "Icon-App-29x29@3x.png", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "size" : "40x40", 35 | "idiom" : "iphone", 36 | "filename" : "Icon-App-40x40@2x.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "40x40", 41 | "idiom" : "iphone", 42 | "filename" : "Icon-App-40x40@3x.png", 43 | "scale" : "3x" 44 | }, 45 | { 46 | "size" : "60x60", 47 | "idiom" : "iphone", 48 | "filename" : "Icon-App-60x60@2x.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "60x60", 53 | "idiom" : "iphone", 54 | "filename" : "Icon-App-60x60@3x.png", 55 | "scale" : "3x" 56 | }, 57 | { 58 | "size" : "20x20", 59 | "idiom" : "ipad", 60 | "filename" : "Icon-App-20x20@1x.png", 61 | "scale" : "1x" 62 | }, 63 | { 64 | "size" : "20x20", 65 | "idiom" : "ipad", 66 | "filename" : "Icon-App-20x20@2x.png", 67 | "scale" : "2x" 68 | }, 69 | { 70 | "size" : "29x29", 71 | "idiom" : "ipad", 72 | "filename" : "Icon-App-29x29@1x.png", 73 | "scale" : "1x" 74 | }, 75 | { 76 | "size" : "29x29", 77 | "idiom" : "ipad", 78 | "filename" : "Icon-App-29x29@2x.png", 79 | "scale" : "2x" 80 | }, 81 | { 82 | "size" : "40x40", 83 | "idiom" : "ipad", 84 | "filename" : "Icon-App-40x40@1x.png", 85 | "scale" : "1x" 86 | }, 87 | { 88 | "size" : "40x40", 89 | "idiom" : "ipad", 90 | "filename" : "Icon-App-40x40@2x.png", 91 | "scale" : "2x" 92 | }, 93 | { 94 | "size" : "76x76", 95 | "idiom" : "ipad", 96 | "filename" : "Icon-App-76x76@1x.png", 97 | "scale" : "1x" 98 | }, 99 | { 100 | "size" : "76x76", 101 | "idiom" : "ipad", 102 | "filename" : "Icon-App-76x76@2x.png", 103 | "scale" : "2x" 104 | }, 105 | { 106 | "size" : "83.5x83.5", 107 | "idiom" : "ipad", 108 | "filename" : "Icon-App-83.5x83.5@2x.png", 109 | "scale" : "2x" 110 | }, 111 | { 112 | "size" : "1024x1024", 113 | "idiom" : "ios-marketing", 114 | "filename" : "Icon-App-1024x1024@1x.png", 115 | "scale" : "1x" 116 | } 117 | ], 118 | "info" : { 119 | "version" : 1, 120 | "author" : "xcode" 121 | } 122 | } 123 | -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "universal", 5 | "filename" : "LaunchImage.png", 6 | "scale" : "1x" 7 | }, 8 | { 9 | "idiom" : "universal", 10 | "filename" : "LaunchImage@2x.png", 11 | "scale" : "2x" 12 | }, 13 | { 14 | "idiom" : "universal", 15 | "filename" : "LaunchImage@3x.png", 16 | "scale" : "3x" 17 | } 18 | ], 19 | "info" : { 20 | "version" : 1, 21 | "author" : "xcode" 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png -------------------------------------------------------------------------------- /ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md: -------------------------------------------------------------------------------- 1 | # Launch Screen Assets 2 | 3 | You can customize the launch screen with your own desired assets by replacing the image files in this directory. 4 | 5 | You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. -------------------------------------------------------------------------------- /ios/Runner/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | -------------------------------------------------------------------------------- /ios/Runner/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | -------------------------------------------------------------------------------- /ios/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CADisableMinimumFrameDurationOnPhone 6 | 7 | CFBundleDevelopmentRegion 8 | $(DEVELOPMENT_LANGUAGE) 9 | CFBundleDisplayName 10 | HaoChat 11 | CFBundleExecutable 12 | $(EXECUTABLE_NAME) 13 | CFBundleIdentifier 14 | $(PRODUCT_BUNDLE_IDENTIFIER) 15 | CFBundleInfoDictionaryVersion 16 | 6.0 17 | CFBundleName 18 | hao_chatgpt 19 | CFBundlePackageType 20 | APPL 21 | CFBundleShortVersionString 22 | $(FLUTTER_BUILD_NAME) 23 | CFBundleSignature 24 | ???? 25 | CFBundleVersion 26 | $(FLUTTER_BUILD_NUMBER) 27 | LSApplicationQueriesSchemes 28 | 29 | https 30 | 31 | LSRequiresIPhoneOS 32 | 33 | UIApplicationSupportsIndirectInputEvents 34 | 35 | UILaunchStoryboardName 36 | LaunchScreen 37 | UIMainStoryboardFile 38 | Main 39 | UISupportedInterfaceOrientations 40 | 41 | UIInterfaceOrientationPortrait 42 | UIInterfaceOrientationLandscapeLeft 43 | UIInterfaceOrientationLandscapeRight 44 | 45 | UISupportedInterfaceOrientations~ipad 46 | 47 | UIInterfaceOrientationPortrait 48 | UIInterfaceOrientationPortraitUpsideDown 49 | UIInterfaceOrientationLandscapeLeft 50 | UIInterfaceOrientationLandscapeRight 51 | 52 | UIViewControllerBasedStatusBarAppearance 53 | 54 | 55 | 56 | -------------------------------------------------------------------------------- /ios/Runner/Runner-Bridging-Header.h: -------------------------------------------------------------------------------- 1 | #import "GeneratedPluginRegistrant.h" 2 | -------------------------------------------------------------------------------- /l10n.bat: -------------------------------------------------------------------------------- 1 | :: 查看帮助命令 2 | :: flutter gen-l10n -h 3 | 4 | flutter gen-l10n -------------------------------------------------------------------------------- /l10n.yaml: -------------------------------------------------------------------------------- 1 | arb-dir: lib/l10n 2 | template-arb-file: intl_en.arb 3 | output-dir: lib/l10n/generated 4 | output-localization-file: l10n.dart 5 | output-class: S 6 | synthetic-package: false 7 | nullable-getter: false -------------------------------------------------------------------------------- /lib/l10n/generated/l10n_en.dart: -------------------------------------------------------------------------------- 1 | import 'package:intl/intl.dart' as intl; 2 | 3 | import 'l10n.dart'; 4 | 5 | /// The translations for English (`en`). 6 | class SEn extends S { 7 | SEn([String locale = 'en']) : super(locale); 8 | 9 | @override 10 | String get settings => 'Settings'; 11 | 12 | @override 13 | String get theme => 'Theme'; 14 | 15 | @override 16 | String get chooseTheme => 'Choose theme'; 17 | 18 | @override 19 | String get light => 'Light'; 20 | 21 | @override 22 | String get dark => 'Dark'; 23 | 24 | @override 25 | String get systemDefault => 'System default'; 26 | 27 | @override 28 | String get language => 'Language'; 29 | 30 | @override 31 | String get chooseLanguage => 'Choose language'; 32 | 33 | @override 34 | String get cancel => 'Cancel'; 35 | 36 | @override 37 | String get settingsReset => 'Reset'; 38 | 39 | @override 40 | String get about => 'About'; 41 | 42 | @override 43 | String get prompt => 'Prompt'; 44 | 45 | @override 46 | String get confirm => 'Confirm'; 47 | 48 | @override 49 | String get remove => 'Remove'; 50 | 51 | @override 52 | String get removeKeyNotice => 'This API key will immediately be removed.'; 53 | 54 | @override 55 | String createdDate(DateTime date) { 56 | final intl.DateFormat dateDateFormat = intl.DateFormat.yMMMd(localeName); 57 | final String dateString = dateDateFormat.format(date); 58 | 59 | return 'Created: $dateString'; 60 | } 61 | 62 | @override 63 | String get default_ => 'Default'; 64 | 65 | @override 66 | String get duplicateApiKey => 'Duplicate API key!'; 67 | 68 | @override 69 | String get appDescription => 'An unofficial open-source ChatGPT application'; 70 | 71 | @override 72 | String get resetToDefault => 'Reset to default'; 73 | 74 | @override 75 | String get haoChatIsPoweredByOpenAI => 'HaoChat is powered by OpenAI'; 76 | 77 | @override 78 | String get storeAPIkeyNotice => 'Please provide an OpenAI API key. This key will only be stored locally in your app cache.'; 79 | 80 | @override 81 | String get enterYourOpenAiApiKey => 'Enter your OpenAI API key'; 82 | 83 | @override 84 | String get done => 'Done'; 85 | 86 | @override 87 | String get navigateTo => 'Navigate to'; 88 | 89 | @override 90 | String get logInAndClick => 'Log in and click \"+ Create new secret key\"'; 91 | 92 | @override 93 | String get newChat => 'New chat'; 94 | 95 | @override 96 | String get deleteConversations => 'Delete conversations'; 97 | 98 | @override 99 | String get confirmDelete => 'Confirm delete'; 100 | 101 | @override 102 | String get selectAll => 'Select all'; 103 | 104 | @override 105 | String get delete => 'Delete'; 106 | 107 | @override 108 | String get home => 'Home'; 109 | 110 | @override 111 | String get shortcuts => 'Shortcuts'; 112 | 113 | @override 114 | String sendWith(String shortcut) { 115 | return 'Send with $shortcut'; 116 | } 117 | 118 | @override 119 | String get httpProxy => 'HTTP Proxy'; 120 | 121 | @override 122 | String get enableProxy => 'Enable proxy'; 123 | 124 | @override 125 | String get hostName => 'Host name'; 126 | 127 | @override 128 | String get portNumber => 'Port number'; 129 | 130 | @override 131 | String get resume => 'Resume'; 132 | 133 | @override 134 | String get systemPrompt => 'System prompt'; 135 | 136 | @override 137 | String get retry => 'Retry'; 138 | 139 | @override 140 | String get copied => 'Copied'; 141 | 142 | @override 143 | String get defaultSystemPrompt => 'You are a helpful assistant.'; 144 | 145 | @override 146 | String get systemPromptRecords => 'System prompt records'; 147 | 148 | @override 149 | String get haoChat => 'HaoChat'; 150 | 151 | @override 152 | String get openAI => 'OpenAI'; 153 | 154 | @override 155 | String get chatGPT => 'ChatGPT'; 156 | 157 | @override 158 | String get gpt35turbo => 'GPT-3.5-Turbo'; 159 | 160 | @override 161 | String get langEnglish => 'English'; 162 | 163 | @override 164 | String get langChinese => '简体中文'; 165 | 166 | @override 167 | String get gpt3 => 'GPT-3'; 168 | 169 | @override 170 | String get model => 'Model'; 171 | 172 | @override 173 | String get temperature => 'Temperature'; 174 | 175 | @override 176 | String get maximumLength => 'Maximum length'; 177 | 178 | @override 179 | String get topP => 'Top P'; 180 | 181 | @override 182 | String get frequencyPenalty => 'Frequency penalty'; 183 | 184 | @override 185 | String get presencePenalty => 'Presence penalty'; 186 | } 187 | -------------------------------------------------------------------------------- /lib/l10n/generated/l10n_zh.dart: -------------------------------------------------------------------------------- 1 | import 'package:intl/intl.dart' as intl; 2 | 3 | import 'l10n.dart'; 4 | 5 | /// The translations for Chinese (`zh`). 6 | class SZh extends S { 7 | SZh([String locale = 'zh']) : super(locale); 8 | 9 | @override 10 | String get settings => '设置'; 11 | 12 | @override 13 | String get theme => '主题'; 14 | 15 | @override 16 | String get chooseTheme => '选择主题'; 17 | 18 | @override 19 | String get light => '亮色模式'; 20 | 21 | @override 22 | String get dark => '暗色模式'; 23 | 24 | @override 25 | String get systemDefault => '系统默认'; 26 | 27 | @override 28 | String get language => '语言'; 29 | 30 | @override 31 | String get chooseLanguage => '选择语言'; 32 | 33 | @override 34 | String get cancel => '取消'; 35 | 36 | @override 37 | String get settingsReset => '重置'; 38 | 39 | @override 40 | String get about => '关于'; 41 | 42 | @override 43 | String get prompt => '提示'; 44 | 45 | @override 46 | String get confirm => '确定'; 47 | 48 | @override 49 | String get remove => '移除'; 50 | 51 | @override 52 | String get removeKeyNotice => '这个API key将立即被移除。'; 53 | 54 | @override 55 | String createdDate(DateTime date) { 56 | final intl.DateFormat dateDateFormat = intl.DateFormat.yMMMd(localeName); 57 | final String dateString = dateDateFormat.format(date); 58 | 59 | return '创建于: $dateString'; 60 | } 61 | 62 | @override 63 | String get default_ => '默认'; 64 | 65 | @override 66 | String get duplicateApiKey => '重复的 API key!'; 67 | 68 | @override 69 | String get appDescription => '一个非官方的开源 ChatGPT 应用'; 70 | 71 | @override 72 | String get resetToDefault => '重置为默认值'; 73 | 74 | @override 75 | String get haoChatIsPoweredByOpenAI => 'HaoChat由OpenAI驱动'; 76 | 77 | @override 78 | String get storeAPIkeyNotice => '请提供OpenAI API key。此密钥仅在您的应用程序缓存中存储。'; 79 | 80 | @override 81 | String get enterYourOpenAiApiKey => '输入你的 OpenAI API key'; 82 | 83 | @override 84 | String get done => '完成'; 85 | 86 | @override 87 | String get navigateTo => '导航到'; 88 | 89 | @override 90 | String get logInAndClick => '登录后,点击 \"+ Create new secret key\"'; 91 | 92 | @override 93 | String get newChat => '新对话'; 94 | 95 | @override 96 | String get deleteConversations => '删除对话'; 97 | 98 | @override 99 | String get confirmDelete => '确认删除'; 100 | 101 | @override 102 | String get selectAll => '全选'; 103 | 104 | @override 105 | String get delete => '删除'; 106 | 107 | @override 108 | String get home => '主页'; 109 | 110 | @override 111 | String get shortcuts => '快捷键'; 112 | 113 | @override 114 | String sendWith(String shortcut) { 115 | return '使用 $shortcut 发送'; 116 | } 117 | 118 | @override 119 | String get httpProxy => 'HTTP代理'; 120 | 121 | @override 122 | String get enableProxy => '启用代理'; 123 | 124 | @override 125 | String get hostName => '主机名'; 126 | 127 | @override 128 | String get portNumber => '端口号'; 129 | 130 | @override 131 | String get resume => '继续'; 132 | 133 | @override 134 | String get systemPrompt => '系统提示'; 135 | 136 | @override 137 | String get retry => '重试'; 138 | 139 | @override 140 | String get copied => '已复制'; 141 | 142 | @override 143 | String get defaultSystemPrompt => '你是一个乐于助人的助手。'; 144 | 145 | @override 146 | String get systemPromptRecords => '系统提示记录'; 147 | 148 | @override 149 | String get haoChat => 'HaoChat'; 150 | 151 | @override 152 | String get openAI => 'OpenAI'; 153 | 154 | @override 155 | String get chatGPT => 'ChatGPT'; 156 | 157 | @override 158 | String get gpt35turbo => 'GPT-3.5-Turbo'; 159 | 160 | @override 161 | String get langEnglish => 'English'; 162 | 163 | @override 164 | String get langChinese => '简体中文'; 165 | 166 | @override 167 | String get gpt3 => 'GPT-3'; 168 | 169 | @override 170 | String get model => 'Model'; 171 | 172 | @override 173 | String get temperature => 'Temperature'; 174 | 175 | @override 176 | String get maximumLength => 'Maximum length'; 177 | 178 | @override 179 | String get topP => 'Top P'; 180 | 181 | @override 182 | String get frequencyPenalty => 'Frequency penalty'; 183 | 184 | @override 185 | String get presencePenalty => 'Presence penalty'; 186 | } 187 | -------------------------------------------------------------------------------- /lib/l10n/intl_en.arb: -------------------------------------------------------------------------------- 1 | { 2 | "settings": "Settings", 3 | "theme": "Theme", 4 | "chooseTheme": "Choose theme", 5 | "light": "Light", 6 | "dark": "Dark", 7 | "systemDefault": "System default", 8 | "language": "Language", 9 | "chooseLanguage": "Choose language", 10 | "cancel": "Cancel", 11 | "settingsReset": "Reset", 12 | "about": "About", 13 | "prompt": "Prompt", 14 | "confirm": "Confirm", 15 | "remove": "Remove", 16 | "removeKeyNotice": "This API key will immediately be removed.", 17 | "createdDate": "Created: {date}", 18 | "@createdDate": { 19 | "placeholders": { 20 | "date": { 21 | "type": "DateTime", 22 | "format": "yMMMd", 23 | "isCustomDateFormat": "true", 24 | "description": "The API key created date." 25 | } 26 | } 27 | }, 28 | "default_": "Default", 29 | "duplicateApiKey": "Duplicate API key!", 30 | "appDescription": "An unofficial open-source ChatGPT application", 31 | "resetToDefault": "Reset to default", 32 | "haoChatIsPoweredByOpenAI": "HaoChat is powered by OpenAI", 33 | "storeAPIkeyNotice": "Please provide an OpenAI API key. This key will only be stored locally in your app cache.", 34 | "enterYourOpenAiApiKey": "Enter your OpenAI API key", 35 | "done": "Done", 36 | "navigateTo": "Navigate to", 37 | "logInAndClick": "Log in and click \"+ Create new secret key\"", 38 | "newChat": "New chat", 39 | "deleteConversations": "Delete conversations", 40 | "confirmDelete": "Confirm delete", 41 | "selectAll": "Select all", 42 | "delete": "Delete", 43 | "home": "Home", 44 | "shortcuts": "Shortcuts", 45 | "sendWith": "Send with {shortcut}", 46 | "@sendWith": { 47 | "placeholders": { 48 | "shortcut": { 49 | "type": "String" 50 | } 51 | } 52 | }, 53 | "httpProxy": "HTTP Proxy", 54 | "enableProxy": "Enable proxy", 55 | "hostName": "Host name", 56 | "portNumber": "Port number", 57 | "resume": "Resume", 58 | "systemPrompt": "System prompt", 59 | "retry": "Retry", 60 | "copied": "Copied", 61 | "defaultSystemPrompt": "You are a helpful assistant.", 62 | "systemPromptRecords": "System prompt records", 63 | 64 | "haoChat": "HaoChat", 65 | "openAI": "OpenAI", 66 | "chatGPT": "ChatGPT", 67 | "gpt35turbo": "GPT-3.5-Turbo", 68 | "langEnglish": "English", 69 | "langChinese": "简体中文", 70 | "gpt3": "GPT-3", 71 | "model": "Model", 72 | "temperature": "Temperature", 73 | "maximumLength": "Maximum length", 74 | "topP": "Top P", 75 | "frequencyPenalty": "Frequency penalty", 76 | "presencePenalty": "Presence penalty" 77 | } -------------------------------------------------------------------------------- /lib/l10n/intl_zh.arb: -------------------------------------------------------------------------------- 1 | { 2 | "settings": "设置", 3 | "theme": "主题", 4 | "chooseTheme": "选择主题", 5 | "light": "亮色模式", 6 | "dark": "暗色模式", 7 | "systemDefault": "系统默认", 8 | "language": "语言", 9 | "chooseLanguage": "选择语言", 10 | "cancel": "取消", 11 | "settingsReset": "重置", 12 | "about": "关于", 13 | "prompt": "提示", 14 | "confirm": "确定", 15 | "remove": "移除", 16 | "removeKeyNotice": "这个API key将立即被移除。", 17 | "createdDate": "创建于: {date}", 18 | "default_": "默认", 19 | "duplicateApiKey": "重复的 API key!", 20 | "appDescription": "一个非官方的开源 ChatGPT 应用", 21 | "resetToDefault": "重置为默认值", 22 | "haoChatIsPoweredByOpenAI": "HaoChat由OpenAI驱动", 23 | "storeAPIkeyNotice": "请提供OpenAI API key。此密钥仅在您的应用程序缓存中存储。", 24 | "enterYourOpenAiApiKey": "输入你的 OpenAI API key", 25 | "done": "完成", 26 | "navigateTo": "导航到", 27 | "logInAndClick": "登录后,点击 \"+ Create new secret key\"", 28 | "newChat": "新对话", 29 | "deleteConversations": "删除对话", 30 | "confirmDelete": "确认删除", 31 | "selectAll": "全选", 32 | "delete": "删除", 33 | "home": "主页", 34 | "shortcuts": "快捷键", 35 | "sendWith": "使用 {shortcut} 发送", 36 | "httpProxy": "HTTP代理", 37 | "enableProxy": "启用代理", 38 | "hostName": "主机名", 39 | "portNumber": "端口号", 40 | "resume": "继续", 41 | "systemPrompt": "系统提示", 42 | "retry": "重试", 43 | "copied": "已复制", 44 | "defaultSystemPrompt": "你是一个乐于助人的助手。", 45 | "systemPromptRecords": "系统提示记录" 46 | } -------------------------------------------------------------------------------- /lib/main.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/app_router.dart'; 2 | import 'package:hao_chatgpt/src/app_manager.dart'; 3 | import 'package:hao_chatgpt/src/constants.dart'; 4 | import 'package:hao_chatgpt/src/extensions.dart'; 5 | import 'package:hao_chatgpt/src/my_colors.dart'; 6 | import 'package:flutter/material.dart'; 7 | import 'package:flutter_localizations/flutter_localizations.dart'; 8 | import 'package:flutter_riverpod/flutter_riverpod.dart'; 9 | import 'package:hao_chatgpt/src/app_config.dart'; 10 | 11 | import 'l10n/generated/l10n.dart'; 12 | 13 | void main() async { 14 | WidgetsFlutterBinding.ensureInitialized(); 15 | await appManager.init(); 16 | runApp(const ProviderScope(child: MyApp())); 17 | } 18 | 19 | final StateProvider themeProvider = StateProvider((ref) => appConfig.themeMode); 20 | final StateProvider localeProvider = StateProvider((ref) => appConfig.locale); 21 | final StateProvider systemPromptProvider = StateProvider((ref) => ''); 22 | final StateProvider proxyProvider = StateProvider((ref) => appConfig.httpProxy); 23 | 24 | class MyApp extends ConsumerWidget { 25 | const MyApp({super.key}); 26 | @override 27 | Widget build(BuildContext context, WidgetRef ref) { 28 | setSystemNavigationBarColor(ref.watch(themeProvider)); 29 | return MaterialApp.router( 30 | title: 'HaoChat', 31 | debugShowCheckedModeBanner: false, 32 | onGenerateTitle: (context) => S.of(context).haoChat, 33 | locale: ref.watch(localeProvider), 34 | localizationsDelegates: const [ 35 | S.delegate, 36 | GlobalMaterialLocalizations.delegate, 37 | GlobalWidgetsLocalizations.delegate, 38 | GlobalCupertinoLocalizations.delegate, 39 | ], 40 | supportedLocales: const [ 41 | Constants.enLocale, 42 | Constants.zhLocale, 43 | ], 44 | themeMode: ref.watch(themeProvider), 45 | theme: ThemeData.light( 46 | useMaterial3: true, 47 | ).copyWith( 48 | extensions: >[MyColors.light], 49 | splashFactory: NoSplash.splashFactory, 50 | ), 51 | darkTheme: ThemeData.dark(useMaterial3: true).copyWith( 52 | extensions: >[MyColors.dark], 53 | splashFactory: NoSplash.splashFactory, 54 | ), 55 | routerConfig: AppRouter().goRouter, 56 | ); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /lib/src/app_manager.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/cupertino.dart'; 2 | import 'package:flutter/services.dart'; 3 | import 'package:hao_chatgpt/src/app_config.dart'; 4 | import 'package:yaml/yaml.dart'; 5 | 6 | class AppManager { 7 | bool _isInitialized = false; 8 | 9 | bool get isInitialized => _isInitialized; 10 | 11 | String? _innerApiKey; 12 | 13 | String? get innerApiKey => _innerApiKey; 14 | 15 | String? get openaiApiKey => appConfig.apiKey ?? _innerApiKey; 16 | 17 | AppManager._internal(); 18 | 19 | static final AppManager _appManager = AppManager._internal(); 20 | 21 | factory AppManager() => _appManager; 22 | 23 | Future init() async { 24 | if (!_isInitialized) { 25 | await appConfig.init(); 26 | await _loadInnerApiKey(); 27 | } 28 | _isInitialized = true; 29 | } 30 | 31 | Future _loadInnerApiKey() async { 32 | try { 33 | String str = await rootBundle.loadString('openai.yaml'); 34 | var doc = loadYaml(str); 35 | _innerApiKey = doc['api_key']; 36 | } catch (e) { 37 | debugPrint('openai.yaml not found.'); 38 | } 39 | } 40 | } 41 | 42 | final AppManager appManager = AppManager(); 43 | -------------------------------------------------------------------------------- /lib/src/app_router.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:go_router/go_router.dart'; 3 | import 'package:hao_chatgpt/src/screens/chat.dart'; 4 | import 'package:hao_chatgpt/src/screens/chat_turbo.dart'; 5 | import 'package:hao_chatgpt/src/screens/settings/settings_apikey.dart'; 6 | import 'package:hao_chatgpt/src/screens/settings/settings_gpt3.dart'; 7 | import 'package:hao_chatgpt/src/screens/home.dart'; 8 | import 'package:hao_chatgpt/src/screens/settings.dart'; 9 | 10 | import 'screens/settings/settings_gpt35turbo.dart'; 11 | import 'screens/webview.dart'; 12 | 13 | class AppUri { 14 | static const root = '/'; 15 | static const chat = 'chat'; 16 | static const chatTurbo = 'chat-turbo'; 17 | static const settings = 'settings'; 18 | static const settingsGpt3 = 'settings/gpt3'; 19 | static const settingsGpt35Turbo = 'settings/gpt35turbo'; 20 | static const settingsApikey = 'settings/apikey'; 21 | static const webview = 'webview'; 22 | } 23 | 24 | class AppRouter { 25 | AppRouter._internal(); 26 | static final AppRouter _appRouter = AppRouter._internal(); 27 | factory AppRouter() => _appRouter; 28 | 29 | /// The route configuration. 30 | final GoRouter _goRouter = GoRouter( 31 | restorationScopeId: 'go_router', 32 | initialLocation: AppUri.root, 33 | routes: [ 34 | GoRoute( 35 | path: AppUri.root, 36 | builder: (BuildContext context, GoRouterState state) => 37 | const HomePage(), 38 | routes: [ 39 | GoRoute( 40 | path: AppUri.settings, 41 | builder: (BuildContext context, GoRouterState state) => 42 | const SettingsPage(), 43 | routes: [ 44 | GoRoute( 45 | path: AppUri.settingsGpt3.replaceFirst('${AppUri.settings}/', ''), 46 | builder: (BuildContext context, GoRouterState state) => 47 | const CustomizeGpt3Page(), 48 | ), 49 | GoRoute( 50 | path: AppUri.settingsGpt35Turbo.replaceFirst('${AppUri.settings}/', ''), 51 | builder: (BuildContext context, GoRouterState state) => 52 | const SettingsGpt35Turbo(), 53 | ), 54 | GoRoute( 55 | path: AppUri.settingsApikey.replaceFirst('${AppUri.settings}/', ''), 56 | builder: (BuildContext context, GoRouterState state) => 57 | const SettingsApikeyPage(), 58 | ), 59 | ], 60 | ), 61 | GoRoute( 62 | path: AppUri.chat, 63 | builder: (BuildContext context, GoRouterState state) => 64 | ChatPage(chatId: int.tryParse(state.queryParams['id'] ?? ''),), 65 | ), 66 | GoRoute( 67 | path: AppUri.chatTurbo, 68 | builder: (BuildContext context, GoRouterState state) => 69 | ChatTurbo(chatId: int.tryParse(state.queryParams['id'] ?? ''),), 70 | ), 71 | GoRoute( 72 | path: AppUri.webview, 73 | builder: (BuildContext context, GoRouterState state) => WebviewPage( 74 | url: state.queryParams['url'], 75 | title: state.queryParams['title'], 76 | ), 77 | ), 78 | ], 79 | ), 80 | ], 81 | ); 82 | 83 | GoRouter get goRouter => _goRouter; 84 | } 85 | -------------------------------------------------------------------------------- /lib/src/app_shortcuts.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:flutter/services.dart'; 5 | 6 | import 'app_config.dart'; 7 | 8 | Map getShortcutsKeys() { 9 | Map keyMap = {'Enter': LogicalKeySet(LogicalKeyboardKey.enter)}; 10 | if(Platform.isWindows || Platform.isLinux || Platform.isFuchsia) { 11 | keyMap['Ctrl + Enter'] = LogicalKeySet(LogicalKeyboardKey.control, LogicalKeyboardKey.enter); 12 | } else if(Platform.isMacOS) { 13 | // \u2318 + Enter 14 | // ⌘ + Enter 15 | keyMap['⌘ + Enter'] = LogicalKeySet(LogicalKeyboardKey.meta, LogicalKeyboardKey.enter); 16 | } 17 | return keyMap; 18 | } 19 | 20 | Map getShortcutsIntents() { 21 | if(Platform.isAndroid || Platform.isIOS) { 22 | return {}; 23 | } else { 24 | List keySets = getShortcutsKeys().values.toList(); 25 | keySets.remove(appConfig.shortcutsSend); 26 | return { 27 | appConfig.shortcutsSend!: const SendIntent(), 28 | keySets.first: const NewLineIntent(), 29 | }; 30 | } 31 | } 32 | 33 | /// An ActionDispatcher that logs all the actions that it invokes. 34 | class LoggingActionDispatcher extends ActionDispatcher { 35 | @override 36 | Object? invokeAction( 37 | covariant Action action, 38 | covariant Intent intent, [ 39 | BuildContext? context, 40 | ]) { 41 | debugPrint('Action invoked: $action($intent) from $context'); 42 | super.invokeAction(action, intent, context); 43 | return null; 44 | } 45 | } 46 | 47 | class SendIntent extends Intent { 48 | const SendIntent(); 49 | } 50 | 51 | class SendAction extends Action { 52 | SendAction(this.callback); 53 | 54 | final VoidCallback callback; 55 | 56 | @override 57 | Object? invoke(covariant SendIntent intent) { 58 | callback(); 59 | return null; 60 | } 61 | } 62 | 63 | 64 | class NewLineIntent extends Intent { 65 | const NewLineIntent(); 66 | } 67 | 68 | class NewLineAction extends Action { 69 | NewLineAction(this.controller); 70 | final TextEditingController controller; 71 | 72 | @override 73 | Object? invoke(covariant NewLineIntent intent) { 74 | String value = controller.text; 75 | int start = controller.selection.start; 76 | String newValue = value.replaceRange(controller.selection.start, controller.selection.end, '\n'); 77 | controller.text = newValue; 78 | controller.selection = TextSelection.fromPosition(TextPosition(offset: start+1),); 79 | return null; 80 | } 81 | } -------------------------------------------------------------------------------- /lib/src/constants.dart: -------------------------------------------------------------------------------- 1 | import 'dart:core'; 2 | import 'dart:ui'; 3 | 4 | class Constants { 5 | static const String splitTag = '<|>'; 6 | static const String gpt3ModelDavinci003 = 'text-davinci-003'; 7 | static const String gpt3ModelCurie001 = 'text-curie-001'; 8 | static const String gpt3ModelBabbage001 = 'text-babbage-001'; 9 | static const String gpt3ModelAda001 = 'text-ada-001'; 10 | static const List gpt3Models = [ 11 | gpt3ModelDavinci003, 12 | gpt3ModelCurie001, 13 | gpt3ModelBabbage001, 14 | gpt3ModelAda001 15 | ]; 16 | 17 | static const Locale enLocale = Locale('en', ''); 18 | static const Locale zhLocale = Locale('zh', ''); 19 | 20 | static const String aboutChatGPTUrl = 'https://openai.com/blog/chatgpt/'; 21 | static const String aboutGPT3ModelsUrl = 22 | 'https://beta.openai.com/docs/models/gpt-3'; 23 | static const String aboutGPT35ModelsUrl = 24 | 'https://platform.openai.com/docs/models/gpt-3-5'; 25 | static const String aboutCodexModelsUrl = 26 | 'https://beta.openai.com/docs/models/codex'; 27 | static const String apiCompletionsUrl = 28 | 'https://platform.openai.com/docs/api-reference/completions/create'; 29 | static const String apiReferenceChatUrl = 30 | 'https://platform.openai.com/docs/api-reference/chat/create'; 31 | static const String haoChatGitHubUrl = 32 | 'https://github.com/conghaonet/hao_chatgpt'; 33 | static const String openAiApiKeysUrl = 34 | 'https://beta.openai.com/account/api-keys'; 35 | 36 | static const String blankUrl = 'about:blank'; 37 | 38 | static const String androidActionMain = 'android.intent.action.MAIN'; 39 | static const String androidCategoryHome = 'android.intent.category.HOME'; 40 | 41 | static const int systemPromptLimit = 10; 42 | } 43 | 44 | class ChatRole { 45 | static const system = 'system', user = 'user', assistant = 'assistant'; 46 | } 47 | 48 | class FinishReason { 49 | static const length = 'length', stop = 'stop'; 50 | } 51 | 52 | enum GptModel { 53 | gpt35Turbo(model: 'gpt-3.5-turbo', maxTokens: 4096); 54 | 55 | const GptModel({required this.model, required this.maxTokens}); 56 | 57 | final String model; 58 | final int maxTokens; 59 | } -------------------------------------------------------------------------------- /lib/src/db/hao_database.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:drift/drift.dart'; 4 | import 'package:drift/native.dart'; 5 | import 'package:path_provider/path_provider.dart'; 6 | import 'package:path/path.dart' as p; 7 | 8 | 9 | part 'hao_database.g.dart'; 10 | 11 | mixin AutoIncrementingPrimaryKey on Table { 12 | IntColumn get id => integer().autoIncrement()(); 13 | } 14 | 15 | @Deprecated('Use Chats instead') 16 | class ChatTitles extends Table with AutoIncrementingPrimaryKey { 17 | TextColumn get title => text()(); 18 | BoolColumn get isFavorite => boolean().nullable()(); 19 | DateTimeColumn get chatDate => dateTime()(); 20 | } 21 | 22 | @Deprecated('Use Messages instead') 23 | class Conversations extends Table with AutoIncrementingPrimaryKey { 24 | IntColumn get titleId => integer().references(ChatTitles, #id)(); 25 | TextColumn get inputMessage => text()(); 26 | TextColumn get prompt => text()(); 27 | TextColumn get completion => text().nullable()(); 28 | BoolColumn get isError => boolean().nullable()(); 29 | DateTimeColumn get promptDate => dateTime()(); 30 | } 31 | 32 | class Chats extends Table with AutoIncrementingPrimaryKey { 33 | TextColumn get title => text()(); 34 | TextColumn get system => text()(); 35 | BoolColumn get isFavorite => boolean()(); 36 | DateTimeColumn get chatDateTime => dateTime()(); 37 | } 38 | 39 | class Messages extends Table with AutoIncrementingPrimaryKey { 40 | IntColumn get chatId => integer().references(Chats, #id)(); 41 | TextColumn get role => text()(); 42 | TextColumn get content => text()(); 43 | BoolColumn get isResponse => boolean()(); 44 | IntColumn get promptTokens => integer().nullable()(); 45 | IntColumn get completionTokens => integer().nullable()(); 46 | IntColumn get totalTokens => integer().nullable()(); 47 | TextColumn get finishReason => text().nullable()(); 48 | BoolColumn get isFavorite => boolean()(); 49 | DateTimeColumn get msgDateTime => dateTime()(); 50 | } 51 | 52 | class SystemPrompts extends Table with AutoIncrementingPrimaryKey { 53 | TextColumn get prompt => text()(); 54 | DateTimeColumn get createDateTime => dateTime()(); 55 | } 56 | 57 | @DriftDatabase(tables: [ChatTitles, Conversations, Chats, Messages, SystemPrompts]) 58 | class HaoDatabase extends _$HaoDatabase { 59 | HaoDatabase() : super(_openConnection()); 60 | 61 | // you should bump this number whenever you change or add a table definition. 62 | // Migrations are covered later in the documentation. 63 | @override 64 | int get schemaVersion => 3; 65 | 66 | @override 67 | MigrationStrategy get migration { 68 | return MigrationStrategy( 69 | onUpgrade: (m, from, to) async { 70 | for (var step = from + 1; step <= to; step++) { 71 | switch (step) { 72 | case 2: 73 | m.createTable(chats); 74 | m.createTable(messages); 75 | break; 76 | case 3: 77 | m.createTable(systemPrompts); 78 | break; 79 | } 80 | } 81 | }, 82 | beforeOpen: (details) async { 83 | // Make sure that foreign keys are enabled 84 | await customStatement('PRAGMA foreign_keys = ON'); 85 | }, 86 | ); 87 | } 88 | } 89 | 90 | LazyDatabase _openConnection() { 91 | // the LazyDatabase util lets us find the right location for the file async. 92 | return LazyDatabase(() async { 93 | // put the database file, called db.sqlite here, into the documents folder 94 | // for your app. 95 | final dbFolder = await getApplicationDocumentsDirectory(); 96 | final file = File(p.join(dbFolder.path, 'hao_chat.db')); 97 | return NativeDatabase.createInBackground(file); 98 | }); 99 | } 100 | 101 | final haoDatabase = HaoDatabase(); -------------------------------------------------------------------------------- /lib/src/my_colors.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | 3 | @immutable 4 | class MyColors extends ThemeExtension { 5 | static MyColors light = MyColors( 6 | systemNavigationBarColor: Colors.white, 7 | completionBackgroundColor: Colors.grey.shade200, 8 | ); 9 | static const dark = MyColors( 10 | systemNavigationBarColor: Colors.black, 11 | completionBackgroundColor: Colors.black54, 12 | ); 13 | 14 | const MyColors({ 15 | required this.systemNavigationBarColor, 16 | required this.completionBackgroundColor, 17 | }); 18 | 19 | final Color? systemNavigationBarColor; 20 | final Color? completionBackgroundColor; 21 | 22 | @override 23 | MyColors copyWith({ 24 | Color? systemNavigationBarColor, 25 | Color? completionBackgroundColor, 26 | }) { 27 | return MyColors( 28 | systemNavigationBarColor: systemNavigationBarColor, 29 | completionBackgroundColor: completionBackgroundColor, 30 | ); 31 | } 32 | 33 | @override 34 | ThemeExtension lerp(ThemeExtension? other, double t) { 35 | if (other is! MyColors) { 36 | return this; 37 | } 38 | return MyColors( 39 | systemNavigationBarColor: Color.lerp( 40 | systemNavigationBarColor, other.systemNavigationBarColor, t), 41 | completionBackgroundColor: Color.lerp( 42 | completionBackgroundColor, other.completionBackgroundColor, t), 43 | ); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /lib/src/network/entity/api_key_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | part 'api_key_entity.g.dart'; 4 | 5 | @JsonSerializable(explicitToJson: true) 6 | class ApiKeyEntity { 7 | final String key; 8 | final DateTime createdTime; 9 | 10 | ApiKeyEntity(this.key, this.createdTime); 11 | 12 | factory ApiKeyEntity.fromJson(Map json) => 13 | _$ApiKeyEntityFromJson(json); 14 | 15 | Map toJson() => _$ApiKeyEntityToJson(this); 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/network/entity/api_key_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'api_key_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | ApiKeyEntity _$ApiKeyEntityFromJson(Map json) => ApiKeyEntity( 10 | json['key'] as String, 11 | DateTime.parse(json['createdTime'] as String), 12 | ); 13 | 14 | Map _$ApiKeyEntityToJson(ApiKeyEntity instance) => 15 | { 16 | 'key': instance.key, 17 | 'createdTime': instance.createdTime.toIso8601String(), 18 | }; 19 | -------------------------------------------------------------------------------- /lib/src/network/entity/dio_error_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | part 'dio_error_entity.g.dart'; 4 | 5 | @JsonSerializable(explicitToJson: true) 6 | class DioErrorEntity { 7 | final String? error; 8 | final String? message; 9 | final String? type; 10 | final String? code; 11 | 12 | DioErrorEntity({this.error, this.message, this.type, this.code}); 13 | 14 | factory DioErrorEntity.fromJson(Map json) => 15 | _$DioErrorEntityFromJson(json); 16 | 17 | Map toJson() => _$DioErrorEntityToJson(this); 18 | } 19 | -------------------------------------------------------------------------------- /lib/src/network/entity/dio_error_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'dio_error_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | DioErrorEntity _$DioErrorEntityFromJson(Map json) => 10 | DioErrorEntity( 11 | error: json['error'] as String?, 12 | message: json['message'] as String?, 13 | type: json['type'] as String?, 14 | code: json['code'] as String?, 15 | ); 16 | 17 | Map _$DioErrorEntityToJson(DioErrorEntity instance) => 18 | { 19 | 'error': instance.error, 20 | 'message': instance.message, 21 | 'type': instance.type, 22 | 'code': instance.code, 23 | }; 24 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/network/entity/openai/chat_message_entity.dart'; 2 | import 'package:json_annotation/json_annotation.dart'; 3 | 4 | import 'completion_usage_entity.dart'; 5 | 6 | part 'chat_entity.g.dart'; 7 | 8 | @JsonSerializable(explicitToJson: true) 9 | class ChatEntity { 10 | final String id; 11 | final String object; 12 | final int created; 13 | final String model; 14 | final List? choices; 15 | final CompletionUsageEntity? usage; 16 | 17 | ChatEntity( 18 | this.id, this.object, this.created, this.model, this.choices, this.usage); 19 | 20 | factory ChatEntity.fromJson(Map json) => 21 | _$ChatEntityFromJson(json); 22 | 23 | Map toJson() => _$ChatEntityToJson(this); 24 | } 25 | 26 | @JsonSerializable(explicitToJson: true) 27 | class ChatChoiceEntity { 28 | final int? index; 29 | final ChatMessageEntity? message; 30 | /// stop, length 31 | @JsonKey(name: "finish_reason") 32 | final String? finishReason; 33 | 34 | ChatChoiceEntity( 35 | this.index, this.message, this.finishReason); 36 | 37 | factory ChatChoiceEntity.fromJson(Map json) => 38 | _$ChatChoiceEntityFromJson(json); 39 | 40 | Map toJson() => _$ChatChoiceEntityToJson(this); 41 | } 42 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'chat_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | ChatEntity _$ChatEntityFromJson(Map json) => ChatEntity( 10 | json['id'] as String, 11 | json['object'] as String, 12 | json['created'] as int, 13 | json['model'] as String, 14 | (json['choices'] as List?) 15 | ?.map((e) => ChatChoiceEntity.fromJson(e as Map)) 16 | .toList(), 17 | json['usage'] == null 18 | ? null 19 | : CompletionUsageEntity.fromJson( 20 | json['usage'] as Map), 21 | ); 22 | 23 | Map _$ChatEntityToJson(ChatEntity instance) => 24 | { 25 | 'id': instance.id, 26 | 'object': instance.object, 27 | 'created': instance.created, 28 | 'model': instance.model, 29 | 'choices': instance.choices?.map((e) => e.toJson()).toList(), 30 | 'usage': instance.usage?.toJson(), 31 | }; 32 | 33 | ChatChoiceEntity _$ChatChoiceEntityFromJson(Map json) => 34 | ChatChoiceEntity( 35 | json['index'] as int?, 36 | json['message'] == null 37 | ? null 38 | : ChatMessageEntity.fromJson(json['message'] as Map), 39 | json['finish_reason'] as String?, 40 | ); 41 | 42 | Map _$ChatChoiceEntityToJson(ChatChoiceEntity instance) => 43 | { 44 | 'index': instance.index, 45 | 'message': instance.message?.toJson(), 46 | 'finish_reason': instance.finishReason, 47 | }; 48 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_message_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | 4 | part 'chat_message_entity.g.dart'; 5 | 6 | @JsonSerializable(explicitToJson: true) 7 | class ChatMessageEntity { 8 | final String role; 9 | final String content; 10 | ChatMessageEntity({required this.role, required this.content}); 11 | 12 | factory ChatMessageEntity.fromJson(Map json) => 13 | _$ChatMessageEntityFromJson(json); 14 | 15 | Map toJson() => _$ChatMessageEntityToJson(this); 16 | } 17 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_message_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'chat_message_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | ChatMessageEntity _$ChatMessageEntityFromJson(Map json) => 10 | ChatMessageEntity( 11 | role: json['role'] as String, 12 | content: json['content'] as String, 13 | ); 14 | 15 | Map _$ChatMessageEntityToJson(ChatMessageEntity instance) => 16 | { 17 | 'role': instance.role, 18 | 'content': instance.content, 19 | }; 20 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_query_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/constants.dart'; 2 | import 'package:hao_chatgpt/src/network/entity/openai/chat_message_entity.dart'; 3 | import 'package:json_annotation/json_annotation.dart'; 4 | 5 | part 'chat_query_entity.g.dart'; 6 | 7 | @JsonSerializable(explicitToJson: true) 8 | class ChatQueryEntity { 9 | /// ID of the model to use. Currently, only gpt-3.5-turbo and gpt-3.5-turbo-0301 are supported. 10 | String model; 11 | 12 | /// The messages to generate chat completions for, in the chat format. 13 | List messages; 14 | 15 | /// 更高的值意味着模型将承担更多的风险。 16 | /// 对于更有创意的应用程序,可以尝试0.9,对于有明确答案的应用程序,可以尝试0。 17 | @JsonKey(defaultValue: 0.7) 18 | double temperature; 19 | 20 | /// An alternative to sampling with temperature, called nucleus sampling, 21 | /// where the model considers the results of the tokens with top_p probability mass. 22 | /// So 0.1 means only the tokens comprising the top 10% probability mass are considered. 23 | /// We generally recommend altering this or temperature but not both. 24 | @JsonKey(name: 'top_p', defaultValue: 1.0) 25 | double topP; 26 | 27 | /// How many chat completion choices to generate for each input message. 28 | @JsonKey(name: 'n', defaultValue: 1) 29 | int numOfChoices; 30 | 31 | /// If set, partial message deltas will be sent, like in ChatGPT. 32 | /// Tokens will be sent as data-only server-sent events as they become available, 33 | /// with the stream terminated by a data: [DONE] message. 34 | @JsonKey(defaultValue: false) 35 | bool stream; 36 | 37 | /// Up to 4 sequences where the API will stop generating further tokens. 38 | List? stop; 39 | 40 | /// The maximum number of tokens allowed for the generated answer. 41 | /// By default, the number of tokens the model can return will be (4096 - prompt tokens). 42 | @JsonKey(name: 'max_tokens', defaultValue: 256) 43 | int maxTokens; 44 | 45 | /// Number between -2.0 and 2.0. 46 | /// Positive values penalize new tokens based on whether they appear in the text so far, 47 | /// increasing the model's likelihood to talk about new topics. 48 | @JsonKey(name: 'presence_penalty', defaultValue: 0.0) 49 | double presencePenalty; 50 | 51 | /// Number between -2.0 and 2.0. 52 | /// Positive values penalize new tokens based on their existing frequency in the text so far, 53 | /// decreasing the model's likelihood to repeat the same line verbatim. 54 | @JsonKey(name: 'frequency_penalty', defaultValue: 0.0) 55 | double frequencyPenalty; 56 | 57 | ChatQueryEntity({ 58 | String? model, 59 | required this.messages, 60 | this.temperature = 0.7, 61 | this.topP = 1.0, 62 | this.numOfChoices = 1, 63 | this.stream = false, 64 | this.stop, 65 | this.maxTokens = 256, 66 | this.presencePenalty = 0.0, 67 | this.frequencyPenalty = 0.0 68 | }) : model = model ?? GptModel.gpt35Turbo.model; 69 | factory ChatQueryEntity.fromJson(Map json) => 70 | _$ChatQueryEntityFromJson(json); 71 | 72 | Map toJson() => _$ChatQueryEntityToJson(this); 73 | } 74 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/chat_query_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'chat_query_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | ChatQueryEntity _$ChatQueryEntityFromJson(Map json) => 10 | ChatQueryEntity( 11 | model: json['model'] as String?, 12 | messages: (json['messages'] as List) 13 | .map((e) => ChatMessageEntity.fromJson(e as Map)) 14 | .toList(), 15 | temperature: (json['temperature'] as num?)?.toDouble() ?? 0.7, 16 | topP: (json['top_p'] as num?)?.toDouble() ?? 1.0, 17 | numOfChoices: json['n'] as int? ?? 1, 18 | stream: json['stream'] as bool? ?? false, 19 | stop: (json['stop'] as List?)?.map((e) => e as String).toList(), 20 | maxTokens: json['max_tokens'] as int? ?? 256, 21 | presencePenalty: (json['presence_penalty'] as num?)?.toDouble() ?? 0.0, 22 | frequencyPenalty: (json['frequency_penalty'] as num?)?.toDouble() ?? 0.0, 23 | ); 24 | 25 | Map _$ChatQueryEntityToJson(ChatQueryEntity instance) => 26 | { 27 | 'model': instance.model, 28 | 'messages': instance.messages.map((e) => e.toJson()).toList(), 29 | 'temperature': instance.temperature, 30 | 'top_p': instance.topP, 31 | 'n': instance.numOfChoices, 32 | 'stream': instance.stream, 33 | 'stop': instance.stop, 34 | 'max_tokens': instance.maxTokens, 35 | 'presence_penalty': instance.presencePenalty, 36 | 'frequency_penalty': instance.frequencyPenalty, 37 | }; 38 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completion_usage_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | part 'completion_usage_entity.g.dart'; 4 | 5 | @JsonSerializable(explicitToJson: true) 6 | class CompletionUsageEntity { 7 | @JsonKey(name: "prompt_tokens") 8 | final int? promptTokens; 9 | @JsonKey(name: "completion_tokens") 10 | final int? completionTokens; 11 | @JsonKey(name: "total_tokens") 12 | final int? totalTokens; 13 | 14 | CompletionUsageEntity( 15 | this.promptTokens, this.completionTokens, this.totalTokens); 16 | 17 | factory CompletionUsageEntity.fromJson(Map json) => 18 | _$CompletionUsageEntityFromJson(json); 19 | 20 | Map toJson() => _$CompletionUsageEntityToJson(this); 21 | } -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completion_usage_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'completion_usage_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | CompletionUsageEntity _$CompletionUsageEntityFromJson( 10 | Map json) => 11 | CompletionUsageEntity( 12 | json['prompt_tokens'] as int?, 13 | json['completion_tokens'] as int?, 14 | json['total_tokens'] as int?, 15 | ); 16 | 17 | Map _$CompletionUsageEntityToJson( 18 | CompletionUsageEntity instance) => 19 | { 20 | 'prompt_tokens': instance.promptTokens, 21 | 'completion_tokens': instance.completionTokens, 22 | 'total_tokens': instance.totalTokens, 23 | }; 24 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completions_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | import 'completion_usage_entity.dart'; 4 | 5 | part 'completions_entity.g.dart'; 6 | 7 | @JsonSerializable(explicitToJson: true) 8 | class CompletionsEntity { 9 | final String id; 10 | final String object; 11 | final int created; 12 | final String model; 13 | final List? choices; 14 | final CompletionUsageEntity? usage; 15 | 16 | CompletionsEntity( 17 | this.id, this.object, this.created, this.model, this.choices, this.usage); 18 | 19 | factory CompletionsEntity.fromJson(Map json) => 20 | _$CompletionsEntityFromJson(json); 21 | 22 | Map toJson() => _$CompletionsEntityToJson(this); 23 | } 24 | 25 | @JsonSerializable(explicitToJson: true) 26 | class CompletionsChoiceEntity { 27 | final String? text; 28 | final int? index; 29 | final int? logprobs; 30 | 31 | /// stop, length 32 | @JsonKey(name: "finish_reason") 33 | final String? finishReason; 34 | 35 | CompletionsChoiceEntity( 36 | this.text, this.index, this.logprobs, this.finishReason); 37 | 38 | factory CompletionsChoiceEntity.fromJson(Map json) => 39 | _$CompletionsChoiceEntityFromJson(json); 40 | 41 | Map toJson() => _$CompletionsChoiceEntityToJson(this); 42 | } 43 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completions_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'completions_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | CompletionsEntity _$CompletionsEntityFromJson(Map json) => 10 | CompletionsEntity( 11 | json['id'] as String, 12 | json['object'] as String, 13 | json['created'] as int, 14 | json['model'] as String, 15 | (json['choices'] as List?) 16 | ?.map((e) => 17 | CompletionsChoiceEntity.fromJson(e as Map)) 18 | .toList(), 19 | json['usage'] == null 20 | ? null 21 | : CompletionUsageEntity.fromJson( 22 | json['usage'] as Map), 23 | ); 24 | 25 | Map _$CompletionsEntityToJson(CompletionsEntity instance) => 26 | { 27 | 'id': instance.id, 28 | 'object': instance.object, 29 | 'created': instance.created, 30 | 'model': instance.model, 31 | 'choices': instance.choices?.map((e) => e.toJson()).toList(), 32 | 'usage': instance.usage?.toJson(), 33 | }; 34 | 35 | CompletionsChoiceEntity _$CompletionsChoiceEntityFromJson( 36 | Map json) => 37 | CompletionsChoiceEntity( 38 | json['text'] as String?, 39 | json['index'] as int?, 40 | json['logprobs'] as int?, 41 | json['finish_reason'] as String?, 42 | ); 43 | 44 | Map _$CompletionsChoiceEntityToJson( 45 | CompletionsChoiceEntity instance) => 46 | { 47 | 'text': instance.text, 48 | 'index': instance.index, 49 | 'logprobs': instance.logprobs, 50 | 'finish_reason': instance.finishReason, 51 | }; 52 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completions_query_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/constants.dart'; 2 | import 'package:json_annotation/json_annotation.dart'; 3 | 4 | part 'completions_query_entity.g.dart'; 5 | 6 | @JsonSerializable(explicitToJson: true) 7 | class CompletionsQueryEntity { 8 | String model; 9 | String prompt; 10 | @JsonKey(name: 'max_tokens') 11 | int maxTokens; 12 | 13 | /// 更高的值意味着模型将承担更多的风险。 14 | /// 对于更有创意的应用程序,可以尝试0.9,对于有明确答案的应用程序,可以尝试0。 15 | @JsonKey(defaultValue: 0.9) 16 | double temperature; 17 | 18 | @JsonKey(name: 'top_p', defaultValue: 1.0) 19 | double topP; 20 | 21 | /// Number between -2.0 and 2.0. 22 | /// Positive values penalize new tokens based on their existing frequency in the text so far, 23 | /// decreasing the model's likelihood to repeat the same line verbatim. 24 | @JsonKey(name: 'frequency_penalty', defaultValue: 0.0) 25 | double frequencyPenalty; 26 | 27 | /// Number between -2.0 and 2.0. 28 | /// Positive values penalize new tokens based on whether they appear in the text so far, 29 | /// increasing the model's likelihood to talk about new topics. 30 | @JsonKey(name: 'presence_penalty', defaultValue: 0.0) 31 | double presencePenalty; 32 | 33 | List? stop; 34 | 35 | /// https://beta.openai.com/docs/guides/completion/conversation 36 | CompletionsQueryEntity.conversation({ 37 | this.model = Constants.gpt3ModelDavinci003, 38 | this.prompt = '', 39 | this.maxTokens = 150, 40 | this.temperature = 0.9, 41 | this.topP = 1.0, 42 | this.frequencyPenalty = 0.0, 43 | this.presencePenalty = 0.6, 44 | this.stop = const [" Human:", " AI:"], 45 | }); 46 | 47 | /// https://beta.openai.com/docs/guides/completion/generation 48 | CompletionsQueryEntity.generation({ 49 | this.model = Constants.gpt3ModelDavinci003, 50 | this.prompt = '', 51 | this.maxTokens = 150, 52 | this.temperature = 0.6, 53 | this.topP = 1.0, 54 | this.frequencyPenalty = 1.0, 55 | this.presencePenalty = 1.0, 56 | this.stop, 57 | }); 58 | 59 | /// https://beta.openai.com/docs/guides/completion/translation 60 | CompletionsQueryEntity.translation({ 61 | this.model = Constants.gpt3ModelDavinci003, 62 | this.prompt = '', 63 | this.maxTokens = 150, 64 | this.temperature = 0.3, 65 | this.topP = 1.0, 66 | this.frequencyPenalty = 0.0, 67 | this.presencePenalty = 0.0, 68 | this.stop, 69 | }); 70 | 71 | CompletionsQueryEntity({ 72 | required this.model, 73 | required this.prompt, 74 | this.maxTokens = 150, 75 | this.temperature = 0.9, 76 | this.topP = 1.0, 77 | this.frequencyPenalty = 0.0, 78 | this.presencePenalty = 0.0, 79 | this.stop, 80 | }); 81 | 82 | factory CompletionsQueryEntity.fromJson(Map json) => 83 | _$CompletionsQueryEntityFromJson(json); 84 | 85 | Map toJson() => _$CompletionsQueryEntityToJson(this); 86 | } 87 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/completions_query_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'completions_query_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | CompletionsQueryEntity _$CompletionsQueryEntityFromJson( 10 | Map json) => 11 | CompletionsQueryEntity( 12 | model: json['model'] as String, 13 | prompt: json['prompt'] as String, 14 | maxTokens: json['max_tokens'] as int? ?? 150, 15 | temperature: (json['temperature'] as num?)?.toDouble() ?? 0.9, 16 | topP: (json['top_p'] as num?)?.toDouble() ?? 1.0, 17 | frequencyPenalty: (json['frequency_penalty'] as num?)?.toDouble() ?? 0.0, 18 | presencePenalty: (json['presence_penalty'] as num?)?.toDouble() ?? 0.0, 19 | stop: (json['stop'] as List?)?.map((e) => e as String).toList(), 20 | ); 21 | 22 | Map _$CompletionsQueryEntityToJson( 23 | CompletionsQueryEntity instance) => 24 | { 25 | 'model': instance.model, 26 | 'prompt': instance.prompt, 27 | 'max_tokens': instance.maxTokens, 28 | 'temperature': instance.temperature, 29 | 'top_p': instance.topP, 30 | 'frequency_penalty': instance.frequencyPenalty, 31 | 'presence_penalty': instance.presencePenalty, 32 | 'stop': instance.stop, 33 | }; 34 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/model_entity.dart: -------------------------------------------------------------------------------- 1 | import 'package:json_annotation/json_annotation.dart'; 2 | 3 | part 'model_entity.g.dart'; 4 | 5 | /// 一次性代码生成:flutter pub run build_runner build --delete-conflicting-outputs 6 | /// 持续生成代码(监听器):flutter pub run build_runner watch 7 | /// 这个标注是告诉生成器,这个类是需要生成Model类的,[参考链接](https://flutter.cn/docs/development/data-and-backend/json) 8 | /// explicitToJson:为嵌套类 (Nested Classes) 生成代码 9 | 10 | @JsonSerializable(explicitToJson: true) 11 | class ModelsEntity { 12 | final String object; 13 | @JsonKey(name: 'data') 14 | final List models; 15 | 16 | ModelsEntity(this.object, this.models); 17 | 18 | factory ModelsEntity.fromJson(Map json) => 19 | _$ModelsEntityFromJson(json); 20 | 21 | Map toJson() => _$ModelsEntityToJson(this); 22 | } 23 | 24 | @JsonSerializable(explicitToJson: true) 25 | class ModelEntity { 26 | final String id; 27 | final String object; 28 | final int created; 29 | @JsonKey(name: "owned_by") 30 | final String ownedBy; 31 | @JsonKey(name: "permission") 32 | final List permissions; 33 | final String root; 34 | final dynamic parent; 35 | 36 | ModelEntity(this.id, this.object, this.created, this.ownedBy, 37 | this.permissions, this.root, this.parent); 38 | 39 | factory ModelEntity.fromJson(Map json) => 40 | _$ModelEntityFromJson(json); 41 | 42 | Map toJson() => _$ModelEntityToJson(this); 43 | } 44 | 45 | @JsonSerializable(explicitToJson: true) 46 | class ModelPermissionEntity { 47 | final String id; 48 | final String object; 49 | final int created; 50 | @JsonKey(name: "allow_create_engine") 51 | final bool allowCreateEngine; 52 | @JsonKey(name: "allow_sampling") 53 | final bool allowSampling; 54 | @JsonKey(name: "allow_logprobs") 55 | final bool allowLogprobs; 56 | @JsonKey(name: "allow_search_indices") 57 | final bool allowSearchIndices; 58 | @JsonKey(name: "allow_view") 59 | final bool allowView; 60 | @JsonKey(name: "allow_fine_tuning") 61 | final bool allowFineTuning; 62 | final String? organization; 63 | final dynamic group; 64 | @JsonKey(name: "is_blocking") 65 | final bool isBlocking; 66 | 67 | ModelPermissionEntity( 68 | this.id, 69 | this.object, 70 | this.created, 71 | this.allowCreateEngine, 72 | this.allowSampling, 73 | this.allowLogprobs, 74 | this.allowSearchIndices, 75 | this.allowView, 76 | this.allowFineTuning, 77 | this.organization, 78 | this.group, 79 | this.isBlocking); 80 | 81 | factory ModelPermissionEntity.fromJson(Map json) => 82 | _$ModelPermissionEntityFromJson(json); 83 | 84 | Map toJson() => _$ModelPermissionEntityToJson(this); 85 | } 86 | -------------------------------------------------------------------------------- /lib/src/network/entity/openai/model_entity.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'model_entity.dart'; 4 | 5 | // ************************************************************************** 6 | // JsonSerializableGenerator 7 | // ************************************************************************** 8 | 9 | ModelsEntity _$ModelsEntityFromJson(Map json) => ModelsEntity( 10 | json['object'] as String, 11 | (json['data'] as List) 12 | .map((e) => ModelEntity.fromJson(e as Map)) 13 | .toList(), 14 | ); 15 | 16 | Map _$ModelsEntityToJson(ModelsEntity instance) => 17 | { 18 | 'object': instance.object, 19 | 'data': instance.models.map((e) => e.toJson()).toList(), 20 | }; 21 | 22 | ModelEntity _$ModelEntityFromJson(Map json) => ModelEntity( 23 | json['id'] as String, 24 | json['object'] as String, 25 | json['created'] as int, 26 | json['owned_by'] as String, 27 | (json['permission'] as List) 28 | .map((e) => ModelPermissionEntity.fromJson(e as Map)) 29 | .toList(), 30 | json['root'] as String, 31 | json['parent'], 32 | ); 33 | 34 | Map _$ModelEntityToJson(ModelEntity instance) => 35 | { 36 | 'id': instance.id, 37 | 'object': instance.object, 38 | 'created': instance.created, 39 | 'owned_by': instance.ownedBy, 40 | 'permission': instance.permissions.map((e) => e.toJson()).toList(), 41 | 'root': instance.root, 42 | 'parent': instance.parent, 43 | }; 44 | 45 | ModelPermissionEntity _$ModelPermissionEntityFromJson( 46 | Map json) => 47 | ModelPermissionEntity( 48 | json['id'] as String, 49 | json['object'] as String, 50 | json['created'] as int, 51 | json['allow_create_engine'] as bool, 52 | json['allow_sampling'] as bool, 53 | json['allow_logprobs'] as bool, 54 | json['allow_search_indices'] as bool, 55 | json['allow_view'] as bool, 56 | json['allow_fine_tuning'] as bool, 57 | json['organization'] as String?, 58 | json['group'], 59 | json['is_blocking'] as bool, 60 | ); 61 | 62 | Map _$ModelPermissionEntityToJson( 63 | ModelPermissionEntity instance) => 64 | { 65 | 'id': instance.id, 66 | 'object': instance.object, 67 | 'created': instance.created, 68 | 'allow_create_engine': instance.allowCreateEngine, 69 | 'allow_sampling': instance.allowSampling, 70 | 'allow_logprobs': instance.allowLogprobs, 71 | 'allow_search_indices': instance.allowSearchIndices, 72 | 'allow_view': instance.allowView, 73 | 'allow_fine_tuning': instance.allowFineTuning, 74 | 'organization': instance.organization, 75 | 'group': instance.group, 76 | 'is_blocking': instance.isBlocking, 77 | }; 78 | -------------------------------------------------------------------------------- /lib/src/network/openai_client.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:hao_chatgpt/src/app_manager.dart'; 4 | import 'package:hao_chatgpt/src/extensions.dart'; 5 | import 'package:dio/adapter.dart'; 6 | import 'package:dio/dio.dart'; 7 | import 'package:flutter/material.dart'; 8 | import 'package:hao_chatgpt/src/app_config.dart'; 9 | 10 | import '../constants.dart'; 11 | 12 | class OpenaiClient { 13 | static const baseUrl = "https://api.openai.com/v1"; 14 | 15 | /// 'Content-Type: application/json' 16 | static BaseOptions baseOptions = BaseOptions( 17 | baseUrl: baseUrl, 18 | connectTimeout: 5000, 19 | receiveTimeout: 60000, 20 | ); 21 | 22 | late Dio _dio; 23 | 24 | Dio get dio => _dio; 25 | 26 | OpenaiClient._internal() { 27 | _dio = Dio(baseOptions); 28 | _setupProxy(); 29 | _dio.interceptors.add(_OpenaiInterceptor()); 30 | } 31 | 32 | static final OpenaiClient _client = OpenaiClient._internal(); 33 | 34 | factory OpenaiClient() => _client; 35 | 36 | void _setupProxy() { 37 | (_dio.httpClientAdapter as DefaultHttpClientAdapter).onHttpClientCreate = (HttpClient client) { 38 | client.findProxy = (uri) { 39 | // set multi proxy 40 | // return "PROXY localhost:8888;PROXY localhost:7777"; 41 | // 设置代理与未设置代理均支持 ‘DIRECT’一定要放在最后 42 | // return "PROXY localhost:8888;DIRECT"; 43 | String? value = appConfig.httpProxy; 44 | if(value.isNotBlank) { 45 | List args = value!.split(Constants.splitTag); 46 | if(args.length == 3) { 47 | bool enableProxy = args[0] == true.toString(); 48 | String hostname = args[1]; 49 | int? portNumber = int.tryParse(args[2]); 50 | if(enableProxy && hostname.isNotBlank && portNumber != null) { 51 | return "PROXY $hostname:$portNumber"; 52 | } 53 | } 54 | } 55 | // no proxy 56 | return 'DIRECT'; 57 | }; 58 | // 解决安卓https抓包问题 59 | client.badCertificateCallback = (X509Certificate cert, String host, int port) => true; 60 | return null; 61 | // you can also create a HttpClient to dio 62 | // return HttpClient(); 63 | }; 64 | } 65 | 66 | } 67 | 68 | class _OpenaiInterceptor extends Interceptor { 69 | @override 70 | void onRequest(RequestOptions options, RequestInterceptorHandler handler) { 71 | if (isOpenaiApiRequest(options)) { 72 | if (appManager.openaiApiKey.isNotBlank) { 73 | options.headers['Authorization'] = 'Bearer ${appManager.openaiApiKey}'; 74 | } 75 | } 76 | super.onRequest(options, handler); 77 | } 78 | 79 | @override 80 | void onResponse(Response response, ResponseInterceptorHandler handler) { 81 | debugPrint(response.headers.toString()); 82 | super.onResponse(response, handler); 83 | } 84 | 85 | @override 86 | void onError(DioError err, ErrorInterceptorHandler handler) { 87 | debugPrint(err.requestOptions.toString()); 88 | super.onError(err, handler); 89 | } 90 | 91 | /// It's a openai api request. 92 | bool isOpenaiApiRequest(RequestOptions options) => 93 | options.path.startsWith('/') && options.baseUrl == OpenaiClient.baseUrl; 94 | } 95 | 96 | final OpenaiClient openaiClient = OpenaiClient(); 97 | -------------------------------------------------------------------------------- /lib/src/network/openai_service.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/network/entity/openai/chat_entity.dart'; 2 | import 'package:hao_chatgpt/src/network/entity/openai/completions_entity.dart'; 3 | import 'package:hao_chatgpt/src/network/entity/openai/completions_query_entity.dart'; 4 | import 'package:hao_chatgpt/src/network/entity/openai/model_entity.dart'; 5 | import 'package:dio/dio.dart'; 6 | import 'package:retrofit/retrofit.dart'; 7 | 8 | import 'entity/openai/chat_query_entity.dart'; 9 | import 'openai_client.dart'; 10 | 11 | part 'openai_service.g.dart'; 12 | 13 | /// flutter pub run build_runner build --delete-conflicting-outputs 14 | @RestApi() 15 | abstract class OpenaiService { 16 | factory OpenaiService(Dio dio, {String? baseUrl}) = _OpenaiService; 17 | 18 | @GET('/models') 19 | Future getModels(); 20 | 21 | @GET('/models/{model}') 22 | Future getModel({@Path("model") required String modelId}); 23 | 24 | @POST('/completions') 25 | Future getCompletions( 26 | @Body() CompletionsQueryEntity query); 27 | 28 | @POST('/chat/completions') 29 | Future getChatCompletions( 30 | @Body() ChatQueryEntity query); 31 | } 32 | 33 | OpenaiService openaiService = OpenaiService(openaiClient.dio); 34 | -------------------------------------------------------------------------------- /lib/src/network/openai_service.g.dart: -------------------------------------------------------------------------------- 1 | // GENERATED CODE - DO NOT MODIFY BY HAND 2 | 3 | part of 'openai_service.dart'; 4 | 5 | // ************************************************************************** 6 | // RetrofitGenerator 7 | // ************************************************************************** 8 | 9 | // ignore_for_file: unnecessary_brace_in_string_interps,no_leading_underscores_for_local_identifiers 10 | 11 | class _OpenaiService implements OpenaiService { 12 | _OpenaiService( 13 | this._dio, { 14 | this.baseUrl, 15 | }); 16 | 17 | final Dio _dio; 18 | 19 | String? baseUrl; 20 | 21 | @override 22 | Future getModels() async { 23 | const _extra = {}; 24 | final queryParameters = {}; 25 | final _headers = {}; 26 | final _data = {}; 27 | final _result = await _dio 28 | .fetch>(_setStreamType(Options( 29 | method: 'GET', 30 | headers: _headers, 31 | extra: _extra, 32 | ) 33 | .compose( 34 | _dio.options, 35 | '/models', 36 | queryParameters: queryParameters, 37 | data: _data, 38 | ) 39 | .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl))); 40 | final value = ModelsEntity.fromJson(_result.data!); 41 | return value; 42 | } 43 | 44 | @override 45 | Future getModel({required modelId}) async { 46 | const _extra = {}; 47 | final queryParameters = {}; 48 | final _headers = {}; 49 | final _data = {}; 50 | final _result = await _dio 51 | .fetch>(_setStreamType(Options( 52 | method: 'GET', 53 | headers: _headers, 54 | extra: _extra, 55 | ) 56 | .compose( 57 | _dio.options, 58 | '/models/${modelId}', 59 | queryParameters: queryParameters, 60 | data: _data, 61 | ) 62 | .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl))); 63 | final value = ModelEntity.fromJson(_result.data!); 64 | return value; 65 | } 66 | 67 | @override 68 | Future getCompletions(query) async { 69 | const _extra = {}; 70 | final queryParameters = {}; 71 | final _headers = {}; 72 | final _data = {}; 73 | _data.addAll(query.toJson()); 74 | final _result = await _dio 75 | .fetch>(_setStreamType(Options( 76 | method: 'POST', 77 | headers: _headers, 78 | extra: _extra, 79 | ) 80 | .compose( 81 | _dio.options, 82 | '/completions', 83 | queryParameters: queryParameters, 84 | data: _data, 85 | ) 86 | .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl))); 87 | final value = CompletionsEntity.fromJson(_result.data!); 88 | return value; 89 | } 90 | 91 | @override 92 | Future getChatCompletions(query) async { 93 | const _extra = {}; 94 | final queryParameters = {}; 95 | final _headers = {}; 96 | final _data = {}; 97 | _data.addAll(query.toJson()); 98 | final _result = await _dio 99 | .fetch>(_setStreamType(Options( 100 | method: 'POST', 101 | headers: _headers, 102 | extra: _extra, 103 | ) 104 | .compose( 105 | _dio.options, 106 | '/chat/completions', 107 | queryParameters: queryParameters, 108 | data: _data, 109 | ) 110 | .copyWith(baseUrl: baseUrl ?? _dio.options.baseUrl))); 111 | final value = ChatEntity.fromJson(_result.data!); 112 | return value; 113 | } 114 | 115 | RequestOptions _setStreamType(RequestOptions requestOptions) { 116 | if (T != dynamic && 117 | !(requestOptions.responseType == ResponseType.bytes || 118 | requestOptions.responseType == ResponseType.stream)) { 119 | if (T == String) { 120 | requestOptions.responseType = ResponseType.plain; 121 | } else { 122 | requestOptions.responseType = ResponseType.json; 123 | } 124 | } 125 | return requestOptions; 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /lib/src/screens/chat/no_key_view.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:hao_chatgpt/src/extensions.dart'; 3 | 4 | import '../../../l10n/generated/l10n.dart'; 5 | import '../../constants.dart'; 6 | import '../../network/entity/api_key_entity.dart'; 7 | import '../../app_config.dart'; 8 | 9 | class NoKeyView extends StatefulWidget { 10 | final VoidCallback? onFinished; 11 | const NoKeyView({this.onFinished, Key? key}) : super(key: key); 12 | 13 | @override 14 | State createState() => _NoKeyViewState(); 15 | } 16 | 17 | class _NoKeyViewState extends State { 18 | String _apiKeyValue = ''; 19 | 20 | @override 21 | Widget build(BuildContext context) { 22 | return Column( 23 | mainAxisSize: MainAxisSize.min, 24 | children: [ 25 | Text(S.of(context).haoChatIsPoweredByOpenAI, style: const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),), 26 | const SizedBox(height: 16,), 27 | Text(S.of(context).storeAPIkeyNotice, style: const TextStyle(fontSize: 12,),), 28 | const SizedBox(height: 16,), 29 | TextField( 30 | maxLines: 1, 31 | decoration: InputDecoration( 32 | border: const OutlineInputBorder(), 33 | hintText: S.of(context).enterYourOpenAiApiKey, 34 | contentPadding: const EdgeInsets.symmetric(horizontal: 8), 35 | ), 36 | onChanged: (value) { 37 | if((value.isNotBlank && !_apiKeyValue.isNotBlank) || (!value.isNotBlank && _apiKeyValue.isNotBlank)) { 38 | setState(() { 39 | _apiKeyValue = value; 40 | }); 41 | } else { 42 | _apiKeyValue = value; 43 | } 44 | }, 45 | ), 46 | const SizedBox(height: 8,), 47 | Row( 48 | children: [ 49 | Expanded(child: Container(),), 50 | Expanded( 51 | child: ElevatedButton( 52 | onPressed: _apiKeyValue.isNotBlank ? () async { 53 | if(_apiKeyValue.isNotBlank) { 54 | ApiKeyEntity entity = 55 | ApiKeyEntity(_apiKeyValue.trim(), DateTime.now()); 56 | appConfig.addApiKey(entity).then((_) { 57 | if(widget.onFinished != null) { 58 | widget.onFinished!(); 59 | } 60 | }); 61 | } 62 | } : null, 63 | child: Text(S.of(context).done), 64 | ), 65 | ), 66 | Expanded(child: Container(),), 67 | ], 68 | ), 69 | Row( 70 | children: [ 71 | Text('1. ${S.of(context).navigateTo}', style: const TextStyle(fontSize: 12,),), 72 | Expanded( 73 | child: TextButton( 74 | onPressed: () { 75 | openWebView(context: context, url: Constants.openAiApiKeysUrl, isExternal: true,); 76 | }, 77 | child: const Text(Constants.openAiApiKeysUrl, overflow: TextOverflow.ellipsis, style: TextStyle(fontSize: 12,),), 78 | ), 79 | ), 80 | ], 81 | ), 82 | Align( 83 | alignment: Alignment.centerLeft, 84 | child: Text('2. ${S.of(context).logInAndClick}', style: const TextStyle(fontSize: 12,),), 85 | ), 86 | ], 87 | ); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /lib/src/screens/chat_turbo/chat_turbo_content.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:flutter/services.dart'; 5 | 6 | import '../../../l10n/generated/l10n.dart'; 7 | import '../../constants.dart'; 8 | import '../../db/hao_database.dart'; 9 | import '../../extensions.dart'; 10 | 11 | class ChatTurboContent extends StatelessWidget { 12 | const ChatTurboContent({required this.message, Key? key}) : super(key: key); 13 | final Message message; 14 | 15 | @override 16 | Widget build(BuildContext context) { 17 | return Card( 18 | child: Column( 19 | crossAxisAlignment: CrossAxisAlignment.start, 20 | children: [ 21 | Container( 22 | decoration: BoxDecoration( 23 | color: Colors.grey.withOpacity(0.3), 24 | border: Border.all(color: Colors.transparent), 25 | borderRadius: const BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8),), 26 | ), 27 | child: Padding( 28 | padding: const EdgeInsets.all(4.0), 29 | child: message.role == ChatRole.user ? _buildUserHeader(context) : _buildAssistantHeader(context), 30 | ), 31 | ), 32 | Padding( 33 | padding: const EdgeInsets.all(8.0), 34 | child: SelectableText( 35 | message.content, 36 | selectionControls: Platform.isIOS ? myCupertinoTextSelectionControls : null, 37 | ), 38 | ), 39 | ], 40 | ), 41 | ); 42 | } 43 | 44 | Widget _buildUserHeader(BuildContext context) { 45 | return Row( 46 | children: [ 47 | const Icon(Icons.account_circle), 48 | const Expanded(child: SizedBox()), 49 | Text(formatDateTime(message.msgDateTime)), 50 | const SizedBox(width: 4,), 51 | _buildCopyButton(context), 52 | ], 53 | ); 54 | } 55 | 56 | Widget _buildAssistantHeader(BuildContext context) { 57 | String tokens = message.completionTokens?.toString() ?? ''; 58 | if(message.totalTokens != null) { 59 | tokens += '/${message.totalTokens}'; 60 | } 61 | return Row( 62 | children: [ 63 | const ImageIcon(AssetImage('assets/images/openai.png'),), 64 | const SizedBox(width: 4,), 65 | Text(tokens.isNotEmpty ? 'Tokens: $tokens' : ''), 66 | const Expanded(child: SizedBox()), 67 | Text(formatDateTime(message.msgDateTime)), 68 | const SizedBox(width: 4,), 69 | _buildCopyButton(context), 70 | ], 71 | ); 72 | } 73 | 74 | 75 | Widget _buildCopyButton(BuildContext context) { 76 | return GestureDetector( 77 | child: const Icon(Icons.copy), 78 | onTap: () { 79 | Clipboard.setData(ClipboardData(text: message.content)); 80 | ScaffoldMessenger.of(context).showSnackBar(SnackBar( 81 | content: Text(S.of(context).copied), 82 | duration: const Duration(milliseconds: 1000), 83 | action: SnackBarAction( 84 | label: 'ok', 85 | onPressed: () {}, 86 | ), 87 | )); 88 | }, 89 | ); 90 | } 91 | 92 | } 93 | -------------------------------------------------------------------------------- /lib/src/screens/home.dart: -------------------------------------------------------------------------------- 1 | import 'dart:io'; 2 | 3 | import 'package:flutter/material.dart'; 4 | import 'package:go_router/go_router.dart'; 5 | import 'package:hao_chatgpt/src/app_router.dart'; 6 | import 'package:hao_chatgpt/src/extensions.dart'; 7 | 8 | import '../../l10n/generated/l10n.dart'; 9 | import '../app_shortcuts.dart'; 10 | import '../constants.dart'; 11 | import '../app_config.dart'; 12 | 13 | class HomePage extends StatefulWidget { 14 | const HomePage({Key? key}) : super(key: key); 15 | 16 | @override 17 | State createState() => _HomePageState(); 18 | } 19 | 20 | class _HomePageState extends State { 21 | 22 | /* 23 | Map _getShortcuts() { 24 | if(Platform.isAndroid || Platform.isAndroid) { 25 | return {}; 26 | } else { 27 | List keySets = getShortcutsKeys().values.toList(); 28 | keySets.remove(appPref.shortcutsSend); 29 | return { 30 | appPref.shortcutsSend!: const SendIntent(), 31 | keySets.first: const NewLineIntent(), 32 | }; 33 | } 34 | } 35 | */ 36 | 37 | @override 38 | Widget build(BuildContext context) { 39 | return Scaffold( 40 | body: SafeArea( 41 | child: Padding( 42 | padding: const EdgeInsets.symmetric(horizontal: 32.0), 43 | child: Column( 44 | mainAxisSize: MainAxisSize.max, 45 | children: [ 46 | Expanded(flex: 2, child: Container()), 47 | Text( 48 | S.of(context).haoChat, 49 | style: 50 | const TextStyle(fontSize: 20, fontWeight: FontWeight.bold), 51 | ), 52 | const SizedBox( 53 | height: 16, 54 | ), 55 | const ImageIcon( 56 | AssetImage('assets/images/openai.png'), 57 | size: 48, 58 | ), 59 | const SizedBox( 60 | height: 32, 61 | ), 62 | Expanded(flex: 3, child: Container()), 63 | ListTile( 64 | leading: const Icon(Icons.chat), 65 | title: Text(S.of(context).gpt35turbo), 66 | trailing: const Icon(Icons.keyboard_arrow_right), 67 | onTap: () { 68 | context.go('/${AppUri.chatTurbo}'); 69 | }, 70 | ), 71 | Container( 72 | height: 1, 73 | width: double.infinity, 74 | color: Theme.of(context).primaryColorLight.withOpacity(0.5), 75 | ), 76 | /* 77 | ListTile( 78 | leading: const Icon(Icons.chat), 79 | title: Text('${S.of(context).chatGPT} (GPT-3)'), 80 | trailing: const Icon(Icons.keyboard_arrow_right), 81 | onTap: () { 82 | context.go('/${AppUri.chat}'); 83 | }, 84 | ), 85 | Container( 86 | height: 1, 87 | width: double.infinity, 88 | color: Theme.of(context).primaryColorLight.withOpacity(0.5), 89 | ), 90 | */ 91 | ListTile( 92 | leading: const Icon(Icons.settings), 93 | title: Text(S.of(context).settings), 94 | trailing: const Icon(Icons.keyboard_arrow_right), 95 | onTap: () { 96 | context.go('/${AppUri.settings}'); 97 | }, 98 | ), 99 | Container( 100 | height: 1, 101 | width: double.infinity, 102 | color: Theme.of(context).primaryColorLight.withOpacity(0.5), 103 | ), 104 | ListTile( 105 | leading: const Icon(Icons.info), 106 | title: Text('${S.of(context).openAI} ${S.of(context).chatGPT}'), 107 | trailing: const Icon(Icons.keyboard_arrow_right), 108 | onTap: () async { 109 | await openWebView( 110 | context: context, 111 | url: Constants.aboutChatGPTUrl, 112 | title: 'ChatGPT'); 113 | }, 114 | ), 115 | Expanded(flex: 3, child: Container()), 116 | TextButton( 117 | onPressed: () async { 118 | openWebView( 119 | context: context, 120 | url: Constants.haoChatGitHubUrl, 121 | title: 'hao_chatgpt'); 122 | }, 123 | child: Padding( 124 | padding: const EdgeInsets.symmetric(vertical: 16.0), 125 | child: Text( 126 | '${S.of(context).appDescription}\nPowered by Conghaonet', 127 | textAlign: TextAlign.center, 128 | style: const TextStyle(fontSize: 10, color: Colors.blue), 129 | ), 130 | ), 131 | ), 132 | ], 133 | ), 134 | ), 135 | ), 136 | ); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /lib/src/screens/settings/settings_proxy.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:flutter/services.dart'; 3 | import 'package:flutter_riverpod/flutter_riverpod.dart'; 4 | import 'package:go_router/go_router.dart'; 5 | import 'package:hao_chatgpt/main.dart'; 6 | import 'package:hao_chatgpt/src/constants.dart'; 7 | import 'package:hao_chatgpt/src/extensions.dart'; 8 | import 'package:hao_chatgpt/src/app_config.dart'; 9 | 10 | import '../../../l10n/generated/l10n.dart'; 11 | 12 | class SettingsProxy extends ConsumerStatefulWidget { 13 | const SettingsProxy({Key? key}) : super(key: key); 14 | 15 | @override 16 | ConsumerState createState() => _SettingsProxyState(); 17 | } 18 | 19 | class _SettingsProxyState extends ConsumerState { 20 | final _hostnameController = TextEditingController(); 21 | final _portNumberController = TextEditingController(); 22 | final GlobalKey _formKey = GlobalKey(); 23 | bool _enableProxy = false; 24 | 25 | @override 26 | void initState() { 27 | super.initState(); 28 | String? value = appConfig.httpProxy; 29 | if(value.isNotBlank) { 30 | List args = value!.split(Constants.splitTag); 31 | if(args.length == 3) { 32 | _enableProxy = args[0] == true.toString(); 33 | _hostnameController.text = args[1]; 34 | _portNumberController.text = args[2]; 35 | } 36 | } 37 | } 38 | 39 | @override 40 | Widget build(BuildContext context) { 41 | return AlertDialog( 42 | title: Text(S.of(context).httpProxy), 43 | content: Form( 44 | key: _formKey, 45 | child: Column( 46 | mainAxisSize: MainAxisSize.min, 47 | children: [ 48 | Row( 49 | children: [ 50 | Text(S.of(context).enableProxy), 51 | const SizedBox(width: 8,), 52 | Checkbox( 53 | value: _enableProxy, 54 | onChanged: (value) { 55 | _enableProxy = value!; 56 | setState(() { 57 | 58 | }); 59 | }, 60 | ), 61 | ], 62 | ), 63 | const SizedBox(height: 12,), 64 | TextFormField( 65 | enabled: _enableProxy, 66 | controller: _hostnameController, 67 | maxLines: 1, 68 | decoration: InputDecoration( 69 | labelText: S.of(context).hostName, 70 | border: const OutlineInputBorder(), 71 | contentPadding: const EdgeInsets.symmetric(horizontal: 8), 72 | ), 73 | validator: (v) { 74 | return _enableProxy && (v == null || v.trim().isEmpty) ? '' : null; 75 | }, 76 | ), 77 | const SizedBox(height: 20,), 78 | TextFormField( 79 | enabled: _enableProxy, 80 | controller: _portNumberController, 81 | maxLines: 1, 82 | decoration: InputDecoration( 83 | labelText: S.of(context).portNumber, 84 | border: const OutlineInputBorder(), 85 | contentPadding: const EdgeInsets.symmetric(horizontal: 8), 86 | ), 87 | validator: (v) { 88 | return _enableProxy && (v == null || v.trim().isEmpty) ? '' : null; 89 | }, 90 | keyboardType: TextInputType.number, 91 | inputFormatters: [ 92 | FilteringTextInputFormatter(RegExp("[0-9]"), allow: true,), 93 | ], 94 | ), 95 | ], 96 | ), 97 | ), 98 | actions: [ 99 | TextButton( 100 | onPressed: () async { 101 | if((_formKey.currentState as FormState).validate()) { 102 | await appConfig.setHttpProxy(_enableProxy, _hostnameController.text, int.tryParse(_portNumberController.text)); 103 | ref.read(proxyProvider.notifier).state = appConfig.httpProxy; 104 | setState(() { 105 | context.pop(); 106 | }); 107 | } 108 | }, 109 | child: Text(S.of(context).confirm), 110 | ), 111 | TextButton( 112 | onPressed: () => context.pop(), 113 | child: Text(S.of(context).cancel), 114 | ), 115 | ], 116 | ); 117 | } 118 | 119 | @override 120 | void dispose() { 121 | _hostnameController.dispose(); 122 | _portNumberController.dispose(); 123 | super.dispose(); 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /lib/src/screens/webview.dart: -------------------------------------------------------------------------------- 1 | import 'package:flutter/material.dart'; 2 | import 'package:hao_chatgpt/src/constants.dart'; 3 | import 'package:hao_chatgpt/src/extensions.dart'; 4 | import 'package:webview_flutter/webview_flutter.dart'; 5 | 6 | class WebviewPage extends StatefulWidget { 7 | final String? url; 8 | final String? title; 9 | const WebviewPage({required this.url, this.title, Key? key}) 10 | : super(key: key); 11 | 12 | @override 13 | State createState() => _WebviewPageState(); 14 | } 15 | 16 | class _WebviewPageState extends State { 17 | late String _title; 18 | late String _url; 19 | late final WebViewController _controller; 20 | double _progress = 0; 21 | 22 | @override 23 | void initState() { 24 | super.initState(); 25 | _title = widget.title ?? ''; 26 | _url = widget.url.isNotBlank ? widget.url! : Constants.blankUrl; 27 | _controller = WebViewController() 28 | ..setJavaScriptMode(JavaScriptMode.unrestricted) 29 | ..setNavigationDelegate(NavigationDelegate( 30 | onProgress: (int progress) { 31 | if (mounted) { 32 | setState(() { 33 | _progress = progress.toDouble() / 100; 34 | }); 35 | } 36 | }, 37 | onNavigationRequest: (NavigationRequest request) { 38 | return NavigationDecision.navigate; 39 | }, 40 | )) 41 | ..loadRequest(Uri.parse(_url)); 42 | } 43 | 44 | @override 45 | Widget build(BuildContext context) { 46 | return Scaffold( 47 | appBar: AppBar( 48 | title: Text(_title), 49 | actions: [ 50 | IconButton( 51 | onPressed: () async { 52 | await _controller.reload(); 53 | }, 54 | icon: const Icon(Icons.refresh), 55 | ), 56 | IconButton( 57 | onPressed: () async { 58 | var currentUrl = await _controller.currentUrl(); 59 | if (currentUrl.isNotBlank) { 60 | await openWebView( 61 | context: context, url: currentUrl!, isExternal: true); 62 | } 63 | }, 64 | icon: const Icon(Icons.open_in_browser), 65 | ), 66 | ], 67 | ), 68 | body: Stack( 69 | children: [ 70 | WillPopScope( 71 | onWillPop: () async { 72 | if (await _controller.canGoBack()) { 73 | await _controller.goBack(); 74 | return false; 75 | } else { 76 | return true; 77 | } 78 | }, 79 | child: WebViewWidget( 80 | controller: _controller, 81 | ), 82 | ), 83 | Offstage( 84 | offstage: _progress == 1.0, 85 | child: LinearProgressIndicator( 86 | value: _progress, 87 | valueColor: const AlwaysStoppedAnimation( 88 | Colors.blueAccent), // 进度条颜色为粉色 89 | ), 90 | ), 91 | ], 92 | ), 93 | ); 94 | } 95 | 96 | @override 97 | void dispose() { 98 | super.dispose(); 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /linux/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral 2 | -------------------------------------------------------------------------------- /linux/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.10) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | 12 | # Serves the same purpose as list(TRANSFORM ... PREPEND ...), 13 | # which isn't available in 3.10. 14 | function(list_prepend LIST_NAME PREFIX) 15 | set(NEW_LIST "") 16 | foreach(element ${${LIST_NAME}}) 17 | list(APPEND NEW_LIST "${PREFIX}${element}") 18 | endforeach(element) 19 | set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE) 20 | endfunction() 21 | 22 | # === Flutter Library === 23 | # System-level dependencies. 24 | find_package(PkgConfig REQUIRED) 25 | pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0) 26 | pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0) 27 | pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0) 28 | 29 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so") 30 | 31 | # Published to parent scope for install step. 32 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 33 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 34 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 35 | set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE) 36 | 37 | list(APPEND FLUTTER_LIBRARY_HEADERS 38 | "fl_basic_message_channel.h" 39 | "fl_binary_codec.h" 40 | "fl_binary_messenger.h" 41 | "fl_dart_project.h" 42 | "fl_engine.h" 43 | "fl_json_message_codec.h" 44 | "fl_json_method_codec.h" 45 | "fl_message_codec.h" 46 | "fl_method_call.h" 47 | "fl_method_channel.h" 48 | "fl_method_codec.h" 49 | "fl_method_response.h" 50 | "fl_plugin_registrar.h" 51 | "fl_plugin_registry.h" 52 | "fl_standard_message_codec.h" 53 | "fl_standard_method_codec.h" 54 | "fl_string_codec.h" 55 | "fl_value.h" 56 | "fl_view.h" 57 | "flutter_linux.h" 58 | ) 59 | list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/") 60 | add_library(flutter INTERFACE) 61 | target_include_directories(flutter INTERFACE 62 | "${EPHEMERAL_DIR}" 63 | ) 64 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}") 65 | target_link_libraries(flutter INTERFACE 66 | PkgConfig::GTK 67 | PkgConfig::GLIB 68 | PkgConfig::GIO 69 | ) 70 | add_dependencies(flutter flutter_assemble) 71 | 72 | # === Flutter tool backend === 73 | # _phony_ is a non-existent file to force this command to run every time, 74 | # since currently there's no way to get a full input/output list from the 75 | # flutter tool. 76 | add_custom_command( 77 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 78 | ${CMAKE_CURRENT_BINARY_DIR}/_phony_ 79 | COMMAND ${CMAKE_COMMAND} -E env 80 | ${FLUTTER_TOOL_ENVIRONMENT} 81 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh" 82 | ${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE} 83 | VERBATIM 84 | ) 85 | add_custom_target(flutter_assemble DEPENDS 86 | "${FLUTTER_LIBRARY}" 87 | ${FLUTTER_LIBRARY_HEADERS} 88 | ) 89 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | #include 11 | 12 | void fl_register_plugins(FlPluginRegistry* registry) { 13 | g_autoptr(FlPluginRegistrar) sqlite3_flutter_libs_registrar = 14 | fl_plugin_registry_get_registrar_for_plugin(registry, "Sqlite3FlutterLibsPlugin"); 15 | sqlite3_flutter_libs_plugin_register_with_registrar(sqlite3_flutter_libs_registrar); 16 | g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar = 17 | fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin"); 18 | url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar); 19 | } 20 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void fl_register_plugins(FlPluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /linux/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | sqlite3_flutter_libs 7 | url_launcher_linux 8 | ) 9 | 10 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 11 | ) 12 | 13 | set(PLUGIN_BUNDLED_LIBRARIES) 14 | 15 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 16 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin}) 17 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 19 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 20 | endforeach(plugin) 21 | 22 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 23 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin}) 24 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 25 | endforeach(ffi_plugin) 26 | -------------------------------------------------------------------------------- /linux/main.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | int main(int argc, char** argv) { 4 | g_autoptr(MyApplication) app = my_application_new(); 5 | return g_application_run(G_APPLICATION(app), argc, argv); 6 | } 7 | -------------------------------------------------------------------------------- /linux/my_application.cc: -------------------------------------------------------------------------------- 1 | #include "my_application.h" 2 | 3 | #include 4 | #ifdef GDK_WINDOWING_X11 5 | #include 6 | #endif 7 | 8 | #include "flutter/generated_plugin_registrant.h" 9 | 10 | struct _MyApplication { 11 | GtkApplication parent_instance; 12 | char** dart_entrypoint_arguments; 13 | }; 14 | 15 | G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION) 16 | 17 | // Implements GApplication::activate. 18 | static void my_application_activate(GApplication* application) { 19 | MyApplication* self = MY_APPLICATION(application); 20 | GtkWindow* window = 21 | GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application))); 22 | 23 | // Use a header bar when running in GNOME as this is the common style used 24 | // by applications and is the setup most users will be using (e.g. Ubuntu 25 | // desktop). 26 | // If running on X and not using GNOME then just use a traditional title bar 27 | // in case the window manager does more exotic layout, e.g. tiling. 28 | // If running on Wayland assume the header bar will work (may need changing 29 | // if future cases occur). 30 | gboolean use_header_bar = TRUE; 31 | #ifdef GDK_WINDOWING_X11 32 | GdkScreen* screen = gtk_window_get_screen(window); 33 | if (GDK_IS_X11_SCREEN(screen)) { 34 | const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen); 35 | if (g_strcmp0(wm_name, "GNOME Shell") != 0) { 36 | use_header_bar = FALSE; 37 | } 38 | } 39 | #endif 40 | if (use_header_bar) { 41 | GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new()); 42 | gtk_widget_show(GTK_WIDGET(header_bar)); 43 | gtk_header_bar_set_title(header_bar, "hao_chatgpt"); 44 | gtk_header_bar_set_show_close_button(header_bar, TRUE); 45 | gtk_window_set_titlebar(window, GTK_WIDGET(header_bar)); 46 | } else { 47 | gtk_window_set_title(window, "hao_chatgpt"); 48 | } 49 | 50 | gtk_window_set_default_size(window, 1280, 720); 51 | gtk_widget_show(GTK_WIDGET(window)); 52 | 53 | g_autoptr(FlDartProject) project = fl_dart_project_new(); 54 | fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments); 55 | 56 | FlView* view = fl_view_new(project); 57 | gtk_widget_show(GTK_WIDGET(view)); 58 | gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view)); 59 | 60 | fl_register_plugins(FL_PLUGIN_REGISTRY(view)); 61 | 62 | gtk_widget_grab_focus(GTK_WIDGET(view)); 63 | } 64 | 65 | // Implements GApplication::local_command_line. 66 | static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) { 67 | MyApplication* self = MY_APPLICATION(application); 68 | // Strip out the first argument as it is the binary name. 69 | self->dart_entrypoint_arguments = g_strdupv(*arguments + 1); 70 | 71 | g_autoptr(GError) error = nullptr; 72 | if (!g_application_register(application, nullptr, &error)) { 73 | g_warning("Failed to register: %s", error->message); 74 | *exit_status = 1; 75 | return TRUE; 76 | } 77 | 78 | g_application_activate(application); 79 | *exit_status = 0; 80 | 81 | return TRUE; 82 | } 83 | 84 | // Implements GObject::dispose. 85 | static void my_application_dispose(GObject* object) { 86 | MyApplication* self = MY_APPLICATION(object); 87 | g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev); 88 | G_OBJECT_CLASS(my_application_parent_class)->dispose(object); 89 | } 90 | 91 | static void my_application_class_init(MyApplicationClass* klass) { 92 | G_APPLICATION_CLASS(klass)->activate = my_application_activate; 93 | G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line; 94 | G_OBJECT_CLASS(klass)->dispose = my_application_dispose; 95 | } 96 | 97 | static void my_application_init(MyApplication* self) {} 98 | 99 | MyApplication* my_application_new() { 100 | return MY_APPLICATION(g_object_new(my_application_get_type(), 101 | "application-id", APPLICATION_ID, 102 | "flags", G_APPLICATION_NON_UNIQUE, 103 | nullptr)); 104 | } 105 | -------------------------------------------------------------------------------- /linux/my_application.h: -------------------------------------------------------------------------------- 1 | #ifndef FLUTTER_MY_APPLICATION_H_ 2 | #define FLUTTER_MY_APPLICATION_H_ 3 | 4 | #include 5 | 6 | G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION, 7 | GtkApplication) 8 | 9 | /** 10 | * my_application_new: 11 | * 12 | * Creates a new Flutter-based application. 13 | * 14 | * Returns: a new #MyApplication. 15 | */ 16 | MyApplication* my_application_new(); 17 | 18 | #endif // FLUTTER_MY_APPLICATION_H_ 19 | -------------------------------------------------------------------------------- /macos/.gitignore: -------------------------------------------------------------------------------- 1 | # Flutter-related 2 | **/Flutter/ephemeral/ 3 | **/Pods/ 4 | 5 | # Xcode-related 6 | **/dgph 7 | **/xcuserdata/ 8 | /Podfile.lock 9 | -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Flutter/Flutter-Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" 2 | #include "ephemeral/Flutter-Generated.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Flutter/GeneratedPluginRegistrant.swift: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | import FlutterMacOS 6 | import Foundation 7 | 8 | import path_provider_foundation 9 | import shared_preferences_foundation 10 | import sqlite3_flutter_libs 11 | import url_launcher_macos 12 | 13 | func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 14 | PathProviderPlugin.register(with: registry.registrar(forPlugin: "PathProviderPlugin")) 15 | SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) 16 | Sqlite3FlutterLibsPlugin.register(with: registry.registrar(forPlugin: "Sqlite3FlutterLibsPlugin")) 17 | UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin")) 18 | } 19 | -------------------------------------------------------------------------------- /macos/Podfile: -------------------------------------------------------------------------------- 1 | platform :osx, '10.14' 2 | 3 | # CocoaPods analytics sends network stats synchronously affecting flutter build latency. 4 | ENV['COCOAPODS_DISABLE_STATS'] = 'true' 5 | 6 | project 'Runner', { 7 | 'Debug' => :debug, 8 | 'Profile' => :release, 9 | 'Release' => :release, 10 | } 11 | 12 | def flutter_root 13 | generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) 14 | unless File.exist?(generated_xcode_build_settings_path) 15 | raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" 16 | end 17 | 18 | File.foreach(generated_xcode_build_settings_path) do |line| 19 | matches = line.match(/FLUTTER_ROOT\=(.*)/) 20 | return matches[1].strip if matches 21 | end 22 | raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" 23 | end 24 | 25 | require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) 26 | 27 | flutter_macos_podfile_setup 28 | 29 | target 'Runner' do 30 | use_frameworks! 31 | use_modular_headers! 32 | 33 | flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) 34 | end 35 | 36 | post_install do |installer| 37 | installer.pods_project.targets.each do |target| 38 | flutter_additional_macos_build_settings(target) 39 | end 40 | end 41 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme: -------------------------------------------------------------------------------- 1 | 2 | 5 | 8 | 9 | 15 | 21 | 22 | 23 | 24 | 25 | 30 | 31 | 37 | 38 | 39 | 40 | 41 | 42 | 52 | 54 | 60 | 61 | 62 | 63 | 69 | 71 | 77 | 78 | 79 | 80 | 82 | 83 | 86 | 87 | 88 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | IDEDidComputeMac32BitWarning 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /macos/Runner/AppDelegate.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | @NSApplicationMain 5 | class AppDelegate: FlutterAppDelegate { 6 | override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { 7 | return true 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "size" : "16x16", 5 | "idiom" : "mac", 6 | "filename" : "app_icon_16.png", 7 | "scale" : "1x" 8 | }, 9 | { 10 | "size" : "16x16", 11 | "idiom" : "mac", 12 | "filename" : "app_icon_32.png", 13 | "scale" : "2x" 14 | }, 15 | { 16 | "size" : "32x32", 17 | "idiom" : "mac", 18 | "filename" : "app_icon_32.png", 19 | "scale" : "1x" 20 | }, 21 | { 22 | "size" : "32x32", 23 | "idiom" : "mac", 24 | "filename" : "app_icon_64.png", 25 | "scale" : "2x" 26 | }, 27 | { 28 | "size" : "128x128", 29 | "idiom" : "mac", 30 | "filename" : "app_icon_128.png", 31 | "scale" : "1x" 32 | }, 33 | { 34 | "size" : "128x128", 35 | "idiom" : "mac", 36 | "filename" : "app_icon_256.png", 37 | "scale" : "2x" 38 | }, 39 | { 40 | "size" : "256x256", 41 | "idiom" : "mac", 42 | "filename" : "app_icon_256.png", 43 | "scale" : "1x" 44 | }, 45 | { 46 | "size" : "256x256", 47 | "idiom" : "mac", 48 | "filename" : "app_icon_512.png", 49 | "scale" : "2x" 50 | }, 51 | { 52 | "size" : "512x512", 53 | "idiom" : "mac", 54 | "filename" : "app_icon_512.png", 55 | "scale" : "1x" 56 | }, 57 | { 58 | "size" : "512x512", 59 | "idiom" : "mac", 60 | "filename" : "app_icon_1024.png", 61 | "scale" : "2x" 62 | } 63 | ], 64 | "info" : { 65 | "version" : 1, 66 | "author" : "xcode" 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png -------------------------------------------------------------------------------- /macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png -------------------------------------------------------------------------------- /macos/Runner/Configs/AppInfo.xcconfig: -------------------------------------------------------------------------------- 1 | // Application-level settings for the Runner target. 2 | // 3 | // This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the 4 | // future. If not, the values below would default to using the project name when this becomes a 5 | // 'flutter create' template. 6 | 7 | // The application's name. By default this is also the title of the Flutter window. 8 | PRODUCT_NAME = HaoChat 9 | 10 | // The application's bundle identifier 11 | PRODUCT_BUNDLE_IDENTIFIER = com.app2m.chatgpt.haoChatgpt 12 | 13 | // The copyright displayed in application information 14 | PRODUCT_COPYRIGHT = Copyright © 2023 com.app2m.chatgpt. All rights reserved. 15 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Debug.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Debug.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Release.xcconfig: -------------------------------------------------------------------------------- 1 | #include "../../Flutter/Flutter-Release.xcconfig" 2 | #include "Warnings.xcconfig" 3 | -------------------------------------------------------------------------------- /macos/Runner/Configs/Warnings.xcconfig: -------------------------------------------------------------------------------- 1 | WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings 2 | GCC_WARN_UNDECLARED_SELECTOR = YES 3 | CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES 4 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE 5 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES 6 | CLANG_WARN_PRAGMA_PACK = YES 7 | CLANG_WARN_STRICT_PROTOTYPES = YES 8 | CLANG_WARN_COMMA = YES 9 | GCC_WARN_STRICT_SELECTOR_MATCH = YES 10 | CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES 11 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES 12 | GCC_WARN_SHADOW = YES 13 | CLANG_WARN_UNREACHABLE_CODE = YES 14 | -------------------------------------------------------------------------------- /macos/Runner/DebugProfile.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.cs.allow-jit 8 | 9 | com.apple.security.network.server 10 | 11 | com.apple.security.network.client 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /macos/Runner/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CFBundleDevelopmentRegion 6 | $(DEVELOPMENT_LANGUAGE) 7 | CFBundleExecutable 8 | $(EXECUTABLE_NAME) 9 | CFBundleIconFile 10 | 11 | CFBundleIdentifier 12 | $(PRODUCT_BUNDLE_IDENTIFIER) 13 | CFBundleInfoDictionaryVersion 14 | 6.0 15 | CFBundleName 16 | $(PRODUCT_NAME) 17 | CFBundlePackageType 18 | APPL 19 | CFBundleShortVersionString 20 | $(FLUTTER_BUILD_NAME) 21 | CFBundleVersion 22 | $(FLUTTER_BUILD_NUMBER) 23 | LSMinimumSystemVersion 24 | $(MACOSX_DEPLOYMENT_TARGET) 25 | NSHumanReadableCopyright 26 | $(PRODUCT_COPYRIGHT) 27 | NSMainNibFile 28 | MainMenu 29 | NSPrincipalClass 30 | NSApplication 31 | 32 | 33 | -------------------------------------------------------------------------------- /macos/Runner/MainFlutterWindow.swift: -------------------------------------------------------------------------------- 1 | import Cocoa 2 | import FlutterMacOS 3 | 4 | class MainFlutterWindow: NSWindow { 5 | override func awakeFromNib() { 6 | let flutterViewController = FlutterViewController.init() 7 | let windowFrame = self.frame 8 | self.contentViewController = flutterViewController 9 | self.setFrame(windowFrame, display: true) 10 | 11 | RegisterGeneratedPlugins(registry: flutterViewController) 12 | 13 | super.awakeFromNib() 14 | } 15 | } 16 | -------------------------------------------------------------------------------- /macos/Runner/Release.entitlements: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | com.apple.security.app-sandbox 6 | 7 | com.apple.security.network.client 8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /pubspec.yaml: -------------------------------------------------------------------------------- 1 | name: hao_chatgpt 2 | description: An unofficial ChatGPT application. 3 | 4 | publish_to: 'none' # Remove this line if you wish to publish to pub.dev 5 | 6 | version: 1.3.3+7 7 | 8 | environment: 9 | sdk: '>=2.18.6 <3.0.0' 10 | 11 | dependencies: 12 | flutter: 13 | sdk: flutter 14 | flutter_localizations: 15 | sdk: flutter 16 | intl: ^0.18.0 17 | cupertino_icons: ^1.0.2 18 | dio: ^4.0.6 19 | yaml: ^3.1.1 20 | json_annotation: ^4.7.0 21 | retrofit: '>=3.0.0 <4.0.0' 22 | logger: ^1.1.0 23 | flutter_riverpod: ^2.1.3 24 | hooks_riverpod: ^2.1.3 25 | riverpod: ^2.1.3 26 | loading_animation_widget: ^1.2.0+4 27 | shared_preferences: ^2.0.15 28 | go_router: ^6.0.0 29 | webview_flutter: ^4.0.1 30 | webview_flutter_android: ^3.1.1 31 | webview_flutter_wkwebview: ^3.0.1 32 | url_launcher: ^6.1.7 33 | drift: ^2.4.2 34 | sqlite3_flutter_libs: ^0.5.12 35 | path_provider: ^2.0.11 36 | path: ^1.8.2 37 | android_intent_plus: ^3.1.5 38 | 39 | dev_dependencies: 40 | flutter_test: 41 | sdk: flutter 42 | build_runner: ^2.3.3 43 | json_serializable: ^6.6.0 44 | retrofit_generator: '>=4.0.0 <5.0.0' 45 | flutter_lints: ^2.0.1 46 | drift_dev: ^2.4.1 47 | 48 | flutter: 49 | # generate: true 50 | uses-material-design: true 51 | assets: 52 | - assets/images/ 53 | - pubspec.yaml 54 | -------------------------------------------------------------------------------- /release_apk.bat: -------------------------------------------------------------------------------- 1 | flutter build apk --release -------------------------------------------------------------------------------- /release_windows.bat: -------------------------------------------------------------------------------- 1 | flutter build windows -------------------------------------------------------------------------------- /screenshots/en/gpt35turbo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/gpt35turbo.jpg -------------------------------------------------------------------------------- /screenshots/en/home.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/home.jpg -------------------------------------------------------------------------------- /screenshots/en/leftmenu01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/leftmenu01.jpg -------------------------------------------------------------------------------- /screenshots/en/leftmenu02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/leftmenu02.jpg -------------------------------------------------------------------------------- /screenshots/en/nokey.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/nokey.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot01.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot02.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot03.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot03.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot04.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot04.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot05.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot05.jpg -------------------------------------------------------------------------------- /screenshots/en/screenshot06.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/screenshot06.jpg -------------------------------------------------------------------------------- /screenshots/en/setsystem01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/setsystem01.jpg -------------------------------------------------------------------------------- /screenshots/en/setsystem02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/setsystem02.jpg -------------------------------------------------------------------------------- /screenshots/en/settings.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/en/settings.jpg -------------------------------------------------------------------------------- /screenshots/flutter_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/flutter_logo.png -------------------------------------------------------------------------------- /screenshots/openai.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/openai.png -------------------------------------------------------------------------------- /screenshots/openai_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/openai_logo.png -------------------------------------------------------------------------------- /screenshots/zh/gpt35turbo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/gpt35turbo.jpg -------------------------------------------------------------------------------- /screenshots/zh/home.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/home.jpg -------------------------------------------------------------------------------- /screenshots/zh/leftmenu01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/leftmenu01.jpg -------------------------------------------------------------------------------- /screenshots/zh/leftmenu02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/leftmenu02.jpg -------------------------------------------------------------------------------- /screenshots/zh/nokey.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/nokey.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot01.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot02.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot03.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot03.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot04.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot04.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot05.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot05.jpg -------------------------------------------------------------------------------- /screenshots/zh/screenshot06.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/screenshot06.jpg -------------------------------------------------------------------------------- /screenshots/zh/setsystem01.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/setsystem01.jpg -------------------------------------------------------------------------------- /screenshots/zh/setsystem02.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/setsystem02.jpg -------------------------------------------------------------------------------- /screenshots/zh/settings.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/screenshots/zh/settings.jpg -------------------------------------------------------------------------------- /test/api_test.dart: -------------------------------------------------------------------------------- 1 | import 'package:hao_chatgpt/src/app_manager.dart'; 2 | import 'package:hao_chatgpt/src/constants.dart'; 3 | import 'package:hao_chatgpt/src/extensions.dart'; 4 | import 'package:hao_chatgpt/src/network/entity/api_key_entity.dart'; 5 | import 'package:hao_chatgpt/src/network/entity/openai/completions_entity.dart'; 6 | import 'package:hao_chatgpt/src/network/entity/openai/completions_query_entity.dart'; 7 | import 'package:hao_chatgpt/src/network/entity/openai/model_entity.dart'; 8 | import 'package:hao_chatgpt/src/network/openai_service.dart'; 9 | import 'package:flutter_test/flutter_test.dart'; 10 | import 'package:hao_chatgpt/src/app_config.dart'; 11 | import 'package:logger/logger.dart'; 12 | import 'dart:io' as io; 13 | import 'package:dio/dio.dart'; 14 | 15 | void main() async { 16 | /// The implementation of TestWidgetsFlutterBinding.ensureInitialized() seems to install 17 | /// a mock http client in package:flutter_test/src/_binding_io.dart (see also _http/overrides.dart), 18 | /// which is probably why you get a different response. 19 | /// After calling TestWidgetsFlutterBinding.ensureInitialized(), set HttpOverrides.global = null in dart:io. 20 | /// https://github.com/flutter/flutter/issues/48050 21 | TestWidgetsFlutterBinding.ensureInitialized(); 22 | io.HttpOverrides.global = null; 23 | // await appManager.init(); 24 | final logger = Logger(); 25 | 26 | test('/models', () async { 27 | ModelsEntity entity = await openaiService.getModels(); 28 | logger.i(entity.toJson()); 29 | }); 30 | test('/model', () async { 31 | ModelEntity modelEntity = 32 | await openaiService.getModel(modelId: Constants.gpt3ModelDavinci003); 33 | logger.i(modelEntity.toJson()); 34 | }); 35 | 36 | test('/completions', () async { 37 | // 地球为什么会自转 38 | // 再具体说说 39 | var query = CompletionsQueryEntity( 40 | model: Constants.gpt3ModelDavinci003, 41 | prompt: '地球为什么会自转', 42 | maxTokens: 1000, 43 | temperature: 0.5, 44 | ); 45 | try { 46 | CompletionsEntity entity = await openaiService.getCompletions(query); 47 | logger.i(entity.toJson()); 48 | } on DioError catch (e) { 49 | logger.e(e.toDioErrorEntity.toJson()); 50 | } on Exception catch (e) { 51 | logger.e(e.toDioErrorEntity.toString()); 52 | } 53 | }); 54 | 55 | test('parse', () { 56 | try { 57 | logger.i(double.tryParse("abc") ?? 'is null'); 58 | } catch (e) { 59 | logger.e(e); 60 | } 61 | }); 62 | test('double format', () { 63 | var a = 0.456; 64 | logger.i(a.toStringAsFixed(2)); 65 | logger.i(a.toStringAsExponential(2)); 66 | logger.i(a.toStringAsPrecision(2)); 67 | }); 68 | 69 | test('test prefs', () async { 70 | // appPref._setApiKeys(null); 71 | 72 | // List entities = List.generate(3, (index) { 73 | // return APIKeyEntity('$index$index$index', DateTime.now()); 74 | // }); 75 | // await appPref.setAPIKeys(entities); 76 | List keys = appConfig.apiKeys; 77 | logger.i(keys.map((e) => e.toJson())); 78 | }); 79 | 80 | test('testReplace', () { 81 | var str = '\n\n\n\nhow\n are you?'; 82 | var regExp = RegExp(r'^\n+'); 83 | logger.i(regExp.hasMatch(str)); 84 | logger.i(str); 85 | logger.i(str.replaceAll(regExp, '')); 86 | }); 87 | 88 | test('RegExp', (){ 89 | String input = 'This model\'s maximum context length is 4097 tokens. However, you requested 4141 tokens (3885 in the messages, 256 in the completion). Please reduce the length of the messages or completion.'; 90 | RegExp digits = RegExp(r'\d+ tokens'); 91 | Iterable matches = digits.allMatches(input); 92 | for (Match match in matches) { 93 | print(match.group(0)); 94 | } 95 | }); 96 | } 97 | -------------------------------------------------------------------------------- /test/widget_test.dart: -------------------------------------------------------------------------------- 1 | // This is a basic Flutter widget test. 2 | // 3 | // To perform an interaction with a widget in your test, use the WidgetTester 4 | // utility in the flutter_test package. For example, you can send tap and scroll 5 | // gestures. You can also use WidgetTester to find child widgets in the widget 6 | // tree, read text, and verify that the values of widget properties are correct. 7 | 8 | import 'package:flutter/material.dart'; 9 | import 'package:flutter_test/flutter_test.dart'; 10 | 11 | import 'package:hao_chatgpt/main.dart'; 12 | 13 | void main() { 14 | testWidgets('Counter increments smoke test', (WidgetTester tester) async { 15 | // Build our app and trigger a frame. 16 | await tester.pumpWidget(const MyApp()); 17 | 18 | // Verify that our counter starts at 0. 19 | expect(find.text('0'), findsOneWidget); 20 | expect(find.text('1'), findsNothing); 21 | 22 | // Tap the '+' icon and trigger a frame. 23 | await tester.tap(find.byIcon(Icons.add)); 24 | await tester.pump(); 25 | 26 | // Verify that our counter has incremented. 27 | expect(find.text('0'), findsNothing); 28 | expect(find.text('1'), findsOneWidget); 29 | }); 30 | } 31 | -------------------------------------------------------------------------------- /web/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/web/favicon.png -------------------------------------------------------------------------------- /web/icons/Icon-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/web/icons/Icon-192.png -------------------------------------------------------------------------------- /web/icons/Icon-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/web/icons/Icon-512.png -------------------------------------------------------------------------------- /web/icons/Icon-maskable-192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/web/icons/Icon-maskable-192.png -------------------------------------------------------------------------------- /web/icons/Icon-maskable-512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/web/icons/Icon-maskable-512.png -------------------------------------------------------------------------------- /web/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | hao_chatgpt 33 | 34 | 35 | 39 | 40 | 41 | 42 | 43 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /web/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "hao_chatgpt", 3 | "short_name": "hao_chatgpt", 4 | "start_url": ".", 5 | "display": "standalone", 6 | "background_color": "#0175C2", 7 | "theme_color": "#0175C2", 8 | "description": "An unofficial ChatGPT application.", 9 | "orientation": "portrait-primary", 10 | "prefer_related_applications": false, 11 | "icons": [ 12 | { 13 | "src": "icons/Icon-192.png", 14 | "sizes": "192x192", 15 | "type": "image/png" 16 | }, 17 | { 18 | "src": "icons/Icon-512.png", 19 | "sizes": "512x512", 20 | "type": "image/png" 21 | }, 22 | { 23 | "src": "icons/Icon-maskable-192.png", 24 | "sizes": "192x192", 25 | "type": "image/png", 26 | "purpose": "maskable" 27 | }, 28 | { 29 | "src": "icons/Icon-maskable-512.png", 30 | "sizes": "512x512", 31 | "type": "image/png", 32 | "purpose": "maskable" 33 | } 34 | ] 35 | } 36 | -------------------------------------------------------------------------------- /windows/.gitignore: -------------------------------------------------------------------------------- 1 | flutter/ephemeral/ 2 | 3 | # Visual Studio user-specific files. 4 | *.suo 5 | *.user 6 | *.userosscache 7 | *.sln.docstates 8 | 9 | # Visual Studio build-related files. 10 | x64/ 11 | x86/ 12 | 13 | # Visual Studio cache files 14 | # files ending in .cache can be ignored 15 | *.[Cc]ache 16 | # but keep track of directories ending in .cache 17 | !*.[Cc]ache/ 18 | -------------------------------------------------------------------------------- /windows/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # Project-level configuration. 2 | cmake_minimum_required(VERSION 3.14) 3 | project(hao_chatgpt LANGUAGES CXX) 4 | 5 | # The name of the executable created for the application. Change this to change 6 | # the on-disk name of your application. 7 | set(BINARY_NAME "hao_chatgpt") 8 | 9 | # Explicitly opt in to modern CMake behaviors to avoid warnings with recent 10 | # versions of CMake. 11 | cmake_policy(SET CMP0063 NEW) 12 | 13 | # Define build configuration option. 14 | get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) 15 | if(IS_MULTICONFIG) 16 | set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" 17 | CACHE STRING "" FORCE) 18 | else() 19 | if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) 20 | set(CMAKE_BUILD_TYPE "Debug" CACHE 21 | STRING "Flutter build mode" FORCE) 22 | set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS 23 | "Debug" "Profile" "Release") 24 | endif() 25 | endif() 26 | # Define settings for the Profile build mode. 27 | set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") 28 | set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") 29 | set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") 30 | set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") 31 | 32 | # Use Unicode for all projects. 33 | add_definitions(-DUNICODE -D_UNICODE) 34 | 35 | # Compilation settings that should be applied to most targets. 36 | # 37 | # Be cautious about adding new options here, as plugins use this function by 38 | # default. In most cases, you should add new options to specific targets instead 39 | # of modifying this function. 40 | function(APPLY_STANDARD_SETTINGS TARGET) 41 | target_compile_features(${TARGET} PUBLIC cxx_std_17) 42 | target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") 43 | target_compile_options(${TARGET} PRIVATE /EHsc) 44 | target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") 45 | target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") 46 | endfunction() 47 | 48 | # Flutter library and tool build rules. 49 | set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") 50 | add_subdirectory(${FLUTTER_MANAGED_DIR}) 51 | 52 | # Application build; see runner/CMakeLists.txt. 53 | add_subdirectory("runner") 54 | 55 | # Generated plugin build rules, which manage building the plugins and adding 56 | # them to the application. 57 | include(flutter/generated_plugins.cmake) 58 | 59 | 60 | # === Installation === 61 | # Support files are copied into place next to the executable, so that it can 62 | # run in place. This is done instead of making a separate bundle (as on Linux) 63 | # so that building and running from within Visual Studio will work. 64 | set(BUILD_BUNDLE_DIR "$") 65 | # Make the "install" step default, as it's required to run. 66 | set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) 67 | if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) 68 | set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) 69 | endif() 70 | 71 | set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") 72 | set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") 73 | 74 | install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" 75 | COMPONENT Runtime) 76 | 77 | install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 78 | COMPONENT Runtime) 79 | 80 | install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 81 | COMPONENT Runtime) 82 | 83 | if(PLUGIN_BUNDLED_LIBRARIES) 84 | install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" 85 | DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" 86 | COMPONENT Runtime) 87 | endif() 88 | 89 | # Fully re-copy the assets directory on each build to avoid having stale files 90 | # from a previous install. 91 | set(FLUTTER_ASSET_DIR_NAME "flutter_assets") 92 | install(CODE " 93 | file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") 94 | " COMPONENT Runtime) 95 | install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" 96 | DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) 97 | 98 | # Install the AOT library on non-Debug builds only. 99 | install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" 100 | CONFIGURATIONS Profile;Release 101 | COMPONENT Runtime) 102 | -------------------------------------------------------------------------------- /windows/flutter/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # This file controls Flutter-level build steps. It should not be edited. 2 | cmake_minimum_required(VERSION 3.14) 3 | 4 | set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") 5 | 6 | # Configuration provided via flutter tool. 7 | include(${EPHEMERAL_DIR}/generated_config.cmake) 8 | 9 | # TODO: Move the rest of this into files in ephemeral. See 10 | # https://github.com/flutter/flutter/issues/57146. 11 | set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") 12 | 13 | # === Flutter Library === 14 | set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") 15 | 16 | # Published to parent scope for install step. 17 | set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) 18 | set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) 19 | set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) 20 | set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) 21 | 22 | list(APPEND FLUTTER_LIBRARY_HEADERS 23 | "flutter_export.h" 24 | "flutter_windows.h" 25 | "flutter_messenger.h" 26 | "flutter_plugin_registrar.h" 27 | "flutter_texture_registrar.h" 28 | ) 29 | list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") 30 | add_library(flutter INTERFACE) 31 | target_include_directories(flutter INTERFACE 32 | "${EPHEMERAL_DIR}" 33 | ) 34 | target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") 35 | add_dependencies(flutter flutter_assemble) 36 | 37 | # === Wrapper === 38 | list(APPEND CPP_WRAPPER_SOURCES_CORE 39 | "core_implementations.cc" 40 | "standard_codec.cc" 41 | ) 42 | list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") 43 | list(APPEND CPP_WRAPPER_SOURCES_PLUGIN 44 | "plugin_registrar.cc" 45 | ) 46 | list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") 47 | list(APPEND CPP_WRAPPER_SOURCES_APP 48 | "flutter_engine.cc" 49 | "flutter_view_controller.cc" 50 | ) 51 | list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") 52 | 53 | # Wrapper sources needed for a plugin. 54 | add_library(flutter_wrapper_plugin STATIC 55 | ${CPP_WRAPPER_SOURCES_CORE} 56 | ${CPP_WRAPPER_SOURCES_PLUGIN} 57 | ) 58 | apply_standard_settings(flutter_wrapper_plugin) 59 | set_target_properties(flutter_wrapper_plugin PROPERTIES 60 | POSITION_INDEPENDENT_CODE ON) 61 | set_target_properties(flutter_wrapper_plugin PROPERTIES 62 | CXX_VISIBILITY_PRESET hidden) 63 | target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) 64 | target_include_directories(flutter_wrapper_plugin PUBLIC 65 | "${WRAPPER_ROOT}/include" 66 | ) 67 | add_dependencies(flutter_wrapper_plugin flutter_assemble) 68 | 69 | # Wrapper sources needed for the runner. 70 | add_library(flutter_wrapper_app STATIC 71 | ${CPP_WRAPPER_SOURCES_CORE} 72 | ${CPP_WRAPPER_SOURCES_APP} 73 | ) 74 | apply_standard_settings(flutter_wrapper_app) 75 | target_link_libraries(flutter_wrapper_app PUBLIC flutter) 76 | target_include_directories(flutter_wrapper_app PUBLIC 77 | "${WRAPPER_ROOT}/include" 78 | ) 79 | add_dependencies(flutter_wrapper_app flutter_assemble) 80 | 81 | # === Flutter tool backend === 82 | # _phony_ is a non-existent file to force this command to run every time, 83 | # since currently there's no way to get a full input/output list from the 84 | # flutter tool. 85 | set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") 86 | set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) 87 | add_custom_command( 88 | OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} 89 | ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} 90 | ${CPP_WRAPPER_SOURCES_APP} 91 | ${PHONY_OUTPUT} 92 | COMMAND ${CMAKE_COMMAND} -E env 93 | ${FLUTTER_TOOL_ENVIRONMENT} 94 | "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" 95 | windows-x64 $ 96 | VERBATIM 97 | ) 98 | add_custom_target(flutter_assemble DEPENDS 99 | "${FLUTTER_LIBRARY}" 100 | ${FLUTTER_LIBRARY_HEADERS} 101 | ${CPP_WRAPPER_SOURCES_CORE} 102 | ${CPP_WRAPPER_SOURCES_PLUGIN} 103 | ${CPP_WRAPPER_SOURCES_APP} 104 | ) 105 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.cc: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #include "generated_plugin_registrant.h" 8 | 9 | #include 10 | #include 11 | 12 | void RegisterPlugins(flutter::PluginRegistry* registry) { 13 | Sqlite3FlutterLibsPluginRegisterWithRegistrar( 14 | registry->GetRegistrarForPlugin("Sqlite3FlutterLibsPlugin")); 15 | UrlLauncherWindowsRegisterWithRegistrar( 16 | registry->GetRegistrarForPlugin("UrlLauncherWindows")); 17 | } 18 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugin_registrant.h: -------------------------------------------------------------------------------- 1 | // 2 | // Generated file. Do not edit. 3 | // 4 | 5 | // clang-format off 6 | 7 | #ifndef GENERATED_PLUGIN_REGISTRANT_ 8 | #define GENERATED_PLUGIN_REGISTRANT_ 9 | 10 | #include 11 | 12 | // Registers Flutter plugins. 13 | void RegisterPlugins(flutter::PluginRegistry* registry); 14 | 15 | #endif // GENERATED_PLUGIN_REGISTRANT_ 16 | -------------------------------------------------------------------------------- /windows/flutter/generated_plugins.cmake: -------------------------------------------------------------------------------- 1 | # 2 | # Generated file, do not edit. 3 | # 4 | 5 | list(APPEND FLUTTER_PLUGIN_LIST 6 | sqlite3_flutter_libs 7 | url_launcher_windows 8 | ) 9 | 10 | list(APPEND FLUTTER_FFI_PLUGIN_LIST 11 | ) 12 | 13 | set(PLUGIN_BUNDLED_LIBRARIES) 14 | 15 | foreach(plugin ${FLUTTER_PLUGIN_LIST}) 16 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) 17 | target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) 18 | list(APPEND PLUGIN_BUNDLED_LIBRARIES $) 19 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) 20 | endforeach(plugin) 21 | 22 | foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) 23 | add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) 24 | list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) 25 | endforeach(ffi_plugin) 26 | -------------------------------------------------------------------------------- /windows/runner/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.14) 2 | project(runner LANGUAGES CXX) 3 | 4 | # Define the application target. To change its name, change BINARY_NAME in the 5 | # top-level CMakeLists.txt, not the value here, or `flutter run` will no longer 6 | # work. 7 | # 8 | # Any new source files that you add to the application should be added here. 9 | add_executable(${BINARY_NAME} WIN32 10 | "flutter_window.cpp" 11 | "main.cpp" 12 | "utils.cpp" 13 | "win32_window.cpp" 14 | "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" 15 | "Runner.rc" 16 | "runner.exe.manifest" 17 | ) 18 | 19 | # Apply the standard set of build settings. This can be removed for applications 20 | # that need different build settings. 21 | apply_standard_settings(${BINARY_NAME}) 22 | 23 | # Add preprocessor definitions for the build version. 24 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") 25 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") 26 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") 27 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") 28 | target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") 29 | 30 | # Disable Windows macros that collide with C++ standard library functions. 31 | target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") 32 | 33 | # Add dependency libraries and include directories. Add any application-specific 34 | # dependencies here. 35 | target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) 36 | target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") 37 | 38 | # Run the Flutter tool portions of the build. This must not be removed. 39 | add_dependencies(${BINARY_NAME} flutter_assemble) 40 | -------------------------------------------------------------------------------- /windows/runner/Runner.rc: -------------------------------------------------------------------------------- 1 | // Microsoft Visual C++ generated resource script. 2 | // 3 | #pragma code_page(65001) 4 | #include "resource.h" 5 | 6 | #define APSTUDIO_READONLY_SYMBOLS 7 | ///////////////////////////////////////////////////////////////////////////// 8 | // 9 | // Generated from the TEXTINCLUDE 2 resource. 10 | // 11 | #include "winres.h" 12 | 13 | ///////////////////////////////////////////////////////////////////////////// 14 | #undef APSTUDIO_READONLY_SYMBOLS 15 | 16 | ///////////////////////////////////////////////////////////////////////////// 17 | // English (United States) resources 18 | 19 | #if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) 20 | LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US 21 | 22 | #ifdef APSTUDIO_INVOKED 23 | ///////////////////////////////////////////////////////////////////////////// 24 | // 25 | // TEXTINCLUDE 26 | // 27 | 28 | 1 TEXTINCLUDE 29 | BEGIN 30 | "resource.h\0" 31 | END 32 | 33 | 2 TEXTINCLUDE 34 | BEGIN 35 | "#include ""winres.h""\r\n" 36 | "\0" 37 | END 38 | 39 | 3 TEXTINCLUDE 40 | BEGIN 41 | "\r\n" 42 | "\0" 43 | END 44 | 45 | #endif // APSTUDIO_INVOKED 46 | 47 | 48 | ///////////////////////////////////////////////////////////////////////////// 49 | // 50 | // Icon 51 | // 52 | 53 | // Icon with lowest ID value placed first to ensure application icon 54 | // remains consistent on all systems. 55 | IDI_APP_ICON ICON "resources\\app_icon.ico" 56 | 57 | 58 | ///////////////////////////////////////////////////////////////////////////// 59 | // 60 | // Version 61 | // 62 | 63 | #if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) 64 | #define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD 65 | #else 66 | #define VERSION_AS_NUMBER 1,0,0,0 67 | #endif 68 | 69 | #if defined(FLUTTER_VERSION) 70 | #define VERSION_AS_STRING FLUTTER_VERSION 71 | #else 72 | #define VERSION_AS_STRING "1.0.0" 73 | #endif 74 | 75 | VS_VERSION_INFO VERSIONINFO 76 | FILEVERSION VERSION_AS_NUMBER 77 | PRODUCTVERSION VERSION_AS_NUMBER 78 | FILEFLAGSMASK VS_FFI_FILEFLAGSMASK 79 | #ifdef _DEBUG 80 | FILEFLAGS VS_FF_DEBUG 81 | #else 82 | FILEFLAGS 0x0L 83 | #endif 84 | FILEOS VOS__WINDOWS32 85 | FILETYPE VFT_APP 86 | FILESUBTYPE 0x0L 87 | BEGIN 88 | BLOCK "StringFileInfo" 89 | BEGIN 90 | BLOCK "040904e4" 91 | BEGIN 92 | VALUE "CompanyName", "com.app2m.chatgpt" "\0" 93 | VALUE "FileDescription", "hao_chatgpt" "\0" 94 | VALUE "FileVersion", VERSION_AS_STRING "\0" 95 | VALUE "InternalName", "hao_chatgpt" "\0" 96 | VALUE "LegalCopyright", "Copyright (C) 2023 com.app2m.chatgpt. All rights reserved." "\0" 97 | VALUE "OriginalFilename", "hao_chatgpt.exe" "\0" 98 | VALUE "ProductName", "hao_chatgpt" "\0" 99 | VALUE "ProductVersion", VERSION_AS_STRING "\0" 100 | END 101 | END 102 | BLOCK "VarFileInfo" 103 | BEGIN 104 | VALUE "Translation", 0x409, 1252 105 | END 106 | END 107 | 108 | #endif // English (United States) resources 109 | ///////////////////////////////////////////////////////////////////////////// 110 | 111 | 112 | 113 | #ifndef APSTUDIO_INVOKED 114 | ///////////////////////////////////////////////////////////////////////////// 115 | // 116 | // Generated from the TEXTINCLUDE 3 resource. 117 | // 118 | 119 | 120 | ///////////////////////////////////////////////////////////////////////////// 121 | #endif // not APSTUDIO_INVOKED 122 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.cpp: -------------------------------------------------------------------------------- 1 | #include "flutter_window.h" 2 | 3 | #include 4 | 5 | #include "flutter/generated_plugin_registrant.h" 6 | 7 | FlutterWindow::FlutterWindow(const flutter::DartProject& project) 8 | : project_(project) {} 9 | 10 | FlutterWindow::~FlutterWindow() {} 11 | 12 | bool FlutterWindow::OnCreate() { 13 | if (!Win32Window::OnCreate()) { 14 | return false; 15 | } 16 | 17 | RECT frame = GetClientArea(); 18 | 19 | // The size here must match the window dimensions to avoid unnecessary surface 20 | // creation / destruction in the startup path. 21 | flutter_controller_ = std::make_unique( 22 | frame.right - frame.left, frame.bottom - frame.top, project_); 23 | // Ensure that basic setup of the controller was successful. 24 | if (!flutter_controller_->engine() || !flutter_controller_->view()) { 25 | return false; 26 | } 27 | RegisterPlugins(flutter_controller_->engine()); 28 | SetChildContent(flutter_controller_->view()->GetNativeWindow()); 29 | return true; 30 | } 31 | 32 | void FlutterWindow::OnDestroy() { 33 | if (flutter_controller_) { 34 | flutter_controller_ = nullptr; 35 | } 36 | 37 | Win32Window::OnDestroy(); 38 | } 39 | 40 | LRESULT 41 | FlutterWindow::MessageHandler(HWND hwnd, UINT const message, 42 | WPARAM const wparam, 43 | LPARAM const lparam) noexcept { 44 | // Give Flutter, including plugins, an opportunity to handle window messages. 45 | if (flutter_controller_) { 46 | std::optional result = 47 | flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, 48 | lparam); 49 | if (result) { 50 | return *result; 51 | } 52 | } 53 | 54 | switch (message) { 55 | case WM_FONTCHANGE: 56 | flutter_controller_->engine()->ReloadSystemFonts(); 57 | break; 58 | } 59 | 60 | return Win32Window::MessageHandler(hwnd, message, wparam, lparam); 61 | } 62 | -------------------------------------------------------------------------------- /windows/runner/flutter_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_FLUTTER_WINDOW_H_ 2 | #define RUNNER_FLUTTER_WINDOW_H_ 3 | 4 | #include 5 | #include 6 | 7 | #include 8 | 9 | #include "win32_window.h" 10 | 11 | // A window that does nothing but host a Flutter view. 12 | class FlutterWindow : public Win32Window { 13 | public: 14 | // Creates a new FlutterWindow hosting a Flutter view running |project|. 15 | explicit FlutterWindow(const flutter::DartProject& project); 16 | virtual ~FlutterWindow(); 17 | 18 | protected: 19 | // Win32Window: 20 | bool OnCreate() override; 21 | void OnDestroy() override; 22 | LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, 23 | LPARAM const lparam) noexcept override; 24 | 25 | private: 26 | // The project to run. 27 | flutter::DartProject project_; 28 | 29 | // The Flutter instance hosted by this window. 30 | std::unique_ptr flutter_controller_; 31 | }; 32 | 33 | #endif // RUNNER_FLUTTER_WINDOW_H_ 34 | -------------------------------------------------------------------------------- /windows/runner/main.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | #include "flutter_window.h" 6 | #include "utils.h" 7 | 8 | int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, 9 | _In_ wchar_t *command_line, _In_ int show_command) { 10 | // Attach to console when present (e.g., 'flutter run') or create a 11 | // new console when running with a debugger. 12 | if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { 13 | CreateAndAttachConsole(); 14 | } 15 | 16 | // Initialize COM, so that it is available for use in the library and/or 17 | // plugins. 18 | ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); 19 | 20 | flutter::DartProject project(L"data"); 21 | 22 | std::vector command_line_arguments = 23 | GetCommandLineArguments(); 24 | 25 | project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); 26 | 27 | FlutterWindow window(project); 28 | Win32Window::Point origin(10, 10); 29 | Win32Window::Size size(1280, 720); 30 | if (!window.CreateAndShow(L"HaoChat", origin, size)) { 31 | return EXIT_FAILURE; 32 | } 33 | window.SetQuitOnClose(true); 34 | 35 | ::MSG msg; 36 | while (::GetMessage(&msg, nullptr, 0, 0)) { 37 | ::TranslateMessage(&msg); 38 | ::DispatchMessage(&msg); 39 | } 40 | 41 | ::CoUninitialize(); 42 | return EXIT_SUCCESS; 43 | } 44 | -------------------------------------------------------------------------------- /windows/runner/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by Runner.rc 4 | // 5 | #define IDI_APP_ICON 101 6 | 7 | // Next default values for new objects 8 | // 9 | #ifdef APSTUDIO_INVOKED 10 | #ifndef APSTUDIO_READONLY_SYMBOLS 11 | #define _APS_NEXT_RESOURCE_VALUE 102 12 | #define _APS_NEXT_COMMAND_VALUE 40001 13 | #define _APS_NEXT_CONTROL_VALUE 1001 14 | #define _APS_NEXT_SYMED_VALUE 101 15 | #endif 16 | #endif 17 | -------------------------------------------------------------------------------- /windows/runner/resources/app_icon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/conghaonet/hao_chatgpt/03fe123477ffdfcd2e4b25bedfda4ad4308de260/windows/runner/resources/app_icon.ico -------------------------------------------------------------------------------- /windows/runner/runner.exe.manifest: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PerMonitorV2 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /windows/runner/utils.cpp: -------------------------------------------------------------------------------- 1 | #include "utils.h" 2 | 3 | #include 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | void CreateAndAttachConsole() { 11 | if (::AllocConsole()) { 12 | FILE *unused; 13 | if (freopen_s(&unused, "CONOUT$", "w", stdout)) { 14 | _dup2(_fileno(stdout), 1); 15 | } 16 | if (freopen_s(&unused, "CONOUT$", "w", stderr)) { 17 | _dup2(_fileno(stdout), 2); 18 | } 19 | std::ios::sync_with_stdio(); 20 | FlutterDesktopResyncOutputStreams(); 21 | } 22 | } 23 | 24 | std::vector GetCommandLineArguments() { 25 | // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. 26 | int argc; 27 | wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); 28 | if (argv == nullptr) { 29 | return std::vector(); 30 | } 31 | 32 | std::vector command_line_arguments; 33 | 34 | // Skip the first argument as it's the binary name. 35 | for (int i = 1; i < argc; i++) { 36 | command_line_arguments.push_back(Utf8FromUtf16(argv[i])); 37 | } 38 | 39 | ::LocalFree(argv); 40 | 41 | return command_line_arguments; 42 | } 43 | 44 | std::string Utf8FromUtf16(const wchar_t* utf16_string) { 45 | if (utf16_string == nullptr) { 46 | return std::string(); 47 | } 48 | int target_length = ::WideCharToMultiByte( 49 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 50 | -1, nullptr, 0, nullptr, nullptr); 51 | std::string utf8_string; 52 | if (target_length == 0 || target_length > utf8_string.max_size()) { 53 | return utf8_string; 54 | } 55 | utf8_string.resize(target_length); 56 | int converted_length = ::WideCharToMultiByte( 57 | CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, 58 | -1, utf8_string.data(), 59 | target_length, nullptr, nullptr); 60 | if (converted_length == 0) { 61 | return std::string(); 62 | } 63 | return utf8_string; 64 | } 65 | -------------------------------------------------------------------------------- /windows/runner/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_UTILS_H_ 2 | #define RUNNER_UTILS_H_ 3 | 4 | #include 5 | #include 6 | 7 | // Creates a console for the process, and redirects stdout and stderr to 8 | // it for both the runner and the Flutter library. 9 | void CreateAndAttachConsole(); 10 | 11 | // Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string 12 | // encoded in UTF-8. Returns an empty std::string on failure. 13 | std::string Utf8FromUtf16(const wchar_t* utf16_string); 14 | 15 | // Gets the command line arguments passed in as a std::vector, 16 | // encoded in UTF-8. Returns an empty std::vector on failure. 17 | std::vector GetCommandLineArguments(); 18 | 19 | #endif // RUNNER_UTILS_H_ 20 | -------------------------------------------------------------------------------- /windows/runner/win32_window.h: -------------------------------------------------------------------------------- 1 | #ifndef RUNNER_WIN32_WINDOW_H_ 2 | #define RUNNER_WIN32_WINDOW_H_ 3 | 4 | #include 5 | 6 | #include 7 | #include 8 | #include 9 | 10 | // A class abstraction for a high DPI-aware Win32 Window. Intended to be 11 | // inherited from by classes that wish to specialize with custom 12 | // rendering and input handling 13 | class Win32Window { 14 | public: 15 | struct Point { 16 | unsigned int x; 17 | unsigned int y; 18 | Point(unsigned int x, unsigned int y) : x(x), y(y) {} 19 | }; 20 | 21 | struct Size { 22 | unsigned int width; 23 | unsigned int height; 24 | Size(unsigned int width, unsigned int height) 25 | : width(width), height(height) {} 26 | }; 27 | 28 | Win32Window(); 29 | virtual ~Win32Window(); 30 | 31 | // Creates and shows a win32 window with |title| and position and size using 32 | // |origin| and |size|. New windows are created on the default monitor. Window 33 | // sizes are specified to the OS in physical pixels, hence to ensure a 34 | // consistent size to will treat the width height passed in to this function 35 | // as logical pixels and scale to appropriate for the default monitor. Returns 36 | // true if the window was created successfully. 37 | bool CreateAndShow(const std::wstring& title, 38 | const Point& origin, 39 | const Size& size); 40 | 41 | // Release OS resources associated with window. 42 | void Destroy(); 43 | 44 | // Inserts |content| into the window tree. 45 | void SetChildContent(HWND content); 46 | 47 | // Returns the backing Window handle to enable clients to set icon and other 48 | // window properties. Returns nullptr if the window has been destroyed. 49 | HWND GetHandle(); 50 | 51 | // If true, closing this window will quit the application. 52 | void SetQuitOnClose(bool quit_on_close); 53 | 54 | // Return a RECT representing the bounds of the current client area. 55 | RECT GetClientArea(); 56 | 57 | protected: 58 | // Processes and route salient window messages for mouse handling, 59 | // size change and DPI. Delegates handling of these to member overloads that 60 | // inheriting classes can handle. 61 | virtual LRESULT MessageHandler(HWND window, 62 | UINT const message, 63 | WPARAM const wparam, 64 | LPARAM const lparam) noexcept; 65 | 66 | // Called when CreateAndShow is called, allowing subclass window-related 67 | // setup. Subclasses should return false if setup fails. 68 | virtual bool OnCreate(); 69 | 70 | // Called when Destroy is called. 71 | virtual void OnDestroy(); 72 | 73 | private: 74 | friend class WindowClassRegistrar; 75 | 76 | // OS callback called by message pump. Handles the WM_NCCREATE message which 77 | // is passed when the non-client area is being created and enables automatic 78 | // non-client DPI scaling so that the non-client area automatically 79 | // responsponds to changes in DPI. All other messages are handled by 80 | // MessageHandler. 81 | static LRESULT CALLBACK WndProc(HWND const window, 82 | UINT const message, 83 | WPARAM const wparam, 84 | LPARAM const lparam) noexcept; 85 | 86 | // Retrieves a class instance pointer for |window| 87 | static Win32Window* GetThisFromHandle(HWND const window) noexcept; 88 | 89 | bool quit_on_close_ = false; 90 | 91 | // window handle for top level window. 92 | HWND window_handle_ = nullptr; 93 | 94 | // window handle for hosted content. 95 | HWND child_content_ = nullptr; 96 | }; 97 | 98 | #endif // RUNNER_WIN32_WINDOW_H_ 99 | --------------------------------------------------------------------------------