commit 738a6364c21c61206fced785e7323381c4d12c2b Author: Lex Lim Date: Mon Jan 2 21:53:58 2023 +0800 初始化项目 diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..8cac985 --- /dev/null +++ b/.gitignore @@ -0,0 +1,45 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp +.DS_Store +.atom/ +.buildlog/ +.history +.svn/ +migrate_working_dir/ +.vscode/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# The .vscode folder contains launch configuration and tasks you configure in +# VS Code which you may wish to be included in version control, so this line +# is commented out by default. +#.vscode/ + +# Flutter/Dart/Pub related +**/doc/api/ +**/ios/Flutter/.last_build_id +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies +.packages +.pub-cache/ +.pub/ +/build/ + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Android Studio will place build artifacts here +/android/app/debug +/android/app/profile +/android/app/release diff --git a/.metadata b/.metadata new file mode 100755 index 0000000..35cfefc --- /dev/null +++ b/.metadata @@ -0,0 +1,30 @@ +# This file tracks properties of this Flutter project. +# Used by Flutter tool to assess capabilities and perform upgrades etc. +# +# This file should be version controlled. + +version: + revision: e3c29ec00c9c825c891d75054c63fcc46454dca1 + channel: stable + +project_type: app + +# Tracks metadata for the flutter migrate command +migration: + platforms: + - platform: root + create_revision: e3c29ec00c9c825c891d75054c63fcc46454dca1 + base_revision: e3c29ec00c9c825c891d75054c63fcc46454dca1 + - platform: web + create_revision: e3c29ec00c9c825c891d75054c63fcc46454dca1 + base_revision: e3c29ec00c9c825c891d75054c63fcc46454dca1 + + # User provided section + + # List of Local paths (relative to this file) that should be + # ignored by the migrate tool. + # + # Files that are not part of the templates will be ignored by default. + unmanaged_files: + - 'lib/main.dart' + - 'ios/Runner.xcodeproj/project.pbxproj' diff --git a/README.md b/README.md new file mode 100755 index 0000000..0e6334d --- /dev/null +++ b/README.md @@ -0,0 +1,16 @@ +# isekai_wiki + +异世界百科APP + +## Getting Started + +This project is a starting point for a Flutter application. + +A few resources to get you started if this is your first Flutter project: + +- [Lab: Write your first Flutter app](https://docs.flutter.dev/get-started/codelab) +- [Cookbook: Useful Flutter samples](https://docs.flutter.dev/cookbook) + +For help getting started with Flutter development, view the +[online documentation](https://docs.flutter.dev/), which offers tutorials, +samples, guidance on mobile development, and a full API reference. diff --git a/analysis_options.yaml b/analysis_options.yaml new file mode 100755 index 0000000..61b6c4d --- /dev/null +++ b/analysis_options.yaml @@ -0,0 +1,29 @@ +# This file configures the analyzer, which statically analyzes Dart code to +# check for errors, warnings, and lints. +# +# The issues identified by the analyzer are surfaced in the UI of Dart-enabled +# IDEs (https://dart.dev/tools#ides-and-editors). The analyzer can also be +# invoked from the command line by running `flutter analyze`. + +# The following line activates a set of recommended lints for Flutter apps, +# packages, and plugins designed to encourage good coding practices. +include: package:flutter_lints/flutter.yaml + +linter: + # The lint rules applied to this project can be customized in the + # section below to disable rules from the `package:flutter_lints/flutter.yaml` + # included above or to enable additional rules. A list of all available lints + # and their documentation is published at + # https://dart-lang.github.io/linter/lints/index.html. + # + # Instead of disabling a lint rule for the entire project in the + # section below, it can also be suppressed for a single line of code + # or a specific dart file by using the `// ignore: name_of_lint` and + # `// ignore_for_file: name_of_lint` syntax on the line or in the file + # producing the lint. + rules: + # avoid_print: false # Uncomment to disable the `avoid_print` rule + # prefer_single_quotes: true # Uncomment to enable the `prefer_single_quotes` rule + +# Additional information about this file can be found at +# https://dart.dev/guides/language/analysis-options diff --git a/android/.gitignore b/android/.gitignore new file mode 100755 index 0000000..6f56801 --- /dev/null +++ b/android/.gitignore @@ -0,0 +1,13 @@ +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat +/local.properties +GeneratedPluginRegistrant.java + +# Remember to never publicly share your keystore. +# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app +key.properties +**/*.keystore +**/*.jks diff --git a/android/app/build.gradle b/android/app/build.gradle new file mode 100755 index 0000000..38f7053 --- /dev/null +++ b/android/app/build.gradle @@ -0,0 +1,71 @@ +def localProperties = new Properties() +def localPropertiesFile = rootProject.file('local.properties') +if (localPropertiesFile.exists()) { + localPropertiesFile.withReader('UTF-8') { reader -> + localProperties.load(reader) + } +} + +def flutterRoot = localProperties.getProperty('flutter.sdk') +if (flutterRoot == null) { + throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.") +} + +def flutterVersionCode = localProperties.getProperty('flutter.versionCode') +if (flutterVersionCode == null) { + flutterVersionCode = '1' +} + +def flutterVersionName = localProperties.getProperty('flutter.versionName') +if (flutterVersionName == null) { + flutterVersionName = '1.0' +} + +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' +apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle" + +android { + compileSdkVersion 33 + ndkVersion flutter.ndkVersion + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + kotlinOptions { + jvmTarget = '1.8' + } + + sourceSets { + main.java.srcDirs += 'src/main/kotlin' + } + + defaultConfig { + // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). + applicationId "cn.isekai.wiki.isekai_wiki" + // You can update the following values to match your application needs. + // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. + minSdkVersion 19 + targetSdkVersion flutter.targetSdkVersion + versionCode flutterVersionCode.toInteger() + versionName flutterVersionName + } + + buildTypes { + release { + // TODO: Add your own signing config for the release build. + // Signing with the debug keys for now, so `flutter run --release` works. + signingConfig signingConfigs.debug + } + } +} + +flutter { + source '../..' +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version" +} diff --git a/android/app/src/debug/AndroidManifest.xml b/android/app/src/debug/AndroidManifest.xml new file mode 100755 index 0000000..35d1a89 --- /dev/null +++ b/android/app/src/debug/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xml new file mode 100755 index 0000000..796c3f9 --- /dev/null +++ b/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,34 @@ + + + + + + + + + + + + + + diff --git a/android/app/src/main/kotlin/cn/isekai/wiki/isekai_wiki/MainActivity.kt b/android/app/src/main/kotlin/cn/isekai/wiki/isekai_wiki/MainActivity.kt new file mode 100755 index 0000000..290d715 --- /dev/null +++ b/android/app/src/main/kotlin/cn/isekai/wiki/isekai_wiki/MainActivity.kt @@ -0,0 +1,6 @@ +package cn.isekai.wiki.isekai_wiki + +import io.flutter.embedding.android.FlutterActivity + +class MainActivity: FlutterActivity() { +} diff --git a/android/app/src/main/res/drawable-v21/launch_background.xml b/android/app/src/main/res/drawable-v21/launch_background.xml new file mode 100755 index 0000000..f74085f --- /dev/null +++ b/android/app/src/main/res/drawable-v21/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/drawable/launch_background.xml b/android/app/src/main/res/drawable/launch_background.xml new file mode 100755 index 0000000..304732f --- /dev/null +++ b/android/app/src/main/res/drawable/launch_background.xml @@ -0,0 +1,12 @@ + + + + + + + + diff --git a/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100755 index 0000000..db77bb4 Binary files /dev/null and b/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100755 index 0000000..17987b7 Binary files /dev/null and b/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100755 index 0000000..09d4391 Binary files /dev/null and b/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100755 index 0000000..d5f1c8d Binary files /dev/null and b/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100755 index 0000000..4d6372e Binary files /dev/null and b/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/android/app/src/main/res/values-night/styles.xml b/android/app/src/main/res/values-night/styles.xml new file mode 100755 index 0000000..06952be --- /dev/null +++ b/android/app/src/main/res/values-night/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/main/res/values/strings.xml b/android/app/src/main/res/values/strings.xml new file mode 100755 index 0000000..2a652de --- /dev/null +++ b/android/app/src/main/res/values/strings.xml @@ -0,0 +1,4 @@ + + + 异世界百科 + \ No newline at end of file diff --git a/android/app/src/main/res/values/styles.xml b/android/app/src/main/res/values/styles.xml new file mode 100755 index 0000000..cb1ef88 --- /dev/null +++ b/android/app/src/main/res/values/styles.xml @@ -0,0 +1,18 @@ + + + + + + + diff --git a/android/app/src/profile/AndroidManifest.xml b/android/app/src/profile/AndroidManifest.xml new file mode 100755 index 0000000..35d1a89 --- /dev/null +++ b/android/app/src/profile/AndroidManifest.xml @@ -0,0 +1,8 @@ + + + + diff --git a/android/build.gradle b/android/build.gradle new file mode 100755 index 0000000..83ae220 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,31 @@ +buildscript { + ext.kotlin_version = '1.6.10' + repositories { + google() + mavenCentral() + } + + dependencies { + classpath 'com.android.tools.build:gradle:7.1.2' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +rootProject.buildDir = '../build' +subprojects { + project.buildDir = "${rootProject.buildDir}/${project.name}" +} +subprojects { + project.evaluationDependsOn(':app') +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/android/gradle.properties b/android/gradle.properties new file mode 100755 index 0000000..94adc3a --- /dev/null +++ b/android/gradle.properties @@ -0,0 +1,3 @@ +org.gradle.jvmargs=-Xmx1536M +android.useAndroidX=true +android.enableJetifier=true diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties new file mode 100755 index 0000000..cb24abd --- /dev/null +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip diff --git a/android/settings.gradle b/android/settings.gradle new file mode 100755 index 0000000..33f0745 --- /dev/null +++ b/android/settings.gradle @@ -0,0 +1,11 @@ +include ':app' + +def localPropertiesFile = new File(rootProject.projectDir, "local.properties") +def properties = new Properties() + +assert localPropertiesFile.exists() +localPropertiesFile.withReader("UTF-8") { reader -> properties.load(reader) } + +def flutterSdkPath = properties.getProperty("flutter.sdk") +assert flutterSdkPath != null, "flutter.sdk not set in local.properties" +apply from: "$flutterSdkPath/packages/flutter_tools/gradle/app_plugin_loader.gradle" diff --git a/buildTypes.sh b/buildTypes.sh new file mode 100755 index 0000000..873c5ff --- /dev/null +++ b/buildTypes.sh @@ -0,0 +1,2 @@ +#!/bin/sh +flutter pub run build_runner build \ No newline at end of file diff --git a/ios/.gitignore b/ios/.gitignore new file mode 100755 index 0000000..7a7f987 --- /dev/null +++ b/ios/.gitignore @@ -0,0 +1,34 @@ +**/dgph +*.mode1v3 +*.mode2v3 +*.moved-aside +*.pbxuser +*.perspectivev3 +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Generated.xcconfig +Flutter/ephemeral/ +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. +!default.mode1v3 +!default.mode2v3 +!default.pbxuser +!default.perspectivev3 diff --git a/ios/Flutter/AppFrameworkInfo.plist b/ios/Flutter/AppFrameworkInfo.plist new file mode 100755 index 0000000..9625e10 --- /dev/null +++ b/ios/Flutter/AppFrameworkInfo.plist @@ -0,0 +1,26 @@ + + + + + CFBundleDevelopmentRegion + en + CFBundleExecutable + App + CFBundleIdentifier + io.flutter.flutter.app + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + App + CFBundlePackageType + FMWK + CFBundleShortVersionString + 1.0 + CFBundleSignature + ???? + CFBundleVersion + 1.0 + MinimumOSVersion + 11.0 + + diff --git a/ios/Flutter/Debug.xcconfig b/ios/Flutter/Debug.xcconfig new file mode 100755 index 0000000..ec97fc6 --- /dev/null +++ b/ios/Flutter/Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Flutter/Release.xcconfig b/ios/Flutter/Release.xcconfig new file mode 100755 index 0000000..c4855bf --- /dev/null +++ b/ios/Flutter/Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "Generated.xcconfig" diff --git a/ios/Podfile b/ios/Podfile new file mode 100755 index 0000000..88359b2 --- /dev/null +++ b/ios/Podfile @@ -0,0 +1,41 @@ +# Uncomment this line to define a global platform for your project +# platform :ios, '11.0' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_ios_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__)) +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_ios_build_settings(target) + end +end diff --git a/ios/Podfile.lock b/ios/Podfile.lock new file mode 100755 index 0000000..fb0e56f --- /dev/null +++ b/ios/Podfile.lock @@ -0,0 +1,46 @@ +PODS: + - Flutter (1.0.0) + - flutter_web_browser (0.17.1): + - Flutter + - package_info_plus (0.4.5): + - Flutter + - video_player_avfoundation (0.0.1): + - Flutter + - wakelock (0.0.1): + - Flutter + - webview_flutter_wkwebview (0.0.1): + - Flutter + +DEPENDENCIES: + - Flutter (from `Flutter`) + - flutter_web_browser (from `.symlinks/plugins/flutter_web_browser/ios`) + - package_info_plus (from `.symlinks/plugins/package_info_plus/ios`) + - video_player_avfoundation (from `.symlinks/plugins/video_player_avfoundation/ios`) + - wakelock (from `.symlinks/plugins/wakelock/ios`) + - webview_flutter_wkwebview (from `.symlinks/plugins/webview_flutter_wkwebview/ios`) + +EXTERNAL SOURCES: + Flutter: + :path: Flutter + flutter_web_browser: + :path: ".symlinks/plugins/flutter_web_browser/ios" + package_info_plus: + :path: ".symlinks/plugins/package_info_plus/ios" + video_player_avfoundation: + :path: ".symlinks/plugins/video_player_avfoundation/ios" + wakelock: + :path: ".symlinks/plugins/wakelock/ios" + webview_flutter_wkwebview: + :path: ".symlinks/plugins/webview_flutter_wkwebview/ios" + +SPEC CHECKSUMS: + Flutter: f04841e97a9d0b0a8025694d0796dd46242b2854 + flutter_web_browser: 7bccaafbb0c5b8862afe7bcd158f15557109f61f + package_info_plus: 6c92f08e1f853dc01228d6f553146438dafcd14e + video_player_avfoundation: e489aac24ef5cf7af82702979ed16f2a5ef84cff + wakelock: d0fc7c864128eac40eba1617cb5264d9c940b46f + webview_flutter_wkwebview: b7e70ef1ddded7e69c796c7390ee74180182971f + +PODFILE CHECKSUM: ef19549a9bc3046e7bb7d2fab4d021637c0c58a3 + +COCOAPODS: 1.11.3 diff --git a/ios/Runner.xcodeproj/project.pbxproj b/ios/Runner.xcodeproj/project.pbxproj new file mode 100755 index 0000000..0f65ac2 --- /dev/null +++ b/ios/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,549 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 50; + objects = { + +/* Begin PBXBuildFile section */ + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */ = {isa = PBXBuildFile; fileRef = 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */; }; + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */ = {isa = PBXBuildFile; fileRef = 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */; }; + 629CF133F5059B08A0BD2C8B /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 501274051A1E3548251A1B08 /* Pods_Runner.framework */; }; + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74858FAE1ED2DC5600515810 /* AppDelegate.swift */; }; + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FA1CF9000F007C117D /* Main.storyboard */; }; + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FD1CF9000F007C117D /* Assets.xcassets */; }; + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */; }; +/* End PBXBuildFile section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 9705A1C41CF9048500538489 /* Embed Frameworks */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Embed Frameworks"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = GeneratedPluginRegistrant.h; sourceTree = ""; }; + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = GeneratedPluginRegistrant.m; sourceTree = ""; }; + 3AFB459EADF80E56F496475E /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; }; + 501274051A1E3548251A1B08 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 67BED01427C75D31D69F353D /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "Runner-Bridging-Header.h"; sourceTree = ""; }; + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = Release.xcconfig; path = Flutter/Release.xcconfig; sourceTree = ""; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Debug.xcconfig; path = Flutter/Debug.xcconfig; sourceTree = ""; }; + 9740EEB31CF90195004384FC /* Generated.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; name = Generated.xcconfig; path = Flutter/Generated.xcconfig; sourceTree = ""; }; + 97C146EE1CF9000F007C117D /* Runner.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Runner.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 97C146FB1CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; + 97C146FD1CF9000F007C117D /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; + 97C147001CF9000F007C117D /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; + 97C147021CF9000F007C117D /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; + F855FC5056C4167AE656E8FE /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 97C146EB1CF9000F007C117D /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 629CF133F5059B08A0BD2C8B /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 6AC34FF921120CE1D2389405 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 501274051A1E3548251A1B08 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; + 9740EEB11CF90186004384FC /* Flutter */ = { + isa = PBXGroup; + children = ( + 3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 9740EEB31CF90195004384FC /* Generated.xcconfig */, + ); + name = Flutter; + sourceTree = ""; + }; + 97C146E51CF9000F007C117D = { + isa = PBXGroup; + children = ( + 9740EEB11CF90186004384FC /* Flutter */, + 97C146F01CF9000F007C117D /* Runner */, + 97C146EF1CF9000F007C117D /* Products */, + E938473C9A6FA23B4894DA7D /* Pods */, + 6AC34FF921120CE1D2389405 /* Frameworks */, + ); + sourceTree = ""; + }; + 97C146EF1CF9000F007C117D /* Products */ = { + isa = PBXGroup; + children = ( + 97C146EE1CF9000F007C117D /* Runner.app */, + ); + name = Products; + sourceTree = ""; + }; + 97C146F01CF9000F007C117D /* Runner */ = { + isa = PBXGroup; + children = ( + 97C146FA1CF9000F007C117D /* Main.storyboard */, + 97C146FD1CF9000F007C117D /* Assets.xcassets */, + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */, + 97C147021CF9000F007C117D /* Info.plist */, + 1498D2321E8E86230040F4C2 /* GeneratedPluginRegistrant.h */, + 1498D2331E8E89220040F4C2 /* GeneratedPluginRegistrant.m */, + 74858FAE1ED2DC5600515810 /* AppDelegate.swift */, + 74858FAD1ED2DC5600515810 /* Runner-Bridging-Header.h */, + ); + path = Runner; + sourceTree = ""; + }; + E938473C9A6FA23B4894DA7D /* Pods */ = { + isa = PBXGroup; + children = ( + 67BED01427C75D31D69F353D /* Pods-Runner.debug.xcconfig */, + 3AFB459EADF80E56F496475E /* Pods-Runner.release.xcconfig */, + F855FC5056C4167AE656E8FE /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 97C146ED1CF9000F007C117D /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 63EA0BA8292C989967BCB1F8 /* [CP] Check Pods Manifest.lock */, + 9740EEB61CF901F6004384FC /* Run Script */, + 97C146EA1CF9000F007C117D /* Sources */, + 97C146EB1CF9000F007C117D /* Frameworks */, + 97C146EC1CF9000F007C117D /* Resources */, + 9705A1C41CF9048500538489 /* Embed Frameworks */, + 3B06AD1E1E4923F5004D2608 /* Thin Binary */, + 11A7373D03D48E9831D34A47 /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + ); + name = Runner; + productName = Runner; + productReference = 97C146EE1CF9000F007C117D /* Runner.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 97C146E61CF9000F007C117D /* Project object */ = { + isa = PBXProject; + attributes = { + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 97C146ED1CF9000F007C117D = { + CreatedOnToolsVersion = 7.3.1; + LastSwiftMigration = 1100; + }; + }; + }; + buildConfigurationList = 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 97C146E51CF9000F007C117D; + productRefGroup = 97C146EF1CF9000F007C117D /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 97C146ED1CF9000F007C117D /* Runner */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 97C146EC1CF9000F007C117D /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 97C147011CF9000F007C117D /* LaunchScreen.storyboard in Resources */, + 3B3967161E833CAA004F5970 /* AppFrameworkInfo.plist in Resources */, + 97C146FE1CF9000F007C117D /* Assets.xcassets in Resources */, + 97C146FC1CF9000F007C117D /* Main.storyboard in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 11A7373D03D48E9831D34A47 /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 3B06AD1E1E4923F5004D2608 /* Thin Binary */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Thin Binary"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" embed_and_thin"; + }; + 63EA0BA8292C989967BCB1F8 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; + 9740EEB61CF901F6004384FC /* Run Script */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = "Run Script"; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "/bin/sh \"$FLUTTER_ROOT/packages/flutter_tools/bin/xcode_backend.sh\" build"; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 97C146EA1CF9000F007C117D /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 74858FAF1ED2DC5600515810 /* AppDelegate.swift in Sources */, + 1498D2341E8E89220040F4C2 /* GeneratedPluginRegistrant.m in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXVariantGroup section */ + 97C146FA1CF9000F007C117D /* Main.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C146FB1CF9000F007C117D /* Base */, + ); + name = Main.storyboard; + sourceTree = ""; + }; + 97C146FF1CF9000F007C117D /* LaunchScreen.storyboard */ = { + isa = PBXVariantGroup; + children = ( + 97C147001CF9000F007C117D /* Base */, + ); + name = LaunchScreen.storyboard; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 249021D3217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Profile; + }; + 249021D4217E4FDB00AE95B9 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.isekai.wiki.isekaiWiki; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Profile; + }; + 97C147031CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = iphoneos; + TARGETED_DEVICE_FAMILY = "1,2"; + }; + name = Debug; + }; + 97C147041CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_COMMA = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_STRICT_PROTOTYPES = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CLANG_WARN_UNREACHABLE_CODE = YES; + CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; + "CODE_SIGN_IDENTITY[sdk=iphoneos*]" = "iPhone Developer"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu99; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNDECLARED_SELECTOR = YES; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + IPHONEOS_DEPLOYMENT_TARGET = 11.0; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = iphoneos; + SUPPORTED_PLATFORMS = iphoneos; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + TARGETED_DEVICE_FAMILY = "1,2"; + VALIDATE_PRODUCT = YES; + }; + name = Release; + }; + 97C147061CF9000F007C117D /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.isekai.wiki.isekaiWiki; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Debug; + }; + 97C147071CF9000F007C117D /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CURRENT_PROJECT_VERSION = "$(FLUTTER_BUILD_NUMBER)"; + ENABLE_BITCODE = NO; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/Frameworks", + ); + PRODUCT_BUNDLE_IDENTIFIER = cn.isekai.wiki.isekaiWiki; + PRODUCT_NAME = "$(TARGET_NAME)"; + SWIFT_OBJC_BRIDGING_HEADER = "Runner/Runner-Bridging-Header.h"; + SWIFT_VERSION = 5.0; + VERSIONING_SYSTEM = "apple-generic"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 97C146E91CF9000F007C117D /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147031CF9000F007C117D /* Debug */, + 97C147041CF9000F007C117D /* Release */, + 249021D3217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 97C147061CF9000F007C117D /* Debug */, + 97C147071CF9000F007C117D /* Release */, + 249021D4217E4FDB00AE95B9 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 97C146E61CF9000F007C117D /* Project object */; +} diff --git a/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata new file mode 100755 index 0000000..919434a --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,7 @@ + + + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100755 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100755 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100755 index 0000000..c87d15a --- /dev/null +++ b/ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner.xcworkspace/contents.xcworkspacedata b/ios/Runner.xcworkspace/contents.xcworkspacedata new file mode 100755 index 0000000..21a3cc1 --- /dev/null +++ b/ios/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100755 index 0000000..18d9810 --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings new file mode 100755 index 0000000..f9b0d7c --- /dev/null +++ b/ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings @@ -0,0 +1,8 @@ + + + + + PreviewsEnabled + + + diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift new file mode 100755 index 0000000..70693e4 --- /dev/null +++ b/ios/Runner/AppDelegate.swift @@ -0,0 +1,13 @@ +import UIKit +import Flutter + +@UIApplicationMain +@objc class AppDelegate: FlutterAppDelegate { + override func application( + _ application: UIApplication, + didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? + ) -> Bool { + GeneratedPluginRegistrant.register(with: self) + return super.application(application, didFinishLaunchingWithOptions: launchOptions) + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100755 index 0000000..d36b1fa --- /dev/null +++ b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,122 @@ +{ + "images" : [ + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "20x20", + "idiom" : "iphone", + "filename" : "Icon-App-20x20@3x.png", + "scale" : "3x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "iphone", + "filename" : "Icon-App-29x29@3x.png", + "scale" : "3x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "iphone", + "filename" : "Icon-App-40x40@3x.png", + "scale" : "3x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@2x.png", + "scale" : "2x" + }, + { + "size" : "60x60", + "idiom" : "iphone", + "filename" : "Icon-App-60x60@3x.png", + "scale" : "3x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@1x.png", + "scale" : "1x" + }, + { + "size" : "20x20", + "idiom" : "ipad", + "filename" : "Icon-App-20x20@2x.png", + "scale" : "2x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@1x.png", + "scale" : "1x" + }, + { + "size" : "29x29", + "idiom" : "ipad", + "filename" : "Icon-App-29x29@2x.png", + "scale" : "2x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@1x.png", + "scale" : "1x" + }, + { + "size" : "40x40", + "idiom" : "ipad", + "filename" : "Icon-App-40x40@2x.png", + "scale" : "2x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@1x.png", + "scale" : "1x" + }, + { + "size" : "76x76", + "idiom" : "ipad", + "filename" : "Icon-App-76x76@2x.png", + "scale" : "2x" + }, + { + "size" : "83.5x83.5", + "idiom" : "ipad", + "filename" : "Icon-App-83.5x83.5@2x.png", + "scale" : "2x" + }, + { + "size" : "1024x1024", + "idiom" : "ios-marketing", + "filename" : "Icon-App-1024x1024@1x.png", + "scale" : "1x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png new file mode 100755 index 0000000..dc9ada4 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-1024x1024@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png new file mode 100755 index 0000000..28c6bf0 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png new file mode 100755 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png new file mode 100755 index 0000000..f091b6b Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-20x20@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png new file mode 100755 index 0000000..4cde121 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png new file mode 100755 index 0000000..d0ef06e Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png new file mode 100755 index 0000000..dcdc230 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-29x29@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png new file mode 100755 index 0000000..2ccbfd9 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png new file mode 100755 index 0000000..c8f9ed8 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png new file mode 100755 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-40x40@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png new file mode 100755 index 0000000..a6d6b86 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png new file mode 100755 index 0000000..75b2d16 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-60x60@3x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png new file mode 100755 index 0000000..c4df70d Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@1x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png new file mode 100755 index 0000000..6a84f41 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-76x76@2x.png differ diff --git a/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png new file mode 100755 index 0000000..d0e1f58 Binary files /dev/null and b/ios/Runner/Assets.xcassets/AppIcon.appiconset/Icon-App-83.5x83.5@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json new file mode 100755 index 0000000..0bedcf2 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json @@ -0,0 +1,23 @@ +{ + "images" : [ + { + "idiom" : "universal", + "filename" : "LaunchImage.png", + "scale" : "1x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@2x.png", + "scale" : "2x" + }, + { + "idiom" : "universal", + "filename" : "LaunchImage@3x.png", + "scale" : "3x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png new file mode 100755 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png new file mode 100755 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@2x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png new file mode 100755 index 0000000..9da19ea Binary files /dev/null and b/ios/Runner/Assets.xcassets/LaunchImage.imageset/LaunchImage@3x.png differ diff --git a/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md new file mode 100755 index 0000000..89c2725 --- /dev/null +++ b/ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md @@ -0,0 +1,5 @@ +# Launch Screen Assets + +You can customize the launch screen with your own desired assets by replacing the image files in this directory. + +You can also do it by opening your Flutter project's Xcode project with `open ios/Runner.xcworkspace`, selecting `Runner/Assets.xcassets` in the Project Navigator and dropping in the desired images. \ No newline at end of file diff --git a/ios/Runner/Base.lproj/LaunchScreen.storyboard b/ios/Runner/Base.lproj/LaunchScreen.storyboard new file mode 100755 index 0000000..f2e259c --- /dev/null +++ b/ios/Runner/Base.lproj/LaunchScreen.storyboard @@ -0,0 +1,37 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Base.lproj/Main.storyboard b/ios/Runner/Base.lproj/Main.storyboard new file mode 100755 index 0000000..f3c2851 --- /dev/null +++ b/ios/Runner/Base.lproj/Main.storyboard @@ -0,0 +1,26 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/ios/Runner/Info.plist b/ios/Runner/Info.plist new file mode 100755 index 0000000..2236f92 --- /dev/null +++ b/ios/Runner/Info.plist @@ -0,0 +1,51 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleDisplayName + Isekai Wiki + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + isekai_wiki + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleSignature + ???? + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSRequiresIPhoneOS + + UILaunchStoryboardName + LaunchScreen + UIMainStoryboardFile + Main + UISupportedInterfaceOrientations + + UIInterfaceOrientationPortrait + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UISupportedInterfaceOrientations~ipad + + UIInterfaceOrientationPortrait + UIInterfaceOrientationPortraitUpsideDown + UIInterfaceOrientationLandscapeLeft + UIInterfaceOrientationLandscapeRight + + UIViewControllerBasedStatusBarAppearance + + CADisableMinimumFrameDurationOnPhone + + UIApplicationSupportsIndirectInputEvents + + + diff --git a/ios/Runner/Runner-Bridging-Header.h b/ios/Runner/Runner-Bridging-Header.h new file mode 100755 index 0000000..308a2a5 --- /dev/null +++ b/ios/Runner/Runner-Bridging-Header.h @@ -0,0 +1 @@ +#import "GeneratedPluginRegistrant.h" diff --git a/lib/api/client.dart b/lib/api/client.dart new file mode 100644 index 0000000..e69de29 diff --git a/lib/api/mw/list.dart b/lib/api/mw/list.dart new file mode 100755 index 0000000..d23babb --- /dev/null +++ b/lib/api/mw/list.dart @@ -0,0 +1,205 @@ +import 'package:isekai_wiki/api/mw/mw_api.dart'; +import 'package:isekai_wiki/api/response/page_info.dart'; +import 'package:isekai_wiki/api/response/recent_changes.dart'; + +class MWApiList { + /// 获取最近更改列表 + static Future>> getRecentChanges( + String type, + {int? limit, + Map? continueInfo}) async { + var query = { + "list": "recentchanges", + "rctype": type, + "rcnamespace": 0, + "rclimit": limit, + }; + if (continueInfo != null && continueInfo.containsKey("rccontinue")) { + query["rccontinue"] = continueInfo["rccontinue"]; + } + + var mwRes = await MWApi.get("query", query: query); + + if (!mwRes.ok) { + return MWResponse(errorList: mwRes.errorList); + } + if (mwRes.data != null) { + var rcRes = RecentChangesResponse.fromJson(mwRes.data!); + + return MWResponse( + ok: true, + data: rcRes.recentchanges, + continueInfo: mwRes.continueInfo); + } else { + return MWResponse( + errorList: [MWError(code: 'response_data_empty', info: '加载的数据为空')]); + } + } + + /// 获取合并的最近更改列表(包括新页面和最近更新) + static Future>> getMixedRecentChanges( + {int? limit, Map? continueInfo}) async { + Map continueInfoNew = {}; + Map continueInfoEdit = {}; + + bool ignoreRcNew = false; + bool ignoreRcEdit = false; + + if (continueInfo != null) { + ignoreRcNew = true; + ignoreRcEdit = true; + + if (continueInfo.containsKey("rcnewcontinue")) { + continueInfoNew["rccontinue"] = continueInfo["rcnewcontinue"]!; + ignoreRcNew = false; + } + if (continueInfo.containsKey("rceditcontinue")) { + continueInfoEdit["rccontinue"] = continueInfo["rceditcontinue"]!; + ignoreRcEdit = false; + } + } + + var rcResList = await Future.wait([ + ignoreRcNew + ? Future.value( + MWResponse>(ok: true, data: [])) + : getRecentChanges("new", + limit: limit, continueInfo: continueInfoNew), + ignoreRcEdit + ? Future.value( + MWResponse>(ok: true, data: [])) + : getRecentChanges("edit", + limit: limit, continueInfo: continueInfoEdit), + ]); + + var rcNewRes = rcResList[0]; + var rcEditRes = rcResList[1]; + + if (!rcNewRes.ok) { + return MWResponse(errorList: rcNewRes.errorList); + } else if (!rcEditRes.ok) { + return MWResponse(errorList: rcNewRes.errorList); + } + + List mergedList = [ + ...rcNewRes.data!, + ...rcEditRes.data! + ]; + + mergedList.sort((a, b) { + // 为新页面添加7天的保护期 + var timeA = a.type == "new" + ? a.timestamp.add(const Duration(days: 7)) + : a.timestamp; + var timeB = b.type == "new" + ? b.timestamp.add(const Duration(days: 7)) + : b.timestamp; + + return timeB.compareTo(timeA); + }); + + List uniqueMergedList = []; + for (var page in mergedList) { + if (uniqueMergedList + .indexWhere((element) => element.pageid == page.pageid) == + -1) { + uniqueMergedList.add(page); + } + } + + Map mergedContinueInfo = {}; + if (rcNewRes.continueInfo != null && + rcNewRes.continueInfo!.containsKey("rccontinue")) { + mergedContinueInfo["rcnewcontinue"] = + rcNewRes.continueInfo!["rccontinue"]!; + } + if (rcEditRes.continueInfo != null && + rcEditRes.continueInfo!.containsKey("rccontinue")) { + mergedContinueInfo["rceditcontinue"] = + rcEditRes.continueInfo!["rccontinue"]!; + } + + return MWResponse( + ok: true, + data: uniqueMergedList, + continueInfo: mergedContinueInfo.isNotEmpty ? mergedContinueInfo : null, + ); + } + + static Future>> getPageInfoList( + {List? pageids, + List? titles, + int extractChars = 200}) async { + var query = { + "prop": "extracts|info|pageimages", + "redirects": 1, + "converttitles": 1, + "exintro": 1, + "explaintext": 1, + "exchars": extractChars, + "inprop": "url", + "piprop": "thumbnail", + "pithumbsize": 640, + "pilicense": "any" + }; + + if (pageids != null) { + query["pageids"] = pageids.join("|"); + } + if (titles != null) { + query["titles"] = titles.join("|"); + } + + var mwRes = await MWApi.get("query", query: query); + + if (!mwRes.ok) { + return MWResponse(errorList: mwRes.errorList); + } + if (mwRes.data != null) { + var pagesRes = PagesResponse.fromJson(mwRes.data!); + + var pageList = pagesRes.pages.map((pageInfo) { + if (pageInfo.description != null) { + pageInfo.description = + pageInfo.description!.replaceAll(RegExp(r"\n\n"), "\n"); + } + if (pageInfo.title.contains("/")) { + var splitPos = pageInfo.title.lastIndexOf("/"); + pageInfo.displayTitle = pageInfo.title.substring(splitPos + 1); + pageInfo.subtitle = pageInfo.title.substring(0, splitPos); + } else { + pageInfo.displayTitle = pageInfo.title; + } + return pageInfo; + }).toList(); + // 按照传入顺序对页面进行排序 + List sortedPages = []; + + if (pageids != null) { + for (var pageid in pageids) { + var index = + pageList.indexWhere((element) => element.pageid == pageid); + if (index != -1) { + sortedPages.add(pageList[index]); + } + } + } + + if (titles != null) { + for (var title in titles) { + var index = + pagesRes.pages.indexWhere((element) => element.title == title); + if (index != -1) { + sortedPages.add(pagesRes.pages[index]); + } + } + } + + return MWResponse( + ok: true, data: sortedPages, continueInfo: mwRes.continueInfo); + } else { + return MWResponse( + errorList: [MWError(code: 'response_data_empty', info: '加载的数据为空')]); + } + } +} diff --git a/lib/api/mw/mw_api.dart b/lib/api/mw/mw_api.dart new file mode 100755 index 0000000..4ddae69 --- /dev/null +++ b/lib/api/mw/mw_api.dart @@ -0,0 +1,169 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; + +import 'package:isekai_wiki/global.dart'; + +import '../../utils/api_utils.dart'; + +const apiBaseUrl = 'https://www.isekai.cn/api.php'; + +class HttpResponseCodeError extends Error { + int? statusCode; + + HttpResponseCodeError(this.statusCode); + + @override + String toString() { + return "Http error: $statusCode"; + } +} + +class MWError { + String? code; + String? info; + String? detail; + + MWError({this.code, this.info, this.detail}); + + static MWError fromMap(Map errorMap) { + var mwError = MWError(); + if (errorMap.containsKey("code")) { + mwError.code = errorMap["code"].toString(); + } + + if (errorMap.containsKey("info")) { + mwError.info = errorMap["info"].toString(); + } + + if (errorMap.containsKey("*")) { + mwError.detail = errorMap["*"].toString(); + } + + return mwError; + } +} + +class MWMultiError extends Error { + List errorList; + + MWMultiError(this.errorList); + + @override + String toString() { + return errorList.map((e) => e.info).join("\n"); + } +} + +class MWResponse { + bool ok = false; + List? errorList; + T? data; + Map? continueInfo; + + MWResponse({this.ok = false, this.errorList, this.data, this.continueInfo}); +} + +class MWApiClient extends http.BaseClient { + final http.Client _inner; + + MWApiClient(this._inner); + + Future send(http.BaseRequest request) async { + request.headers['user-agent'] = await ApiUtils.getUserAgent(); + return await _inner.send(request); + } +} + +class MWApi { + static Uri apiBaseUri = Uri.parse(apiBaseUrl); + + static HttpClient getHttpClient() { + return HttpClient(); + } + + static Future> _getHeaders() async { + var headers = { + "X-IsekaiWikiApp-Version": Global.packageInfo?.version ?? "unknow", + }; + + if (!kIsWeb) { + headers["User-Agent"] = await ApiUtils.getUserAgent(); + } + + return headers; + } + + static Future>> get(String action, + {Map? query}) async { + Map queryStr = + query?.map((key, value) => MapEntry(key, value.toString())) ?? {}; + queryStr.addAll({ + "action": action, + "format": "json", + "formatversion": "2", + "uselang": Global.wikiLang, + }); + if (Global.webOrigin != null) { + queryStr["origin"] = Global.webOrigin!; + } + + Uri requestUri = apiBaseUri.replace(queryParameters: queryStr); + + var res = await http.get(requestUri, headers: await _getHeaders()); + + if (res.statusCode != 200) { + throw HttpResponseCodeError(res.statusCode); + } + + var responseBody = res.body; + + return parseMWResponse(action, responseBody); + } + + static MWResponse> parseMWResponse(String action, String resJson) { + var mwRes = MWResponse>(); + List errorList = []; + + var resData = jsonDecode(resJson); + if (resData is Map) { + // 处理请求错误 + var resError = resData["error"]; + if (resError is Map) { + errorList.add(MWError.fromMap(resError)); + } else if (resError is List) { + for (var errItem in resError) { + if (errItem is Map) { + errorList.add(MWError.fromMap(errItem)); + } + } + } + if (errorList.isNotEmpty) { + mwRes.errorList = errorList; + return mwRes; + } + + // 请求结果 + if (resData.containsKey(action) && resData[action] is Map) { + mwRes.data = resData[action] as Map; + mwRes.ok = true; + } + + // 继续查询参数 + var batchcomplete = resData["batchcomplete"]; + if (batchcomplete is bool && batchcomplete) { + var continueInfo = resData["continue"]; + if (continueInfo is Map) { + mwRes.continueInfo = {}; + continueInfo.forEach((key, value) { + var keyStr = key.toString(); + mwRes.continueInfo![keyStr] = value.toString(); + }); + } + } + } + + return mwRes; + } +} diff --git a/lib/api/response/page_info.dart b/lib/api/response/page_info.dart new file mode 100644 index 0000000..8e6eae1 --- /dev/null +++ b/lib/api/response/page_info.dart @@ -0,0 +1,89 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'page_info.g.dart'; + +@JsonSerializable() +class PageInfo { + int pageid; + int ns; + String title; + String? displayTitle; + String? subtitle; + int? lastrevid; + String? contentmodel; + String? pagelanguage; + String? pagelanguagehtmlcode; + String? pagelanguagedir; + bool? inwatchlist; + + int? length; + String? fullurl; + String? editurl; + String? canonicalurl; + + PageImageInfo? thumbnail; + + @JsonKey(name: "extract") + String? description; + + @JsonKey(name: "touched") + DateTime? updatedTime; + + PageInfo({ + required this.pageid, + required this.ns, + required this.title, + this.subtitle, + this.displayTitle, + this.description, + this.contentmodel, + this.pagelanguage, + this.pagelanguagehtmlcode, + this.pagelanguagedir, + this.updatedTime, + this.lastrevid, + this.length, + this.fullurl, + this.editurl, + this.canonicalurl, + }); + + String get mainTitle { + return displayTitle ?? title; + } + + String? get mainCategory { + return null; + } + + factory PageInfo.fromJson(Map json) => + _$PageInfoFromJson(json); + + Map toJson() => _$PageInfoToJson(this); +} + +@JsonSerializable() +class PagesResponse { + List pages; + + PagesResponse({required this.pages}); + + factory PagesResponse.fromJson(Map json) => + _$PagesResponseFromJson(json); + + Map toJson() => _$PagesResponseToJson(this); +} + +@JsonSerializable() +class PageImageInfo { + String source; + int? width; + int? height; + + PageImageInfo({required this.source, this.width, this.height}); + + factory PageImageInfo.fromJson(Map json) => + _$PageImageInfoFromJson(json); + + Map toJson() => _$PageImageInfoToJson(this); +} diff --git a/lib/api/response/page_info.g.dart b/lib/api/response/page_info.g.dart new file mode 100644 index 0000000..77ba46d --- /dev/null +++ b/lib/api/response/page_info.g.dart @@ -0,0 +1,79 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'page_info.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +PageInfo _$PageInfoFromJson(Map json) => PageInfo( + pageid: json['pageid'] as int, + ns: json['ns'] as int, + title: json['title'] as String, + subtitle: json['subtitle'] as String?, + description: json['extract'] as String?, + contentmodel: json['contentmodel'] as String?, + pagelanguage: json['pagelanguage'] as String?, + pagelanguagehtmlcode: json['pagelanguagehtmlcode'] as String?, + pagelanguagedir: json['pagelanguagedir'] as String?, + updatedTime: json['touched'] == null + ? null + : DateTime.parse(json['touched'] as String), + lastrevid: json['lastrevid'] as int?, + length: json['length'] as int?, + fullurl: json['fullurl'] as String?, + editurl: json['editurl'] as String?, + canonicalurl: json['canonicalurl'] as String?, + ) + ..displayTitle = json['displayTitle'] as String? + ..inwatchlist = json['inwatchlist'] as bool? + ..thumbnail = json['thumbnail'] == null + ? null + : PageImageInfo.fromJson(json['thumbnail'] as Map); + +Map _$PageInfoToJson(PageInfo instance) => { + 'pageid': instance.pageid, + 'ns': instance.ns, + 'title': instance.title, + 'displayTitle': instance.displayTitle, + 'subtitle': instance.subtitle, + 'lastrevid': instance.lastrevid, + 'contentmodel': instance.contentmodel, + 'pagelanguage': instance.pagelanguage, + 'pagelanguagehtmlcode': instance.pagelanguagehtmlcode, + 'pagelanguagedir': instance.pagelanguagedir, + 'inwatchlist': instance.inwatchlist, + 'length': instance.length, + 'fullurl': instance.fullurl, + 'editurl': instance.editurl, + 'canonicalurl': instance.canonicalurl, + 'thumbnail': instance.thumbnail, + 'extract': instance.description, + 'touched': instance.updatedTime?.toIso8601String(), + }; + +PagesResponse _$PagesResponseFromJson(Map json) => + PagesResponse( + pages: (json['pages'] as List) + .map((e) => PageInfo.fromJson(e as Map)) + .toList(), + ); + +Map _$PagesResponseToJson(PagesResponse instance) => + { + 'pages': instance.pages, + }; + +PageImageInfo _$PageImageInfoFromJson(Map json) => + PageImageInfo( + source: json['source'] as String, + width: json['width'] as int?, + height: json['height'] as int?, + ); + +Map _$PageImageInfoToJson(PageImageInfo instance) => + { + 'source': instance.source, + 'width': instance.width, + 'height': instance.height, + }; diff --git a/lib/api/response/recent_changes.dart b/lib/api/response/recent_changes.dart new file mode 100644 index 0000000..cc180d3 --- /dev/null +++ b/lib/api/response/recent_changes.dart @@ -0,0 +1,51 @@ +import 'package:json_annotation/json_annotation.dart'; + +part 'recent_changes.g.dart'; + +@JsonSerializable() +class RecentChangesItem { + String? type; + + int ns; + + String title; + + int pageid; + + int revid; + + @JsonKey(name: 'old_revid') + int? oldRevid; + + int? rcid; + + DateTime timestamp; + + RecentChangesItem({ + this.type, + required this.ns, + required this.title, + required this.pageid, + required this.revid, + this.oldRevid, + this.rcid, + required this.timestamp, + }); + + factory RecentChangesItem.fromJson(Map json) => + _$RecentChangesItemFromJson(json); + + Map toJson() => _$RecentChangesItemToJson(this); +} + +@JsonSerializable() +class RecentChangesResponse { + List recentchanges; + + RecentChangesResponse({required this.recentchanges}); + + factory RecentChangesResponse.fromJson(Map json) => + _$RecentChangesResponseFromJson(json); + + Map toJson() => _$RecentChangesResponseToJson(this); +} diff --git a/lib/api/response/recent_changes.g.dart b/lib/api/response/recent_changes.g.dart new file mode 100644 index 0000000..586a00d --- /dev/null +++ b/lib/api/response/recent_changes.g.dart @@ -0,0 +1,45 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'recent_changes.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +RecentChangesItem _$RecentChangesItemFromJson(Map json) => + RecentChangesItem( + type: json['type'] as String?, + ns: json['ns'] as int, + title: json['title'] as String, + pageid: json['pageid'] as int, + revid: json['revid'] as int, + oldRevid: json['old_revid'] as int?, + rcid: json['rcid'] as int?, + timestamp: DateTime.parse(json['timestamp'] as String), + ); + +Map _$RecentChangesItemToJson(RecentChangesItem instance) => + { + 'type': instance.type, + 'ns': instance.ns, + 'title': instance.title, + 'pageid': instance.pageid, + 'revid': instance.revid, + 'old_revid': instance.oldRevid, + 'rcid': instance.rcid, + 'timestamp': instance.timestamp.toIso8601String(), + }; + +RecentChangesResponse _$RecentChangesResponseFromJson( + Map json) => + RecentChangesResponse( + recentchanges: (json['recentchanges'] as List) + .map((e) => RecentChangesItem.fromJson(e as Map)) + .toList(), + ); + +Map _$RecentChangesResponseToJson( + RecentChangesResponse instance) => + { + 'recentchanges': instance.recentchanges, + }; diff --git a/lib/api/restbase/page.dart b/lib/api/restbase/page.dart new file mode 100644 index 0000000..7d61f5b --- /dev/null +++ b/lib/api/restbase/page.dart @@ -0,0 +1,12 @@ +import 'package:isekai_wiki/api/restbase/restbase_api.dart'; + +class RestfulPageApi { + static Future getPageHtml(String title, {int? revId}) async { + title = Uri.encodeComponent(title); + var url = "/page/html/$title"; + if (revId != null) { + url += "/$revId"; + } + return await RestbaseApi.get(url); + } +} diff --git a/lib/api/restbase/restbase_api.dart b/lib/api/restbase/restbase_api.dart new file mode 100644 index 0000000..247009f --- /dev/null +++ b/lib/api/restbase/restbase_api.dart @@ -0,0 +1,58 @@ +import 'dart:convert'; +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:http/http.dart' as http; +import 'package:isekai_wiki/global.dart'; + +import 'package:isekai_wiki/utils/api_utils.dart'; + +import '../mw/mw_api.dart'; + +const restBaseUrl = "https://www.isekai.cn/api/rest_v1"; + +class RestbaseApi { + static String restApiEndpoint = restBaseUrl; + + static Uri getUri(String endpoint, {Map? search}) { + String url = restApiEndpoint; + if (url.endsWith("/")) { + url = url.substring(0, url.length - 1); + } + + return Uri.parse(url + endpoint).replace(queryParameters: search); + } + + static Future> _getHeaders() async { + Map headers = {}; + + if (!kIsWeb) { + headers["X-IsekaiWikiApp-Version"] = Global.packageInfo?.version ?? "unknow"; + headers["User-Agent"] = await ApiUtils.getUserAgent(); + } + + return headers; + } + + static Future get(String path, {Map? search}) async { + var uri = getUri(path, search: search); + + var res = await http.get(uri, headers: await _getHeaders()); + + if (res.statusCode != 200) { + throw HttpResponseCodeError(res.statusCode); + } + + return res.body; + } + + static Future getJson(String path) async { + var resText = await get(path); + var resData = jsonDecode(resText); + + if (resData is Map) { + return resData; + } else { + return {}; + } + } +} diff --git a/lib/app.dart b/lib/app.dart new file mode 100755 index 0000000..c2bd01b --- /dev/null +++ b/lib/app.dart @@ -0,0 +1,40 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'models/model.dart'; +import 'pages/tab_page.dart'; +import 'styles.dart'; + +class IsekaiWikiApp extends StatelessWidget { + const IsekaiWikiApp({super.key}); + + // This widget is the root of your application. + @override + Widget build(BuildContext context) { + return Material( + child: GetCupertinoApp( + title: '异世界百科', + theme: const CupertinoThemeData( + textTheme: Styles.defaultTextTheme, + scaffoldBackgroundColor: Styles.themePageBackgroundColor), + localizationsDelegates: const >[ + DefaultMaterialLocalizations.delegate, + DefaultWidgetsLocalizations.delegate, + DefaultCupertinoLocalizations.delegate, + ], + initialBinding: InitialBinding(), + home: const IsekaiWikiTabsPage(), + builder: (context, child) { + if (child == null) { + return Container(); + } else { + Styles.textScaleFactor = MediaQuery.of(context).textScaleFactor; + Styles.isXs = MediaQuery.of(context).size.width <= 340; + return child; + } + }, + debugShowCheckedModeBanner: false, + ), + ); + } +} diff --git a/lib/components/backbutton_nav.dart b/lib/components/backbutton_nav.dart new file mode 100755 index 0000000..e0cbea9 --- /dev/null +++ b/lib/components/backbutton_nav.dart @@ -0,0 +1,21 @@ +import 'package:flutter/cupertino.dart'; + +class BackButtonNav extends StatelessWidget { + final BuildContext context; + final Widget child; + + const BackButtonNav({super.key, required this.context, required this.child}); + + Future _handleWillPop() async { + if (Navigator.canPop(context)) { + Navigator.pop(context); + return false; + } + return false; + } + + @override + Widget build(BuildContext context) { + return WillPopScope(onWillPop: _handleWillPop, child: child); + } +} diff --git a/lib/components/collapsed_tab.dart b/lib/components/collapsed_tab.dart new file mode 100755 index 0000000..efafe4a --- /dev/null +++ b/lib/components/collapsed_tab.dart @@ -0,0 +1,14 @@ +import 'package:flutter/cupertino.dart'; + +class CollapsedTabText extends StatelessWidget { + final String text; + const CollapsedTabText(this.text, {super.key}); + + @override + Widget build(BuildContext context) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10), + child: Center(child: Text(text)), + ); + } +} \ No newline at end of file diff --git a/lib/components/dummy_icon.dart b/lib/components/dummy_icon.dart new file mode 100755 index 0000000..57f644a --- /dev/null +++ b/lib/components/dummy_icon.dart @@ -0,0 +1,37 @@ +import 'package:flutter/cupertino.dart'; + +class DummyIcon extends StatelessWidget { + const DummyIcon( + {Key? key, + required this.color, + required this.icon, + this.size = 30.0, + this.rounded = false}) + : super(key: key); + + final double size; + final Color color; + final IconData icon; + final bool rounded; + + @override + Widget build(BuildContext context) { + return Container( + width: size, + height: size, + decoration: BoxDecoration( + color: color, + borderRadius: rounded + ? BorderRadius.circular(size / 2) + : BorderRadius.circular(size / 6), + ), + child: Center( + child: Icon( + icon, + color: CupertinoColors.white, + size: size * 0.6, + ), + ), + ); + } +} diff --git a/lib/components/flutter_scale_tap/flutter_scale_tap.dart b/lib/components/flutter_scale_tap/flutter_scale_tap.dart new file mode 100644 index 0000000..af38114 --- /dev/null +++ b/lib/components/flutter_scale_tap/flutter_scale_tap.dart @@ -0,0 +1,248 @@ +library flutter_scale_tap; + +import 'dart:math'; + +import 'package:flutter/physics.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; +import 'package:get/get.dart'; + +const double _DEFAULT_SCALE_MIN_VALUE = 0.96; +const double _DEFAULT_OPACITY_MIN_VALUE = 0.90; +final Curve _DEFAULT_SCALE_CURVE = + CurveSpring(); // ignore: non_constant_identifier_names +const Curve _DEFAULT_OPACITY_CURVE = Curves.ease; +const Duration _DEFAULT_DURATION = Duration(milliseconds: 250); + +class ScaleTapConfig { + static double? scaleMinValue; + static Curve? scaleCurve; + static double? opacityMinValue; + static Curve? opacityCurve; + static Duration? duration; +} + +class ScaleTapController extends GetxController { + var ignoredAreaPressing = false; +} + +class ScaleTap extends StatefulWidget { + final Future Function()? onPressed; + final Future Function()? onLongPress; + final Widget? child; + final Duration? duration; + final double? scaleMinValue; + final Curve? scaleCurve; + final Curve? opacityCurve; + final double? opacityMinValue; + final bool enableFeedback; + + ScaleTap({ + this.enableFeedback = true, + this.onPressed, + this.onLongPress, + required this.child, + this.duration, + this.scaleMinValue, + this.opacityMinValue, + this.scaleCurve, + this.opacityCurve, + }); + + @override + _ScaleTapState createState() => _ScaleTapState(); +} + +class _ScaleTapState extends State + with SingleTickerProviderStateMixin { + late AnimationController _animationController; + late Animation _scale; + late Animation _opacity; + + var c = ScaleTapController(); + + bool _scaleAnimating = false; + bool _isPressing = false; + bool _isEventBlocking = false; + + @override + void initState() { + super.initState(); + + c = Get.put(c); + + _animationController = AnimationController(vsync: this); + _scale = Tween(begin: 1.0, end: 1.0).animate(_animationController); + _opacity = + Tween(begin: 1.0, end: 1.0).animate(_animationController); + } + + @override + void dispose() { + _animationController.dispose(); + super.dispose(); + } + + Future anim({double? scale, double? opacity, Duration? duration}) { + _animationController.stop(); + _animationController.duration = duration ?? Duration.zero; + + _scale = Tween( + begin: _scale.value, + end: scale, + ).animate(CurvedAnimation( + curve: widget.scaleCurve ?? + ScaleTapConfig.scaleCurve ?? + _DEFAULT_SCALE_CURVE, + parent: _animationController, + )); + _opacity = Tween( + begin: _opacity.value, + end: opacity, + ).animate(CurvedAnimation( + curve: widget.opacityCurve ?? + ScaleTapConfig.opacityCurve ?? + _DEFAULT_OPACITY_CURVE, + parent: _animationController, + )); + _animationController.reset(); + return _animationController.forward(); + } + + Future recoverySize() async { + if (!_scaleAnimating && !_isPressing && !_isEventBlocking) { + return await anim( + scale: 1.0, + opacity: 1.0, + duration: + widget.duration ?? ScaleTapConfig.duration ?? _DEFAULT_DURATION, + ); + } + } + + Future _onTapDown(_) async { + if (c.ignoredAreaPressing) return; + + _isPressing = true; + _scaleAnimating = true; + + await anim( + scale: widget.scaleMinValue ?? + ScaleTapConfig.scaleMinValue ?? + _DEFAULT_SCALE_MIN_VALUE, + opacity: widget.opacityMinValue ?? + ScaleTapConfig.opacityMinValue ?? + _DEFAULT_OPACITY_MIN_VALUE, + duration: widget.duration ?? ScaleTapConfig.duration ?? _DEFAULT_DURATION, + ); + + _scaleAnimating = false; + await recoverySize(); + } + + Future _onTapUp(_) async { + _isPressing = false; + c.ignoredAreaPressing = false; + return await recoverySize(); + } + + Future _onTapCancel(_) { + return _onTapUp(_); + } + + @override + Widget build(BuildContext context) { + final bool isTapEnabled = + widget.onPressed != null || widget.onLongPress != null; + + return AnimatedBuilder( + animation: _animationController, + builder: (_, Widget? child) { + return Opacity( + opacity: _opacity.value, + child: Transform.scale( + alignment: Alignment.center, + scale: _scale.value, + child: child, + ), + ); + }, + child: Listener( + onPointerDown: isTapEnabled ? _onTapDown : null, + onPointerCancel: _onTapCancel, + onPointerUp: _onTapUp, + child: GestureDetector( + onTap: isTapEnabled + ? () async { + if (c.ignoredAreaPressing) return; + + if (widget.enableFeedback) { + SystemSound.play(SystemSoundType.click); + } + + _isEventBlocking = true; + + await Future.delayed(const Duration(milliseconds: 50)); + + await widget.onPressed?.call(); + _isEventBlocking = false; + recoverySize(); + } + : null, + onLongPress: isTapEnabled + ? () async { + if (c.ignoredAreaPressing) return; + + _isEventBlocking = true; + widget.onLongPress?.call(); + _isEventBlocking = false; + recoverySize(); + } + : null, + child: widget.child, + ), + ), + ); + } +} + +class ScaleTapIgnore extends StatelessWidget { + final Widget child; + + const ScaleTapIgnore({super.key, required this.child}); + + @override + Widget build(BuildContext context) { + var c = Get.find(); + return Listener( + onPointerDown: (_) { + c.ignoredAreaPressing = true; + }, + child: GestureDetector( + child: child, + onTap: () {}, + onLongPress: () {}, + ), + ); + } +} + +class CurveSpring extends Curve { + final SpringSimulation sim; + + CurveSpring() : this.sim = _sim(70, 20); + + @override + double transform(double t) => sim.x(t) + t * (1 - sim.x(1.0)); +} + +_sim(double stiffness, double damping) => SpringSimulation( + SpringDescription.withDampingRatio( + mass: 1, + stiffness: stiffness, + ratio: 0.7, + ), + 0.0, + 1.0, + 0.0, + ); diff --git a/lib/components/follow_scale.dart b/lib/components/follow_scale.dart new file mode 100755 index 0000000..0e69df2 --- /dev/null +++ b/lib/components/follow_scale.dart @@ -0,0 +1,11 @@ +import 'package:flutter/cupertino.dart'; +import 'package:isekai_wiki/styles.dart'; + +class FollowTextScale extends StatelessWidget { + final Widget child; + const FollowTextScale({super.key, required this.child}); + @override + Widget build(BuildContext context) { + return MediaQuery(data: MediaQueryData(textScaleFactor: Styles.textScaleFactor), child: child); + } +} diff --git a/lib/components/gesture_detector.dart b/lib/components/gesture_detector.dart new file mode 100755 index 0000000..602931c --- /dev/null +++ b/lib/components/gesture_detector.dart @@ -0,0 +1,32 @@ +import 'package:flutter/widgets.dart'; + +import '../styles.dart'; + +class OpacityGestureDetector extends StatefulWidget { + final String text; + + const OpacityGestureDetector(this.text, {super.key}); + + @override + State createState() => _OpacityGestureDetectorState(); +} + +class _OpacityGestureDetectorState extends State { + bool checked = false; + bool animChecked = false; + + @override + void initState() { + super.initState(); + } + + @override + Widget build(BuildContext context) { + return Text(widget.text, + style: const TextStyle( + color: Styles.themeNavTitleColor, + fontWeight: FontWeight.normal + ), + ); + } +} \ No newline at end of file diff --git a/lib/components/isekai_nav_bar.dart b/lib/components/isekai_nav_bar.dart new file mode 100755 index 0000000..d9c6376 --- /dev/null +++ b/lib/components/isekai_nav_bar.dart @@ -0,0 +1,2440 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'dart:math' as math; +import 'dart:ui' show ImageFilter; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/foundation.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; + +/// Standard iOS navigation bar height without the status bar. +/// +/// This height is constant and independent of accessibility as it is in iOS. +const double _kNavBarPersistentHeight = kMinInteractiveDimensionCupertino; + +/// Size increase from expanding the navigation bar into an iOS-11-style large title +/// form in a [CustomScrollView]. +const double _kNavBarLargeTitleHeightExtension = 52.0; + +/// Number of logical pixels scrolled down before the title text is transferred +/// from the normal navigation bar to a big title below the navigation bar. +const double _kNavBarShowLargeTitleThreshold = 10.0; + +const double _kNavBarEdgePadding = 16.0; + +const double _kNavBarBackButtonTapWidth = 50.0; + +/// Title text transfer fade. +const Duration _kNavBarTitleFadeDuration = Duration(milliseconds: 150); + +const Color _kDefaultNavBarBorderColor = Color(0x4D000000); + +const Border _kDefaultNavBarBorder = Border( + bottom: BorderSide( + color: _kDefaultNavBarBorderColor, + width: 0.0, // 0.0 means one physical pixel + ), +); + +// There's a single tag for all instances of navigation bars because they can +// all transition between each other (per Navigator) via Hero transitions. +const _HeroTag _defaultHeroTag = _HeroTag(null); + +@immutable +class _HeroTag { + const _HeroTag(this.navigator); + + final NavigatorState? navigator; + + // Let the Hero tag be described in tree dumps. + @override + String toString() => + 'Default Hero tag for Cupertino navigation bars with navigator $navigator'; + + @override + bool operator ==(Object other) { + if (identical(this, other)) { + return true; + } + if (other.runtimeType != runtimeType) { + return false; + } + return other is _HeroTag && other.navigator == navigator; + } + + @override + int get hashCode => identityHashCode(navigator); +} + +// An `AnimatedWidget` that imposes a fixed size on its child widget, and +// shifts the child widget in the parent stack, driven by its `offsetAnimation` +// property. +class _FixedSizeSlidingTransition extends AnimatedWidget { + const _FixedSizeSlidingTransition({ + required this.isLTR, + required this.offsetAnimation, + required this.size, + required this.child, + }) : super(listenable: offsetAnimation); + + // Whether the writing direction used in the navigation bar transition is + // left-to-right. + final bool isLTR; + + // The fixed size to impose on `child`. + final Size size; + + // The animated offset from the top-leading corner of the stack. + // + // When `isLTR` is true, the `Offset` is the position of the child widget in + // the stack render box's regular coordinate space. + // + // When `isLTR` is false, the coordinate system is flipped around the + // horizontal axis and the origin is set to the top right corner of the render + // boxes. In other words, this parameter describes the offset from the top + // right corner of the stack, to the top right corner of the child widget, and + // the x-axis runs right to left. + final Animation offsetAnimation; + + final Widget child; + + @override + Widget build(BuildContext context) { + return Positioned( + top: offsetAnimation.value.dy, + left: isLTR ? offsetAnimation.value.dx : null, + right: isLTR ? null : offsetAnimation.value.dx, + width: size.width, + height: size.height, + child: child, + ); + } +} + +/// Returns `child` wrapped with background and a bottom border if background color +/// is opaque. Otherwise, also blur with [BackdropFilter]. +/// +/// When `updateSystemUiOverlay` is true, the nav bar will update the OS +/// status bar's color theme based on the background color of the nav bar. +Widget _wrapWithBackground({ + Border? border, + required Color backgroundColor, + Brightness? brightness, + required Widget child, + bool updateSystemUiOverlay = true, +}) { + Widget result = child; + if (updateSystemUiOverlay) { + final bool isDark = backgroundColor.computeLuminance() < 0.179; + final Brightness newBrightness = + brightness ?? (isDark ? Brightness.dark : Brightness.light); + final SystemUiOverlayStyle overlayStyle; + switch (newBrightness) { + case Brightness.dark: + overlayStyle = SystemUiOverlayStyle.light; + break; + case Brightness.light: + overlayStyle = SystemUiOverlayStyle.dark; + break; + } + result = AnnotatedRegion( + value: overlayStyle, + child: result, + ); + } + final DecoratedBox childWithBackground = DecoratedBox( + decoration: BoxDecoration( + border: border, + color: backgroundColor, + ), + child: result, + ); + + if (backgroundColor.alpha == 0xFF) { + return childWithBackground; + } + + return ClipRect( + child: BackdropFilter( + filter: ImageFilter.blur(sigmaX: 10.0, sigmaY: 10.0), + child: childWithBackground, + ), + ); +} + +// Whether the current route supports nav bar hero transitions from or to. +bool _isTransitionable(BuildContext context) { + final ModalRoute? route = ModalRoute.of(context); + + // Fullscreen dialogs never transitions their nav bar with other push-style + // pages' nav bars or with other fullscreen dialog pages on the way in or on + // the way out. + return route is PageRoute && !route.fullscreenDialog; +} + +/// An iOS-styled navigation bar. +/// +/// The navigation bar is a toolbar that minimally consists of a widget, normally +/// a page title, in the [middle] of the toolbar. +/// +/// It also supports a [leading] and [trailing] widget before and after the +/// [middle] widget while keeping the [middle] widget centered. +/// +/// The [leading] widget will automatically be a back chevron icon button (or a +/// close button in case of a fullscreen dialog) to pop the current route if none +/// is provided and [automaticallyImplyLeading] is true (true by default). +/// +/// The [middle] widget will automatically be a title text from the current +/// [CupertinoPageRoute] if none is provided and [automaticallyImplyMiddle] is +/// true (true by default). +/// +/// It should be placed at top of the screen and automatically accounts for +/// the OS's status bar. +/// +/// If the given [backgroundColor]'s opacity is not 1.0 (which is the case by +/// default), it will produce a blurring effect to the content behind it. +/// +/// When [transitionBetweenRoutes] is true, this navigation bar will transition +/// on top of the routes instead of inside them if the route being transitioned +/// to also has a [IsekaiNavigationBar] or a [IsekaiSliverNavigationBar] +/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is +/// true, none of the [Widget] parameters can contain a key in its subtree since +/// that widget will exist in multiple places in the tree simultaneously. +/// +/// By default, only one [IsekaiNavigationBar] or [IsekaiSliverNavigationBar] +/// should be present in each [PageRoute] to support the default transitions. +/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition +/// behavior for multiple navigation bars per route. +/// +/// When used in a [CupertinoPageScaffold], [CupertinoPageScaffold.navigationBar] +/// has its text scale factor set to 1.0 and does not respond to text scale factor +/// changes from the operating system, to match the native iOS behavior. To override +/// this behavior, wrap each of the `navigationBar`'s components inside a [MediaQuery] +/// with the desired [MediaQueryData.textScaleFactor] value. The text scale factor +/// value from the operating system can be retrieved in many ways, such as querying +/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext]. +/// +/// {@tool dartpad} +/// This example shows a [IsekaiNavigationBar] placed in a [CupertinoPageScaffold]. +/// Since [backgroundColor]'s opacity is not 1.0, there is a blur effect and +/// content slides underneath. +/// +/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_navigation_bar.0.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [CupertinoPageScaffold], a page layout helper typically hosting the +/// [IsekaiNavigationBar]. +/// * [IsekaiSliverNavigationBar] for a navigation bar to be placed in a +/// scrolling list and that supports iOS-11-style large titles. +/// * +class IsekaiNavigationBar extends StatefulWidget + implements ObstructingPreferredSizeWidget { + /// Creates a navigation bar in the iOS style. + const IsekaiNavigationBar({ + super.key, + this.leading, + this.automaticallyImplyLeading = true, + this.automaticallyImplyMiddle = true, + this.previousPageTitle, + this.middle, + this.trailing, + this.border = _kDefaultNavBarBorder, + this.backgroundColor, + this.brightness, + this.padding, + this.transitionBetweenRoutes = true, + this.heroTag = _defaultHeroTag, + }) : assert(automaticallyImplyLeading != null), + assert(automaticallyImplyMiddle != null), + assert(transitionBetweenRoutes != null), + assert( + heroTag != null, + 'heroTag cannot be null. Use transitionBetweenRoutes = false to ' + 'disable Hero transition on this navigation bar.', + ), + assert( + !transitionBetweenRoutes || identical(heroTag, _defaultHeroTag), + 'Cannot specify a heroTag override if this navigation bar does not ' + 'transition due to transitionBetweenRoutes = false.', + ); + + /// {@template flutter.cupertino.IsekaiNavigationBar.leading} + /// Widget to place at the start of the navigation bar. Normally a back button + /// for a normal page or a cancel button for full page dialogs. + /// + /// If null and [automaticallyImplyLeading] is true, an appropriate button + /// will be automatically created. + /// {@endtemplate} + final Widget? leading; + + /// {@template flutter.cupertino.IsekaiNavigationBar.automaticallyImplyLeading} + /// Controls whether we should try to imply the leading widget if null. + /// + /// If true and [leading] is null, automatically try to deduce what the [leading] + /// widget should be. If [leading] widget is not null, this parameter has no effect. + /// + /// Specifically this navigation bar will: + /// + /// 1. Show a 'Close' button if the current route is a `fullscreenDialog`. + /// 2. Show a back chevron with [previousPageTitle] if [previousPageTitle] is + /// not null. + /// 3. Show a back chevron with the previous route's `title` if the current + /// route is a [CupertinoPageRoute] and the previous route is also a + /// [CupertinoPageRoute]. + /// + /// This value cannot be null. + /// {@endtemplate} + final bool automaticallyImplyLeading; + + /// Controls whether we should try to imply the middle widget if null. + /// + /// If true and [middle] is null, automatically fill in a [Text] widget with + /// the current route's `title` if the route is a [CupertinoPageRoute]. + /// If [middle] widget is not null, this parameter has no effect. + /// + /// This value cannot be null. + final bool automaticallyImplyMiddle; + + /// {@template flutter.cupertino.IsekaiNavigationBar.previousPageTitle} + /// Manually specify the previous route's title when automatically implying + /// the leading back button. + /// + /// Overrides the text shown with the back chevron instead of automatically + /// showing the previous [CupertinoPageRoute]'s `title` when + /// [automaticallyImplyLeading] is true. + /// + /// Has no effect when [leading] is not null or if [automaticallyImplyLeading] + /// is false. + /// {@endtemplate} + final String? previousPageTitle; + + /// Widget to place in the middle of the navigation bar. Normally a title or + /// a segmented control. + /// + /// If null and [automaticallyImplyMiddle] is true, an appropriate [Text] + /// title will be created if the current route is a [CupertinoPageRoute] and + /// has a `title`. + final Widget? middle; + + /// {@template flutter.cupertino.IsekaiNavigationBar.trailing} + /// Widget to place at the end of the navigation bar. Normally additional actions + /// taken on the page such as a search or edit function. + /// {@endtemplate} + final Widget? trailing; + + // TODO(xster): https://github.com/flutter/flutter/issues/10469 implement + // support for double row navigation bars. + + /// {@template flutter.cupertino.IsekaiNavigationBar.backgroundColor} + /// The background color of the navigation bar. If it contains transparency, the + /// tab bar will automatically produce a blurring effect to the content + /// behind it. + /// + /// Defaults to [CupertinoTheme]'s `barBackgroundColor` if null. + /// {@endtemplate} + final Color? backgroundColor; + + /// {@template flutter.cupertino.IsekaiNavigationBar.brightness} + /// The brightness of the specified [backgroundColor]. + /// + /// Setting this value changes the style of the system status bar. Typically + /// used to increase the contrast ratio of the system status bar over + /// [backgroundColor]. + /// + /// If set to null, the value of the property will be inferred from the relative + /// luminance of [backgroundColor]. + /// {@endtemplate} + final Brightness? brightness; + + /// {@template flutter.cupertino.IsekaiNavigationBar.padding} + /// Padding for the contents of the navigation bar. + /// + /// If null, the navigation bar will adopt the following defaults: + /// + /// * Vertically, contents will be sized to the same height as the navigation + /// bar itself minus the status bar. + /// * Horizontally, padding will be 16 pixels according to iOS specifications + /// unless the leading widget is an automatically inserted back button, in + /// which case the padding will be 0. + /// + /// Vertical padding won't change the height of the nav bar. + /// {@endtemplate} + final EdgeInsetsDirectional? padding; + + /// {@template flutter.cupertino.IsekaiNavigationBar.border} + /// The border of the navigation bar. By default renders a single pixel bottom border side. + /// + /// If a border is null, the navigation bar will not display a border. + /// {@endtemplate} + final Border? border; + + /// {@template flutter.cupertino.IsekaiNavigationBar.transitionBetweenRoutes} + /// Whether to transition between navigation bars. + /// + /// When [transitionBetweenRoutes] is true, this navigation bar will transition + /// on top of the routes instead of inside it if the route being transitioned + /// to also has a [IsekaiNavigationBar] or a [IsekaiSliverNavigationBar] + /// with [transitionBetweenRoutes] set to true. + /// + /// This transition will also occur on edge back swipe gestures like on iOS + /// but only if the previous page below has `maintainState` set to true on the + /// [PageRoute]. + /// + /// When set to true, only one navigation bar can be present per route unless + /// [heroTag] is also set. + /// + /// This value defaults to true and cannot be null. + /// {@endtemplate} + final bool transitionBetweenRoutes; + + /// {@template flutter.cupertino.IsekaiNavigationBar.heroTag} + /// Tag for the navigation bar's Hero widget if [transitionBetweenRoutes] is true. + /// + /// Defaults to a common tag between all [IsekaiNavigationBar] and + /// [IsekaiSliverNavigationBar] instances of the same [Navigator]. With the + /// default tag, all navigation bars of the same navigator can transition + /// between each other as long as there's only one navigation bar per route. + /// + /// This [heroTag] can be overridden to manually handle having multiple + /// navigation bars per route or to transition between multiple + /// [Navigator]s. + /// + /// Cannot be null. To disable Hero transitions for this navigation bar, + /// set [transitionBetweenRoutes] to false. + /// {@endtemplate} + final Object heroTag; + + /// True if the navigation bar's background color has no transparency. + @override + bool shouldFullyObstruct(BuildContext context) { + final Color backgroundColor = + CupertinoDynamicColor.maybeResolve(this.backgroundColor, context) ?? + CupertinoTheme.of(context).barBackgroundColor; + return backgroundColor.alpha == 0xFF; + } + + @override + Size get preferredSize { + return const Size.fromHeight(_kNavBarPersistentHeight); + } + + @override + State createState() => _IsekaiNavigationBarState(); +} + +// A state class exists for the nav bar so that the keys of its sub-components +// don't change when rebuilding the nav bar, causing the sub-components to +// lose their own states. +class _IsekaiNavigationBarState extends State { + late _NavigationBarStaticComponentsKeys keys; + + @override + void initState() { + super.initState(); + keys = _NavigationBarStaticComponentsKeys(); + } + + @override + Widget build(BuildContext context) { + final Color backgroundColor = + CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? + CupertinoTheme.of(context).barBackgroundColor; + + final _NavigationBarStaticComponents components = + _NavigationBarStaticComponents( + keys: keys, + route: ModalRoute.of(context), + userLeading: widget.leading, + automaticallyImplyLeading: widget.automaticallyImplyLeading, + automaticallyImplyTitle: widget.automaticallyImplyMiddle, + previousPageTitle: widget.previousPageTitle, + userMiddle: widget.middle, + userTrailing: widget.trailing, + padding: widget.padding, + userLargeTitle: null, + large: false, + ); + + final Widget navBar = _wrapWithBackground( + border: widget.border, + backgroundColor: backgroundColor, + brightness: widget.brightness, + child: DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: _PersistentNavigationBar( + components: components, + padding: widget.padding, + ), + ), + ); + + if (!widget.transitionBetweenRoutes || !_isTransitionable(context)) { + // Lint ignore to maintain backward compatibility. + return navBar; + } + + return Builder( + // Get the context that might have a possibly changed CupertinoTheme. + builder: (BuildContext context) { + return Hero( + tag: widget.heroTag == _defaultHeroTag + ? _HeroTag(Navigator.of(context)) + : widget.heroTag, + createRectTween: _linearTranslateWithLargestRectSizeTween, + placeholderBuilder: _navBarHeroLaunchPadBuilder, + flightShuttleBuilder: _navBarHeroFlightShuttleBuilder, + transitionOnUserGestures: true, + child: _TransitionableNavigationBar( + componentsKeys: keys, + backgroundColor: backgroundColor, + backButtonTextStyle: + CupertinoTheme.of(context).textTheme.navActionTextStyle, + titleTextStyle: + CupertinoTheme.of(context).textTheme.navTitleTextStyle, + largeTitleTextStyle: null, + border: widget.border, + hasUserMiddle: widget.middle != null, + largeExpanded: false, + child: navBar, + ), + ); + }, + ); + } +} + +/// An iOS-styled navigation bar with iOS-11-style large titles using slivers. +/// +/// The [IsekaiSliverNavigationBar] must be placed in a sliver group such +/// as the [CustomScrollView]. +/// +/// This navigation bar consists of two sections, a pinned static section on top +/// and a sliding section containing iOS-11-style large title below it. +/// +/// It should be placed at top of the screen and automatically accounts for +/// the iOS status bar. +/// +/// Minimally, a [largeTitle] widget will appear in the middle of the app bar +/// when the sliver is collapsed and transfer to the area below in larger font +/// when the sliver is expanded. +/// +/// For advanced uses, an optional [middle] widget can be supplied to show a +/// different widget in the middle of the navigation bar when the sliver is collapsed. +/// +/// Like [IsekaiNavigationBar], it also supports a [leading] and [trailing] +/// widget on the static section on top that remains while scrolling. +/// +/// The [leading] widget will automatically be a back chevron icon button (or a +/// close button in case of a fullscreen dialog) to pop the current route if none +/// is provided and [automaticallyImplyLeading] is true (true by default). +/// +/// The [largeTitle] widget will automatically be a title text from the current +/// [CupertinoPageRoute] if none is provided and [automaticallyImplyTitle] is +/// true (true by default). +/// +/// When [transitionBetweenRoutes] is true, this navigation bar will transition +/// on top of the routes instead of inside them if the route being transitioned +/// to also has a [IsekaiNavigationBar] or a [IsekaiSliverNavigationBar] +/// with [transitionBetweenRoutes] set to true. If [transitionBetweenRoutes] is +/// true, none of the [Widget] parameters can contain any [GlobalKey]s in their +/// subtrees since those widgets will exist in multiple places in the tree +/// simultaneously. +/// +/// By default, only one [IsekaiNavigationBar] or [IsekaiSliverNavigationBar] +/// should be present in each [PageRoute] to support the default transitions. +/// Use [transitionBetweenRoutes] or [heroTag] to customize the transition +/// behavior for multiple navigation bars per route. +/// +/// `IsekaiSliverNavigationBar` has its text scale factor set to 1.0 by default +/// and does not respond to text scale factor changes from the operating system, +/// to match the native iOS behavior. To override this behavior, wrap each of the +/// `IsekaiSliverNavigationBar`'s components inside a [MediaQuery] with the +/// desired [MediaQueryData.textScaleFactor] value. The text scale factor value +/// from the operating system can be retrieved in many ways, such as querying +/// [MediaQuery.textScaleFactorOf] against [CupertinoApp]'s [BuildContext]. +/// +/// The [stretch] parameter determines whether the nav bar should stretch to +/// fill the over-scroll area. The nav bar can still expand and contract as the +/// user scrolls, but it will also stretch when the user over-scrolls if the +/// [stretch] value is `true`. Defaults to `false`. +/// +/// {@tool dartpad} +/// This example shows [IsekaiSliverNavigationBar] in action inside a [CustomScrollView]. +/// +/// ** See code in examples/api/lib/cupertino/nav_bar/cupertino_sliver_nav_bar.0.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [IsekaiNavigationBar], an iOS navigation bar for use on non-scrolling +/// pages. +/// * [CustomScrollView], a ScrollView that creates custom scroll effects using slivers. +/// * +class IsekaiSliverNavigationBar extends StatefulWidget { + /// Creates a navigation bar for scrolling lists. + /// + /// The [largeTitle] argument is required and must not be null. + const IsekaiSliverNavigationBar({ + super.key, + this.largeTitle, + this.leading, + this.automaticallyImplyLeading = true, + this.automaticallyImplyTitle = true, + this.previousPageTitle, + this.middle, + this.trailing, + this.border = _kDefaultNavBarBorder, + this.backgroundColor, + this.brightness, + this.padding, + this.transitionBetweenRoutes = true, + this.heroTag = _defaultHeroTag, + this.stretch = false, + }) : assert(automaticallyImplyLeading != null), + assert(automaticallyImplyTitle != null), + assert( + automaticallyImplyTitle == true || largeTitle != null, + 'No largeTitle has been provided but automaticallyImplyTitle is also ' + 'false. Either provide a largeTitle or set automaticallyImplyTitle to ' + 'true.', + ); + + /// The navigation bar's title. + /// + /// This text will appear in the top static navigation bar when collapsed and + /// below the navigation bar, in a larger font, when expanded. + /// + /// A suitable [DefaultTextStyle] is provided around this widget as it is + /// moved around, to change its font size. + /// + /// If [middle] is null, then the [largeTitle] widget will be inserted into + /// the tree in two places when transitioning from the collapsed state to the + /// expanded state. It is therefore imperative that this subtree not contain + /// any [GlobalKey]s, and that it not rely on maintaining state (for example, + /// animations will not survive the transition from one location to the other, + /// and may in fact be visible in two places at once during the transition). + /// + /// If null and [automaticallyImplyTitle] is true, an appropriate [Text] + /// title will be created if the current route is a [CupertinoPageRoute] and + /// has a `title`. + /// + /// This parameter must either be non-null or the route must have a title + /// ([CupertinoPageRoute.title]) and [automaticallyImplyTitle] must be true. + final Widget? largeTitle; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.leading} + /// + /// This widget is visible in both collapsed and expanded states. + final Widget? leading; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.automaticallyImplyLeading} + final bool automaticallyImplyLeading; + + /// Controls whether we should try to imply the [largeTitle] widget if null. + /// + /// If true and [largeTitle] is null, automatically fill in a [Text] widget + /// with the current route's `title` if the route is a [CupertinoPageRoute]. + /// If [largeTitle] widget is not null, this parameter has no effect. + /// + /// This value cannot be null. + final bool automaticallyImplyTitle; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.previousPageTitle} + final String? previousPageTitle; + + /// A widget to place in the middle of the static navigation bar instead of + /// the [largeTitle]. + /// + /// This widget is visible in both collapsed and expanded states. The text + /// supplied in [largeTitle] will no longer appear in collapsed state if a + /// [middle] widget is provided. + final Widget? middle; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.trailing} + /// + /// This widget is visible in both collapsed and expanded states. + final Widget? trailing; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.backgroundColor} + final Color? backgroundColor; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.brightness} + final Brightness? brightness; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.padding} + final EdgeInsetsDirectional? padding; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.border} + final Border? border; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.transitionBetweenRoutes} + final bool transitionBetweenRoutes; + + /// {@macro flutter.cupertino.IsekaiNavigationBar.heroTag} + final Object heroTag; + + /// True if the navigation bar's background color has no transparency. + bool get opaque => backgroundColor?.alpha == 0xFF; + + /// Whether the nav bar should stretch to fill the over-scroll area. + /// + /// The nav bar can still expand and contract as the user scrolls, but it will + /// also stretch when the user over-scrolls if the [stretch] value is `true`. + /// + /// When set to `true`, the nav bar will prevent subsequent slivers from + /// accessing overscrolls. This may be undesirable for using overscroll-based + /// widgets like the [CupertinoSliverRefreshControl]. + /// + /// Defaults to `false`. + final bool stretch; + + @override + State createState() => + _IsekaiSliverNavigationBarState(); +} + +// A state class exists for the nav bar so that the keys of its sub-components +// don't change when rebuilding the nav bar, causing the sub-components to +// lose their own states. +class _IsekaiSliverNavigationBarState extends State { + late _NavigationBarStaticComponentsKeys keys; + + @override + void initState() { + super.initState(); + keys = _NavigationBarStaticComponentsKeys(); + } + + @override + Widget build(BuildContext context) { + final _NavigationBarStaticComponents components = + _NavigationBarStaticComponents( + keys: keys, + route: ModalRoute.of(context), + userLeading: widget.leading, + automaticallyImplyLeading: widget.automaticallyImplyLeading, + automaticallyImplyTitle: widget.automaticallyImplyTitle, + previousPageTitle: widget.previousPageTitle, + userMiddle: widget.middle, + userTrailing: widget.trailing, + userLargeTitle: widget.largeTitle, + padding: widget.padding, + large: true, + ); + + return SliverPersistentHeader( + pinned: true, // iOS navigation bars are always pinned. + delegate: _LargeTitleNavigationBarSliverDelegate( + keys: keys, + components: components, + userMiddle: widget.middle, + backgroundColor: CupertinoDynamicColor.maybeResolve( + widget.backgroundColor, context) ?? + CupertinoTheme.of(context).barBackgroundColor, + brightness: widget.brightness, + border: widget.border, + padding: widget.padding, + actionsForegroundColor: CupertinoTheme.of(context).primaryColor, + transitionBetweenRoutes: widget.transitionBetweenRoutes, + heroTag: widget.heroTag, + persistentHeight: + _kNavBarPersistentHeight + MediaQuery.of(context).padding.top, + alwaysShowMiddle: widget.middle != null, + stretchConfiguration: + widget.stretch ? OverScrollHeaderStretchConfiguration() : null, + ), + ); + } +} + +class _LargeTitleNavigationBarSliverDelegate + extends SliverPersistentHeaderDelegate with DiagnosticableTreeMixin { + _LargeTitleNavigationBarSliverDelegate({ + required this.keys, + required this.components, + required this.userMiddle, + required this.backgroundColor, + required this.brightness, + required this.border, + required this.padding, + required this.actionsForegroundColor, + required this.transitionBetweenRoutes, + required this.heroTag, + required this.persistentHeight, + required this.alwaysShowMiddle, + required this.stretchConfiguration, + }) : assert(persistentHeight != null), + assert(alwaysShowMiddle != null), + assert(transitionBetweenRoutes != null); + + final _NavigationBarStaticComponentsKeys keys; + final _NavigationBarStaticComponents components; + final Widget? userMiddle; + final Color backgroundColor; + final Brightness? brightness; + final Border? border; + final EdgeInsetsDirectional? padding; + final Color actionsForegroundColor; + final bool transitionBetweenRoutes; + final Object heroTag; + final double persistentHeight; + final bool alwaysShowMiddle; + + @override + double get minExtent => persistentHeight; + + @override + double get maxExtent => persistentHeight + _kNavBarLargeTitleHeightExtension; + + @override + OverScrollHeaderStretchConfiguration? stretchConfiguration; + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + final bool showLargeTitle = + shrinkOffset < maxExtent - minExtent - _kNavBarShowLargeTitleThreshold; + + final _PersistentNavigationBar persistentNavigationBar = + _PersistentNavigationBar( + components: components, + padding: padding, + // If a user specified middle exists, always show it. Otherwise, show + // title when sliver is collapsed. + middleVisible: alwaysShowMiddle ? null : !showLargeTitle, + ); + + final Widget navBar = _wrapWithBackground( + border: border, + backgroundColor: CupertinoDynamicColor.resolve(backgroundColor, context), + brightness: brightness, + child: DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.textStyle, + child: Stack( + fit: StackFit.expand, + children: [ + Positioned( + top: persistentHeight, + left: 0.0, + right: 0.0, + bottom: 0.0, + child: ClipRect( + // The large title starts at the persistent bar. + // It's aligned with the bottom of the sliver and expands clipped + // and behind the persistent bar. + child: OverflowBox( + minHeight: 0.0, + maxHeight: double.infinity, + alignment: AlignmentDirectional.bottomStart, + child: Padding( + padding: const EdgeInsetsDirectional.only( + start: _kNavBarEdgePadding, + bottom: 8.0, // Bottom has a different padding. + ), + child: SafeArea( + top: false, + bottom: false, + child: AnimatedOpacity( + opacity: showLargeTitle ? 1.0 : 0.0, + duration: _kNavBarTitleFadeDuration, + child: Semantics( + header: true, + child: DefaultTextStyle( + style: CupertinoTheme.of(context) + .textTheme + .navLargeTitleTextStyle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: components.largeTitle!, + ), + ), + ), + ), + ), + ), + ), + ), + Positioned( + left: 0.0, + right: 0.0, + top: 0.0, + child: persistentNavigationBar, + ), + ], + ), + ), + ); + + if (!transitionBetweenRoutes || !_isTransitionable(context)) { + return navBar; + } + + return Hero( + tag: heroTag == _defaultHeroTag + ? _HeroTag(Navigator.of(context)) + : heroTag, + createRectTween: _linearTranslateWithLargestRectSizeTween, + flightShuttleBuilder: _navBarHeroFlightShuttleBuilder, + placeholderBuilder: _navBarHeroLaunchPadBuilder, + transitionOnUserGestures: true, + // This is all the way down here instead of being at the top level of + // IsekaiSliverNavigationBar like IsekaiNavigationBar because it + // needs to wrap the top level RenderBox rather than a RenderSliver. + child: _TransitionableNavigationBar( + componentsKeys: keys, + backgroundColor: + CupertinoDynamicColor.resolve(backgroundColor, context), + backButtonTextStyle: + CupertinoTheme.of(context).textTheme.navActionTextStyle, + titleTextStyle: CupertinoTheme.of(context).textTheme.navTitleTextStyle, + largeTitleTextStyle: + CupertinoTheme.of(context).textTheme.navLargeTitleTextStyle, + border: border, + hasUserMiddle: userMiddle != null, + largeExpanded: showLargeTitle, + child: navBar, + ), + ); + } + + @override + bool shouldRebuild(_LargeTitleNavigationBarSliverDelegate oldDelegate) { + return components != oldDelegate.components || + userMiddle != oldDelegate.userMiddle || + backgroundColor != oldDelegate.backgroundColor || + border != oldDelegate.border || + padding != oldDelegate.padding || + actionsForegroundColor != oldDelegate.actionsForegroundColor || + transitionBetweenRoutes != oldDelegate.transitionBetweenRoutes || + persistentHeight != oldDelegate.persistentHeight || + alwaysShowMiddle != oldDelegate.alwaysShowMiddle || + heroTag != oldDelegate.heroTag; + } +} + +/// The top part of the navigation bar that's never scrolled away. +/// +/// Consists of the entire navigation bar without background and border when used +/// without large titles. With large titles, it's the top static half that +/// doesn't scroll. +class _PersistentNavigationBar extends StatelessWidget { + const _PersistentNavigationBar({ + required this.components, + this.padding, + this.middleVisible, + }); + + final _NavigationBarStaticComponents components; + + final EdgeInsetsDirectional? padding; + + /// Whether the middle widget has a visible animated opacity. A null value + /// means the middle opacity will not be animated. + final bool? middleVisible; + + @override + Widget build(BuildContext context) { + Widget? middle = components.middle; + + if (middle != null) { + middle = DefaultTextStyle( + style: CupertinoTheme.of(context).textTheme.navTitleTextStyle, + child: Semantics(header: true, child: middle), + ); + // When the middle's visibility can change on the fly like with large title + // slivers, wrap with animated opacity. + middle = middleVisible == null + ? middle + : AnimatedOpacity( + opacity: middleVisible! ? 1.0 : 0.0, + duration: _kNavBarTitleFadeDuration, + child: middle, + ); + } + + Widget? leading = components.leading; + final Widget? backChevron = components.backChevron; + final Widget? backLabel = components.backLabel; + + if (leading == null && backChevron != null && backLabel != null) { + leading = IsekaiNavigationBarBackButton._assemble( + backChevron, + backLabel, + ); + } + + Widget paddedToolbar = NavigationToolbar( + leading: leading, + middle: middle, + trailing: components.trailing, + middleSpacing: 6.0, + ); + + if (padding != null) { + paddedToolbar = Padding( + padding: EdgeInsets.only( + top: padding!.top, + bottom: padding!.bottom, + ), + child: paddedToolbar, + ); + } + + return SizedBox( + height: _kNavBarPersistentHeight + MediaQuery.of(context).padding.top, + child: SafeArea( + bottom: false, + child: paddedToolbar, + ), + ); + } +} + +// A collection of keys always used when building static routes' nav bars's +// components with _NavigationBarStaticComponents and read in +// _NavigationBarTransition in Hero flights in order to reference the components' +// RenderBoxes for their positions. +// +// These keys should never re-appear inside the Hero flights. +@immutable +class _NavigationBarStaticComponentsKeys { + _NavigationBarStaticComponentsKeys() + : navBarBoxKey = GlobalKey(debugLabel: 'Navigation bar render box'), + leadingKey = GlobalKey(debugLabel: 'Leading'), + backChevronKey = GlobalKey(debugLabel: 'Back chevron'), + backLabelKey = GlobalKey(debugLabel: 'Back label'), + middleKey = GlobalKey(debugLabel: 'Middle'), + trailingKey = GlobalKey(debugLabel: 'Trailing'), + largeTitleKey = GlobalKey(debugLabel: 'Large title'); + + final GlobalKey navBarBoxKey; + final GlobalKey leadingKey; + final GlobalKey backChevronKey; + final GlobalKey backLabelKey; + final GlobalKey middleKey; + final GlobalKey trailingKey; + final GlobalKey largeTitleKey; +} + +// Based on various user Widgets and other parameters, construct KeyedSubtree +// components that are used in common by the IsekaiNavigationBar and +// IsekaiSliverNavigationBar. The KeyedSubtrees are inserted into static +// routes and the KeyedSubtrees' child are reused in the Hero flights. +@immutable +class _NavigationBarStaticComponents { + _NavigationBarStaticComponents({ + required _NavigationBarStaticComponentsKeys keys, + required ModalRoute? route, + required Widget? userLeading, + required bool automaticallyImplyLeading, + required bool automaticallyImplyTitle, + required String? previousPageTitle, + required Widget? userMiddle, + required Widget? userTrailing, + required Widget? userLargeTitle, + required EdgeInsetsDirectional? padding, + required bool large, + }) : leading = createLeading( + leadingKey: keys.leadingKey, + userLeading: userLeading, + route: route, + automaticallyImplyLeading: automaticallyImplyLeading, + padding: padding, + ), + backChevron = createBackChevron( + backChevronKey: keys.backChevronKey, + userLeading: userLeading, + route: route, + automaticallyImplyLeading: automaticallyImplyLeading, + ), + backLabel = createBackLabel( + backLabelKey: keys.backLabelKey, + userLeading: userLeading, + route: route, + previousPageTitle: previousPageTitle, + automaticallyImplyLeading: automaticallyImplyLeading, + ), + middle = createMiddle( + middleKey: keys.middleKey, + userMiddle: userMiddle, + userLargeTitle: userLargeTitle, + route: route, + automaticallyImplyTitle: automaticallyImplyTitle, + large: large, + ), + trailing = createTrailing( + trailingKey: keys.trailingKey, + userTrailing: userTrailing, + padding: padding, + ), + largeTitle = createLargeTitle( + largeTitleKey: keys.largeTitleKey, + userLargeTitle: userLargeTitle, + route: route, + automaticImplyTitle: automaticallyImplyTitle, + large: large, + ); + + static Widget? _derivedTitle({ + required bool automaticallyImplyTitle, + ModalRoute? currentRoute, + }) { + // Auto use the CupertinoPageRoute's title if middle not provided. + if (automaticallyImplyTitle && + currentRoute is CupertinoRouteTransitionMixin && + currentRoute.title != null) { + return Text(currentRoute.title!); + } + + return null; + } + + final KeyedSubtree? leading; + static KeyedSubtree? createLeading({ + required GlobalKey leadingKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, + required EdgeInsetsDirectional? padding, + }) { + Widget? leadingContent; + + if (userLeading != null) { + leadingContent = userLeading; + } else if (automaticallyImplyLeading && + route is PageRoute && + route.canPop && + route.fullscreenDialog) { + leadingContent = CupertinoButton( + padding: EdgeInsets.zero, + onPressed: () { + route.navigator!.maybePop(); + }, + child: const Text('Close'), + ); + } + + if (leadingContent == null) { + return null; + } + + return KeyedSubtree( + key: leadingKey, + child: Padding( + padding: EdgeInsetsDirectional.only( + start: padding?.start ?? _kNavBarEdgePadding, + ), + child: IconTheme.merge( + data: const IconThemeData( + size: 32.0, + ), + child: leadingContent, + ), + ), + ); + } + + final KeyedSubtree? backChevron; + static KeyedSubtree? createBackChevron({ + required GlobalKey backChevronKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, + }) { + if (userLeading != null || + !automaticallyImplyLeading || + route == null || + !route.canPop || + (route is PageRoute && route.fullscreenDialog)) { + return null; + } + + return KeyedSubtree(key: backChevronKey, child: const _BackChevron()); + } + + /// This widget is not decorated with a font since the font style could + /// animate during transitions. + final KeyedSubtree? backLabel; + static KeyedSubtree? createBackLabel({ + required GlobalKey backLabelKey, + required Widget? userLeading, + required ModalRoute? route, + required bool automaticallyImplyLeading, + required String? previousPageTitle, + }) { + if (userLeading != null || + !automaticallyImplyLeading || + route == null || + !route.canPop || + (route is PageRoute && route.fullscreenDialog)) { + return null; + } + + return KeyedSubtree( + key: backLabelKey, + child: _BackLabel( + specifiedPreviousTitle: previousPageTitle, + route: route, + ), + ); + } + + /// This widget is not decorated with a font since the font style could + /// animate during transitions. + final KeyedSubtree? middle; + static KeyedSubtree? createMiddle({ + required GlobalKey middleKey, + required Widget? userMiddle, + required Widget? userLargeTitle, + required bool large, + required bool automaticallyImplyTitle, + required ModalRoute? route, + }) { + Widget? middleContent = userMiddle; + + if (large) { + middleContent ??= userLargeTitle; + } + + middleContent ??= _derivedTitle( + automaticallyImplyTitle: automaticallyImplyTitle, + currentRoute: route, + ); + + if (middleContent == null) { + return null; + } + + return KeyedSubtree( + key: middleKey, + child: middleContent, + ); + } + + final KeyedSubtree? trailing; + static KeyedSubtree? createTrailing({ + required GlobalKey trailingKey, + required Widget? userTrailing, + required EdgeInsetsDirectional? padding, + }) { + if (userTrailing == null) { + return null; + } + + return KeyedSubtree( + key: trailingKey, + child: Padding( + padding: EdgeInsetsDirectional.only( + end: padding?.end ?? _kNavBarEdgePadding, + ), + child: IconTheme.merge( + data: const IconThemeData( + size: 32.0, + ), + child: userTrailing, + ), + ), + ); + } + + /// This widget is not decorated with a font since the font style could + /// animate during transitions. + final KeyedSubtree? largeTitle; + static KeyedSubtree? createLargeTitle({ + required GlobalKey largeTitleKey, + required Widget? userLargeTitle, + required bool large, + required bool automaticImplyTitle, + required ModalRoute? route, + }) { + if (!large) { + return null; + } + + final Widget? largeTitleContent = userLargeTitle ?? + _derivedTitle( + automaticallyImplyTitle: automaticImplyTitle, + currentRoute: route, + ); + + assert( + largeTitleContent != null, + 'largeTitle was not provided and there was no title from the route.', + ); + + return KeyedSubtree( + key: largeTitleKey, + child: largeTitleContent!, + ); + } +} + +/// A nav bar back button typically used in [IsekaiNavigationBar]. +/// +/// This is automatically inserted into [IsekaiNavigationBar] and +/// [IsekaiSliverNavigationBar]'s `leading` slot when +/// `automaticallyImplyLeading` is true. +/// +/// When manually inserted, the [IsekaiNavigationBarBackButton] should only +/// be used in routes that can be popped unless a custom [onPressed] is +/// provided. +/// +/// Shows a back chevron and the previous route's title when available from +/// the previous [CupertinoPageRoute.title]. If [previousPageTitle] is specified, +/// it will be shown instead. +class IsekaiNavigationBarBackButton extends StatelessWidget { + /// Construct a [IsekaiNavigationBarBackButton] that can be used to pop + /// the current route. + /// + /// The [color] parameter must not be null. + const IsekaiNavigationBarBackButton({ + super.key, + this.color, + this.previousPageTitle, + this.onPressed, + }) : _backChevron = null, + _backLabel = null; + + // Allow the back chevron and label to be separately created (and keyed) + // because they animate separately during page transitions. + const IsekaiNavigationBarBackButton._assemble( + this._backChevron, + this._backLabel, + ) : previousPageTitle = null, + color = null, + onPressed = null; + + /// The [Color] of the back button. + /// + /// Can be used to override the color of the back button chevron and label. + /// + /// Defaults to [CupertinoTheme]'s `primaryColor` if null. + final Color? color; + + /// An override for showing the previous route's title. If null, it will be + /// automatically derived from [CupertinoPageRoute.title] if the current and + /// previous routes are both [CupertinoPageRoute]s. + final String? previousPageTitle; + + /// An override callback to perform instead of the default behavior which is + /// to pop the [Navigator]. + /// + /// It can, for instance, be used to pop the platform's navigation stack + /// via [SystemNavigator] instead of Flutter's [Navigator] in add-to-app + /// situations. + /// + /// Defaults to null. + final VoidCallback? onPressed; + + final Widget? _backChevron; + + final Widget? _backLabel; + + @override + Widget build(BuildContext context) { + final ModalRoute? currentRoute = ModalRoute.of(context); + if (onPressed == null) { + assert( + currentRoute?.canPop ?? false, + 'IsekaiNavigationBarBackButton should only be used in routes that can be popped', + ); + } + + TextStyle actionTextStyle = + CupertinoTheme.of(context).textTheme.navActionTextStyle; + if (color != null) { + actionTextStyle = actionTextStyle.copyWith( + color: CupertinoDynamicColor.maybeResolve(color, context)); + } + + return CupertinoButton( + padding: EdgeInsets.zero, + child: Semantics( + container: true, + excludeSemantics: true, + label: 'Back', + button: true, + child: DefaultTextStyle( + style: actionTextStyle, + child: ConstrainedBox( + constraints: + const BoxConstraints(minWidth: _kNavBarBackButtonTapWidth), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Padding(padding: EdgeInsetsDirectional.only(start: 8.0)), + _backChevron ?? const _BackChevron(), + const Padding(padding: EdgeInsetsDirectional.only(start: 6.0)), + Flexible( + child: _backLabel ?? + _BackLabel( + specifiedPreviousTitle: previousPageTitle, + route: currentRoute, + ), + ), + ], + ), + ), + ), + ), + onPressed: () { + if (onPressed != null) { + onPressed!(); + } else { + Navigator.maybePop(context); + } + }, + ); + } +} + +class _BackChevron extends StatelessWidget { + const _BackChevron(); + + @override + Widget build(BuildContext context) { + final TextDirection textDirection = Directionality.of(context); + final TextStyle textStyle = DefaultTextStyle.of(context).style; + + // Replicate the Icon logic here to get a tightly sized icon and add + // custom non-square padding. + Widget iconWidget = Padding( + padding: const EdgeInsetsDirectional.only(start: 6, end: 2), + child: Text.rich( + TextSpan( + text: String.fromCharCode(CupertinoIcons.back.codePoint), + style: TextStyle( + inherit: false, + color: textStyle.color, + fontSize: 30.0, + fontFamily: CupertinoIcons.back.fontFamily, + package: CupertinoIcons.back.fontPackage, + ), + ), + ), + ); + switch (textDirection) { + case TextDirection.rtl: + iconWidget = Transform( + transform: Matrix4.identity()..scale(-1.0, 1.0, 1.0), + alignment: Alignment.center, + transformHitTests: false, + child: iconWidget, + ); + break; + case TextDirection.ltr: + break; + } + + return iconWidget; + } +} + +/// A widget that shows next to the back chevron when `automaticallyImplyLeading` +/// is true. +class _BackLabel extends StatelessWidget { + const _BackLabel({ + required this.specifiedPreviousTitle, + required this.route, + }); + + final String? specifiedPreviousTitle; + final ModalRoute? route; + + // `child` is never passed in into ValueListenableBuilder so it's always + // null here and unused. + Widget _buildPreviousTitleWidget( + BuildContext context, String? previousTitle, Widget? child) { + previousTitle ??= "返回"; + + Text textWidget = Text( + previousTitle, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ); + + if (previousTitle.length > 12) { + textWidget = const Text('Back'); + } + + return Align( + alignment: AlignmentDirectional.centerStart, + widthFactor: 1.0, + child: textWidget, + ); + } + + @override + Widget build(BuildContext context) { + if (specifiedPreviousTitle != null) { + return _buildPreviousTitleWidget(context, specifiedPreviousTitle, null); + } else if (route is CupertinoRouteTransitionMixin && + !route!.isFirst) { + final CupertinoRouteTransitionMixin cupertinoRoute = + route! as CupertinoRouteTransitionMixin; + // There is no timing issue because the previousTitle Listenable changes + // happen during route modifications before the ValueListenableBuilder + // is built. + return ValueListenableBuilder( + valueListenable: cupertinoRoute.previousTitle, + builder: _buildPreviousTitleWidget, + ); + } else { + return const SizedBox(height: 0.0, width: 0.0); + } + } +} + +/// This should always be the first child of Hero widgets. +/// +/// This class helps each Hero transition obtain the start or end navigation +/// bar's box size and the inner components of the navigation bar that will +/// move around. +/// +/// It should be wrapped around the biggest [RenderBox] of the static +/// navigation bar in each route. +class _TransitionableNavigationBar extends StatelessWidget { + _TransitionableNavigationBar({ + required this.componentsKeys, + required this.backgroundColor, + required this.backButtonTextStyle, + required this.titleTextStyle, + required this.largeTitleTextStyle, + required this.border, + required this.hasUserMiddle, + required this.largeExpanded, + required this.child, + }) : assert(componentsKeys != null), + assert(largeExpanded != null), + assert(!largeExpanded || largeTitleTextStyle != null), + super(key: componentsKeys.navBarBoxKey); + + final _NavigationBarStaticComponentsKeys componentsKeys; + final Color? backgroundColor; + final TextStyle backButtonTextStyle; + final TextStyle titleTextStyle; + final TextStyle? largeTitleTextStyle; + final Border? border; + final bool hasUserMiddle; + final bool largeExpanded; + final Widget child; + + RenderBox get renderBox { + final RenderBox box = componentsKeys.navBarBoxKey.currentContext! + .findRenderObject()! as RenderBox; + assert( + box.attached, + '_TransitionableNavigationBar.renderBox should be called when building ' + 'hero flight shuttles when the from and the to nav bar boxes are already ' + 'laid out and painted.', + ); + return box; + } + + @override + Widget build(BuildContext context) { + assert(() { + bool inHero = false; + context.visitAncestorElements((Element ancestor) { + if (ancestor is ComponentElement) { + assert( + ancestor.widget.runtimeType != _NavigationBarTransition, + '_TransitionableNavigationBar should never re-appear inside ' + '_NavigationBarTransition. Keyed _TransitionableNavigationBar should ' + 'only serve as anchor points in routes rather than appearing inside ' + 'Hero flights themselves.', + ); + if (ancestor.widget.runtimeType == Hero) { + inHero = true; + } + } + return true; + }); + assert( + inHero, + '_TransitionableNavigationBar should only be added as the immediate ' + 'child of Hero widgets.', + ); + return true; + }()); + return child; + } +} + +/// This class represents the widget that will be in the Hero flight instead of +/// the 2 static navigation bars by taking inner components from both. +/// +/// The `topNavBar` parameter is the nav bar that was on top regardless of +/// push/pop direction. +/// +/// Similarly, the `bottomNavBar` parameter is the nav bar that was at the +/// bottom regardless of the push/pop direction. +/// +/// If [MediaQuery.padding] is still present in this widget's [BuildContext], +/// that padding will become part of the transitional navigation bar as well. +/// +/// [MediaQuery.padding] should be consistent between the from/to routes and +/// the Hero overlay. Inconsistent [MediaQuery.padding] will produce undetermined +/// results. +class _NavigationBarTransition extends StatelessWidget { + _NavigationBarTransition({ + required this.animation, + required this.topNavBar, + required this.bottomNavBar, + }) : heightTween = Tween( + begin: bottomNavBar.renderBox.size.height, + end: topNavBar.renderBox.size.height, + ), + backgroundTween = ColorTween( + begin: bottomNavBar.backgroundColor, + end: topNavBar.backgroundColor, + ), + borderTween = BorderTween( + begin: bottomNavBar.border, + end: topNavBar.border, + ); + + final Animation animation; + final _TransitionableNavigationBar topNavBar; + final _TransitionableNavigationBar bottomNavBar; + + final Tween heightTween; + final ColorTween backgroundTween; + final BorderTween borderTween; + + @override + Widget build(BuildContext context) { + final _NavigationBarComponentsTransition componentsTransition = + _NavigationBarComponentsTransition( + animation: animation, + bottomNavBar: bottomNavBar, + topNavBar: topNavBar, + directionality: Directionality.of(context), + ); + + final List children = [ + // Draw an empty navigation bar box with changing shape behind all the + // moving components without any components inside it itself. + AnimatedBuilder( + animation: animation, + builder: (BuildContext context, Widget? child) { + return _wrapWithBackground( + // Don't update the system status bar color mid-flight. + updateSystemUiOverlay: false, + backgroundColor: backgroundTween.evaluate(animation)!, + border: borderTween.evaluate(animation), + child: SizedBox( + height: heightTween.evaluate(animation), + width: double.infinity, + ), + ); + }, + ), + // Draw all the components on top of the empty bar box. + if (componentsTransition.bottomBackChevron != null) + componentsTransition.bottomBackChevron!, + if (componentsTransition.bottomBackLabel != null) + componentsTransition.bottomBackLabel!, + if (componentsTransition.bottomLeading != null) + componentsTransition.bottomLeading!, + if (componentsTransition.bottomMiddle != null) + componentsTransition.bottomMiddle!, + if (componentsTransition.bottomLargeTitle != null) + componentsTransition.bottomLargeTitle!, + if (componentsTransition.bottomTrailing != null) + componentsTransition.bottomTrailing!, + // Draw top components on top of the bottom components. + if (componentsTransition.topLeading != null) + componentsTransition.topLeading!, + if (componentsTransition.topBackChevron != null) + componentsTransition.topBackChevron!, + if (componentsTransition.topBackLabel != null) + componentsTransition.topBackLabel!, + if (componentsTransition.topMiddle != null) + componentsTransition.topMiddle!, + if (componentsTransition.topLargeTitle != null) + componentsTransition.topLargeTitle!, + if (componentsTransition.topTrailing != null) + componentsTransition.topTrailing!, + ]; + + // The actual outer box is big enough to contain both the bottom and top + // navigation bars. It's not a direct Rect lerp because some components + // can actually be outside the linearly lerp'ed Rect in the middle of + // the animation, such as the topLargeTitle. + return SizedBox( + height: math.max(heightTween.begin!, heightTween.end!) + + MediaQuery.of(context).padding.top, + width: double.infinity, + child: Stack( + children: children, + ), + ); + } +} + +/// This class helps create widgets that are in transition based on static +/// components from the bottom and top navigation bars. +/// +/// It animates these transitional components both in terms of position and +/// their appearance. +/// +/// Instead of running the transitional components through their normal static +/// navigation bar layout logic, this creates transitional widgets that are based +/// on these widgets' existing render objects' layout and position. +/// +/// This is possible because this widget is only used during Hero transitions +/// where both the from and to routes are already built and laid out. +/// +/// The components' existing layout constraints and positions are then +/// replicated using [Positioned] or [PositionedTransition] wrappers. +/// +/// This class should never return [KeyedSubtree]s created by +/// _NavigationBarStaticComponents directly. Since widgets from +/// _NavigationBarStaticComponents are still present in the widget tree during the +/// hero transitions, it would cause global key duplications. Instead, return +/// only the [KeyedSubtree]s' child. +@immutable +class _NavigationBarComponentsTransition { + _NavigationBarComponentsTransition({ + required this.animation, + required _TransitionableNavigationBar bottomNavBar, + required _TransitionableNavigationBar topNavBar, + required TextDirection directionality, + }) : bottomComponents = bottomNavBar.componentsKeys, + topComponents = topNavBar.componentsKeys, + bottomNavBarBox = bottomNavBar.renderBox, + topNavBarBox = topNavBar.renderBox, + bottomBackButtonTextStyle = bottomNavBar.backButtonTextStyle, + topBackButtonTextStyle = topNavBar.backButtonTextStyle, + bottomTitleTextStyle = bottomNavBar.titleTextStyle, + topTitleTextStyle = topNavBar.titleTextStyle, + bottomLargeTitleTextStyle = bottomNavBar.largeTitleTextStyle, + topLargeTitleTextStyle = topNavBar.largeTitleTextStyle, + bottomHasUserMiddle = bottomNavBar.hasUserMiddle, + topHasUserMiddle = topNavBar.hasUserMiddle, + bottomLargeExpanded = bottomNavBar.largeExpanded, + topLargeExpanded = topNavBar.largeExpanded, + transitionBox = + // paintBounds are based on offset zero so it's ok to expand the Rects. + bottomNavBar.renderBox.paintBounds + .expandToInclude(topNavBar.renderBox.paintBounds), + forwardDirection = directionality == TextDirection.ltr ? 1.0 : -1.0; + + static final Animatable fadeOut = Tween( + begin: 1.0, + end: 0.0, + ); + static final Animatable fadeIn = Tween( + begin: 0.0, + end: 1.0, + ); + + final Animation animation; + final _NavigationBarStaticComponentsKeys bottomComponents; + final _NavigationBarStaticComponentsKeys topComponents; + + // These render boxes that are the ancestors of all the bottom and top + // components are used to determine the components' relative positions inside + // their respective navigation bars. + final RenderBox bottomNavBarBox; + final RenderBox topNavBarBox; + + final TextStyle bottomBackButtonTextStyle; + final TextStyle topBackButtonTextStyle; + final TextStyle bottomTitleTextStyle; + final TextStyle topTitleTextStyle; + final TextStyle? bottomLargeTitleTextStyle; + final TextStyle? topLargeTitleTextStyle; + + final bool bottomHasUserMiddle; + final bool topHasUserMiddle; + final bool bottomLargeExpanded; + final bool topLargeExpanded; + + // This is the outer box in which all the components will be fitted. The + // sizing component of RelativeRects will be based on this rect's size. + final Rect transitionBox; + + // x-axis unity number representing the direction of growth for text. + final double forwardDirection; + + // Take a widget it its original ancestor navigation bar render box and + // translate it into a RelativeBox in the transition navigation bar box. + RelativeRect positionInTransitionBox( + GlobalKey key, { + required RenderBox from, + }) { + final RenderBox componentBox = + key.currentContext!.findRenderObject()! as RenderBox; + assert(componentBox.attached); + + return RelativeRect.fromRect( + componentBox.localToGlobal(Offset.zero, ancestor: from) & + componentBox.size, + transitionBox, + ); + } + + // Create an animated widget that moves the given child widget between its + // original position in its ancestor navigation bar to another widget's + // position in that widget's navigation bar. + // + // Anchor their positions based on the vertical middle of their respective + // render boxes' leading edge. + // + // This method assumes there's no other transforms other than translations + // when converting a rect from the original navigation bar's coordinate space + // to the other navigation bar's coordinate space, to avoid performing + // floating point operations on the size of the child widget, so that the + // incoming constraints used for sizing the child widget will be exactly the + // same. + _FixedSizeSlidingTransition slideFromLeadingEdge({ + required GlobalKey fromKey, + required RenderBox fromNavBarBox, + required GlobalKey toKey, + required RenderBox toNavBarBox, + required Widget child, + }) { + final RenderBox fromBox = + fromKey.currentContext!.findRenderObject()! as RenderBox; + final RenderBox toBox = + toKey.currentContext!.findRenderObject()! as RenderBox; + + final bool isLTR = forwardDirection > 0; + + // The animation moves the fromBox so its anchor (left-center or right-center + // depending on the writing direction) aligns with toBox's anchor. + final Offset fromAnchorLocal = Offset( + isLTR ? 0 : fromBox.size.width, + fromBox.size.height / 2, + ); + final Offset toAnchorLocal = Offset( + isLTR ? 0 : toBox.size.width, + toBox.size.height / 2, + ); + final Offset fromAnchorInFromBox = + fromBox.localToGlobal(fromAnchorLocal, ancestor: fromNavBarBox); + final Offset toAnchorInToBox = + toBox.localToGlobal(toAnchorLocal, ancestor: toNavBarBox); + + // We can't get ahold of the render box of the stack (i.e., `transitionBox`) + // we place components on yet, but we know the stack needs to be top-leading + // aligned with both fromNavBarBox and toNavBarBox to make the transition + // look smooth. Also use the top-leading point as the origin for ease of + // calculation. + + // The offset to move fromAnchor to toAnchor, in transitionBox's top-leading + // coordinates. + final Offset translation = isLTR + ? toAnchorInToBox - fromAnchorInFromBox + : Offset(toNavBarBox.size.width - toAnchorInToBox.dx, + toAnchorInToBox.dy) - + Offset(fromNavBarBox.size.width - fromAnchorInFromBox.dx, + fromAnchorInFromBox.dy); + + final RelativeRect fromBoxMargin = + positionInTransitionBox(fromKey, from: fromNavBarBox); + final Offset fromOriginInTransitionBox = Offset( + isLTR ? fromBoxMargin.left : fromBoxMargin.right, + fromBoxMargin.top, + ); + + final Tween anchorMovementInTransitionBox = Tween( + begin: fromOriginInTransitionBox, + end: fromOriginInTransitionBox + translation, + ); + + return _FixedSizeSlidingTransition( + isLTR: isLTR, + offsetAnimation: animation.drive(anchorMovementInTransitionBox), + size: fromBox.size, + child: child, + ); + } + + Animation fadeInFrom(double t, {Curve curve = Curves.easeIn}) { + return animation.drive(fadeIn.chain( + CurveTween(curve: Interval(t, 1.0, curve: curve)), + )); + } + + Animation fadeOutBy(double t, {Curve curve = Curves.easeOut}) { + return animation.drive(fadeOut.chain( + CurveTween(curve: Interval(0.0, t, curve: curve)), + )); + } + + Widget? get bottomLeading { + final KeyedSubtree? bottomLeading = + bottomComponents.leadingKey.currentWidget as KeyedSubtree?; + + if (bottomLeading == null) { + return null; + } + + return Positioned.fromRelativeRect( + rect: positionInTransitionBox(bottomComponents.leadingKey, + from: bottomNavBarBox), + child: FadeTransition( + opacity: fadeOutBy(0.4), + child: bottomLeading.child, + ), + ); + } + + Widget? get bottomBackChevron { + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; + + if (bottomBackChevron == null) { + return null; + } + + return Positioned.fromRelativeRect( + rect: positionInTransitionBox(bottomComponents.backChevronKey, + from: bottomNavBarBox), + child: FadeTransition( + opacity: fadeOutBy(0.6), + child: DefaultTextStyle( + style: bottomBackButtonTextStyle, + child: bottomBackChevron.child, + ), + ), + ); + } + + Widget? get bottomBackLabel { + final KeyedSubtree? bottomBackLabel = + bottomComponents.backLabelKey.currentWidget as KeyedSubtree?; + + if (bottomBackLabel == null) { + return null; + } + + final RelativeRect from = positionInTransitionBox( + bottomComponents.backLabelKey, + from: bottomNavBarBox); + + // Transition away by sliding horizontally to the leading edge off of the screen. + final RelativeRectTween positionTween = RelativeRectTween( + begin: from, + end: from.shift( + Offset( + forwardDirection * (-bottomNavBarBox.size.width / 2.0), + 0.0, + ), + ), + ); + + return PositionedTransition( + rect: animation.drive(positionTween), + child: FadeTransition( + opacity: fadeOutBy(0.2), + child: DefaultTextStyle( + style: bottomBackButtonTextStyle, + child: bottomBackLabel.child, + ), + ), + ); + } + + Widget? get bottomMiddle { + final KeyedSubtree? bottomMiddle = + bottomComponents.middleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = + topComponents.backLabelKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topLeading = + topComponents.leadingKey.currentWidget as KeyedSubtree?; + + // The middle component is non-null when the nav bar is a large title + // nav bar but would be invisible when expanded, therefore don't show it here. + if (!bottomHasUserMiddle && bottomLargeExpanded) { + return null; + } + + if (bottomMiddle != null && topBackLabel != null) { + // Move from current position to the top page's back label position. + return slideFromLeadingEdge( + fromKey: bottomComponents.middleKey, + fromNavBarBox: bottomNavBarBox, + toKey: topComponents.backLabelKey, + toNavBarBox: topNavBarBox, + child: FadeTransition( + // A custom middle widget like a segmented control fades away faster. + opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7), + child: Align( + // As the text shrinks, make sure it's still anchored to the leading + // edge of a constantly sized outer box. + alignment: AlignmentDirectional.centerStart, + child: DefaultTextStyleTransition( + style: animation.drive(TextStyleTween( + begin: bottomTitleTextStyle, + end: topBackButtonTextStyle, + )), + child: bottomMiddle.child, + ), + ), + ), + ); + } + + // When the top page has a leading widget override (one of the few ways to + // not have a top back label), don't move the bottom middle widget and just + // fade. + if (bottomMiddle != null && topLeading != null) { + return Positioned.fromRelativeRect( + rect: positionInTransitionBox(bottomComponents.middleKey, + from: bottomNavBarBox), + child: FadeTransition( + opacity: fadeOutBy(bottomHasUserMiddle ? 0.4 : 0.7), + // Keep the font when transitioning into a non-back label leading. + child: DefaultTextStyle( + style: bottomTitleTextStyle, + child: bottomMiddle.child, + ), + ), + ); + } + + return null; + } + + Widget? get bottomLargeTitle { + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = + topComponents.backLabelKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topLeading = + topComponents.leadingKey.currentWidget as KeyedSubtree?; + + if (bottomLargeTitle == null || !bottomLargeExpanded) { + return null; + } + + if (bottomLargeTitle != null && topBackLabel != null) { + // Move from current position to the top page's back label position. + return slideFromLeadingEdge( + fromKey: bottomComponents.largeTitleKey, + fromNavBarBox: bottomNavBarBox, + toKey: topComponents.backLabelKey, + toNavBarBox: topNavBarBox, + child: FadeTransition( + opacity: fadeOutBy(0.6), + child: Align( + // As the text shrinks, make sure it's still anchored to the leading + // edge of a constantly sized outer box. + alignment: AlignmentDirectional.centerStart, + child: DefaultTextStyleTransition( + style: animation.drive(TextStyleTween( + begin: bottomLargeTitleTextStyle, + end: topBackButtonTextStyle, + )), + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: bottomLargeTitle.child, + ), + ), + ), + ); + } + + if (bottomLargeTitle != null && topLeading != null) { + // Unlike bottom middle, the bottom large title moves when it can't + // transition to the top back label position. + final RelativeRect from = positionInTransitionBox( + bottomComponents.largeTitleKey, + from: bottomNavBarBox); + + final RelativeRectTween positionTween = RelativeRectTween( + begin: from, + end: from.shift( + Offset( + forwardDirection * bottomNavBarBox.size.width / 4.0, + 0.0, + ), + ), + ); + + // Just shift slightly towards the trailing edge instead of moving to the + // back label position. + return PositionedTransition( + rect: animation.drive(positionTween), + child: FadeTransition( + opacity: fadeOutBy(0.4), + // Keep the font when transitioning into a non-back-label leading. + child: DefaultTextStyle( + style: bottomLargeTitleTextStyle!, + child: bottomLargeTitle.child, + ), + ), + ); + } + + return null; + } + + Widget? get bottomTrailing { + final KeyedSubtree? bottomTrailing = + bottomComponents.trailingKey.currentWidget as KeyedSubtree?; + + if (bottomTrailing == null) { + return null; + } + + return Positioned.fromRelativeRect( + rect: positionInTransitionBox(bottomComponents.trailingKey, + from: bottomNavBarBox), + child: FadeTransition( + opacity: fadeOutBy(0.6), + child: bottomTrailing.child, + ), + ); + } + + Widget? get topLeading { + final KeyedSubtree? topLeading = + topComponents.leadingKey.currentWidget as KeyedSubtree?; + + if (topLeading == null) { + return null; + } + + return Positioned.fromRelativeRect( + rect: + positionInTransitionBox(topComponents.leadingKey, from: topNavBarBox), + child: FadeTransition( + opacity: fadeInFrom(0.6), + child: topLeading.child, + ), + ); + } + + Widget? get topBackChevron { + final KeyedSubtree? topBackChevron = + topComponents.backChevronKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomBackChevron = + bottomComponents.backChevronKey.currentWidget as KeyedSubtree?; + + if (topBackChevron == null) { + return null; + } + + final RelativeRect to = positionInTransitionBox( + topComponents.backChevronKey, + from: topNavBarBox); + RelativeRect from = to; + + // If it's the first page with a back chevron, shift in slightly from the + // right. + if (bottomBackChevron == null) { + final RenderBox topBackChevronBox = + topComponents.backChevronKey.currentContext!.findRenderObject()! + as RenderBox; + from = to.shift( + Offset( + forwardDirection * topBackChevronBox.size.width * 2.0, + 0.0, + ), + ); + } + + final RelativeRectTween positionTween = RelativeRectTween( + begin: from, + end: to, + ); + + return PositionedTransition( + rect: animation.drive(positionTween), + child: FadeTransition( + opacity: fadeInFrom(bottomBackChevron == null ? 0.7 : 0.4), + child: DefaultTextStyle( + style: topBackButtonTextStyle, + child: topBackChevron.child, + ), + ), + ); + } + + Widget? get topBackLabel { + final KeyedSubtree? bottomMiddle = + bottomComponents.middleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? bottomLargeTitle = + bottomComponents.largeTitleKey.currentWidget as KeyedSubtree?; + final KeyedSubtree? topBackLabel = + topComponents.backLabelKey.currentWidget as KeyedSubtree?; + + if (topBackLabel == null) { + return null; + } + + final RenderAnimatedOpacity? topBackLabelOpacity = topComponents + .backLabelKey.currentContext + ?.findAncestorRenderObjectOfType(); + + Animation? midClickOpacity; + if (topBackLabelOpacity != null && + topBackLabelOpacity.opacity.value < 1.0) { + midClickOpacity = animation.drive(Tween( + begin: 0.0, + end: topBackLabelOpacity.opacity.value, + )); + } + + // Pick up from an incoming transition from the large title. This is + // duplicated here from the bottomLargeTitle transition widget because the + // content text might be different. For instance, if the bottomLargeTitle + // text is too long, the topBackLabel will say 'Back' instead of the original + // text. + if (bottomLargeTitle != null && + topBackLabel != null && + bottomLargeExpanded) { + return slideFromLeadingEdge( + fromKey: bottomComponents.largeTitleKey, + fromNavBarBox: bottomNavBarBox, + toKey: topComponents.backLabelKey, + toNavBarBox: topNavBarBox, + child: FadeTransition( + opacity: midClickOpacity ?? fadeInFrom(0.4), + child: DefaultTextStyleTransition( + style: animation.drive(TextStyleTween( + begin: bottomLargeTitleTextStyle, + end: topBackButtonTextStyle, + )), + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: topBackLabel.child, + ), + ), + ); + } + + // The topBackLabel always comes from the large title first if available + // and expanded instead of middle. + if (bottomMiddle != null && topBackLabel != null) { + return slideFromLeadingEdge( + fromKey: bottomComponents.middleKey, + fromNavBarBox: bottomNavBarBox, + toKey: topComponents.backLabelKey, + toNavBarBox: topNavBarBox, + child: FadeTransition( + opacity: midClickOpacity ?? fadeInFrom(0.3), + child: DefaultTextStyleTransition( + style: animation.drive(TextStyleTween( + begin: bottomTitleTextStyle, + end: topBackButtonTextStyle, + )), + child: topBackLabel.child, + ), + ), + ); + } + + return null; + } + + Widget? get topMiddle { + final KeyedSubtree? topMiddle = + topComponents.middleKey.currentWidget as KeyedSubtree?; + + if (topMiddle == null) { + return null; + } + + // The middle component is non-null when the nav bar is a large title + // nav bar but would be invisible when expanded, therefore don't show it here. + if (!topHasUserMiddle && topLargeExpanded) { + return null; + } + + final RelativeRect to = + positionInTransitionBox(topComponents.middleKey, from: topNavBarBox); + final RenderBox toBox = topComponents.middleKey.currentContext! + .findRenderObject()! as RenderBox; + + final bool isLTR = forwardDirection > 0; + + // Anchor is the top-leading point of toBox, in transition box's top-leading + // coordinate space. + final Offset toAnchorInTransitionBox = Offset( + isLTR ? to.left : to.right, + to.top, + ); + + // Shift in from the trailing edge of the screen. + final Tween anchorMovementInTransitionBox = Tween( + begin: Offset( + // the "width / 2" here makes the middle widget's horizontal center on + // the trailing edge of the top nav bar. + topNavBarBox.size.width - toBox.size.width / 2, + to.top, + ), + end: toAnchorInTransitionBox, + ); + + return _FixedSizeSlidingTransition( + isLTR: isLTR, + offsetAnimation: animation.drive(anchorMovementInTransitionBox), + size: toBox.size, + child: FadeTransition( + opacity: fadeInFrom(0.25), + child: DefaultTextStyle( + style: topTitleTextStyle, + child: topMiddle.child, + ), + ), + ); + } + + Widget? get topTrailing { + final KeyedSubtree? topTrailing = + topComponents.trailingKey.currentWidget as KeyedSubtree?; + + if (topTrailing == null) { + return null; + } + + return Positioned.fromRelativeRect( + rect: positionInTransitionBox(topComponents.trailingKey, + from: topNavBarBox), + child: FadeTransition( + opacity: fadeInFrom(0.4), + child: topTrailing.child, + ), + ); + } + + Widget? get topLargeTitle { + final KeyedSubtree? topLargeTitle = + topComponents.largeTitleKey.currentWidget as KeyedSubtree?; + + if (topLargeTitle == null || !topLargeExpanded) { + return null; + } + + final RelativeRect to = positionInTransitionBox(topComponents.largeTitleKey, + from: topNavBarBox); + + // Shift in from the trailing edge of the screen. + final RelativeRectTween positionTween = RelativeRectTween( + begin: to.shift( + Offset( + forwardDirection * topNavBarBox.size.width, + 0.0, + ), + ), + end: to, + ); + + return PositionedTransition( + rect: animation.drive(positionTween), + child: FadeTransition( + opacity: fadeInFrom(0.3), + child: DefaultTextStyle( + style: topLargeTitleTextStyle!, + maxLines: 1, + overflow: TextOverflow.ellipsis, + child: topLargeTitle.child, + ), + ), + ); + } +} + +/// Navigation bars' hero rect tween that will move between the static bars +/// but keep a constant size that's the bigger of both navigation bars. +RectTween _linearTranslateWithLargestRectSizeTween(Rect? begin, Rect? end) { + final Size largestSize = Size( + math.max(begin!.size.width, end!.size.width), + math.max(begin.size.height, end.size.height), + ); + return RectTween( + begin: begin.topLeft & largestSize, + end: end.topLeft & largestSize, + ); +} + +Widget _navBarHeroLaunchPadBuilder( + BuildContext context, + Size heroSize, + Widget child, +) { + assert(child is _TransitionableNavigationBar); + // Tree reshaping is fine here because the Heroes' child is always a + // _TransitionableNavigationBar which has a GlobalKey. + + // Keeping the Hero subtree here is needed (instead of just swapping out the + // anchor nav bars for fixed size boxes during flights) because the nav bar + // and their specific component children may serve as anchor points again if + // another mid-transition flight diversion is triggered. + + // This is ok performance-wise because static nav bars are generally cheap to + // build and layout but expensive to GPU render (due to clips and blurs) which + // we're skipping here. + return Visibility( + maintainSize: true, + maintainAnimation: true, + maintainState: true, + visible: false, + child: child, + ); +} + +/// Navigation bars' hero flight shuttle builder. +Widget _navBarHeroFlightShuttleBuilder( + BuildContext flightContext, + Animation animation, + HeroFlightDirection flightDirection, + BuildContext fromHeroContext, + BuildContext toHeroContext, +) { + assert(animation != null); + assert(flightDirection != null); + assert(fromHeroContext != null); + assert(toHeroContext != null); + assert(fromHeroContext.widget is Hero); + assert(toHeroContext.widget is Hero); + + final Hero fromHeroWidget = fromHeroContext.widget as Hero; + final Hero toHeroWidget = toHeroContext.widget as Hero; + + assert(fromHeroWidget.child is _TransitionableNavigationBar); + assert(toHeroWidget.child is _TransitionableNavigationBar); + + final _TransitionableNavigationBar fromNavBar = + fromHeroWidget.child as _TransitionableNavigationBar; + final _TransitionableNavigationBar toNavBar = + toHeroWidget.child as _TransitionableNavigationBar; + + assert(fromNavBar.componentsKeys != null); + assert(toNavBar.componentsKeys != null); + + assert( + fromNavBar.componentsKeys.navBarBoxKey.currentContext!.owner != null, + 'The from nav bar to Hero must have been mounted in the previous frame', + ); + assert( + toNavBar.componentsKeys.navBarBoxKey.currentContext!.owner != null, + 'The to nav bar to Hero must have been mounted in the previous frame', + ); + + switch (flightDirection) { + case HeroFlightDirection.push: + return _NavigationBarTransition( + animation: animation, + bottomNavBar: fromNavBar, + topNavBar: toNavBar, + ); + case HeroFlightDirection.pop: + return _NavigationBarTransition( + animation: animation, + bottomNavBar: toNavBar, + topNavBar: fromNavBar, + ); + } +} diff --git a/lib/components/isekai_page_scaffold.dart b/lib/components/isekai_page_scaffold.dart new file mode 100755 index 0000000..da3275f --- /dev/null +++ b/lib/components/isekai_page_scaffold.dart @@ -0,0 +1,194 @@ +// Copyright 2014 The Flutter Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +import 'package:flutter/cupertino.dart'; + +/// Implements a single iOS application page's layout. +/// +/// The scaffold lays out the navigation bar on top and the content between or +/// behind the navigation bar. +/// +/// When tapping a status bar at the top of the IsekaiPageScaffold, an +/// animation will complete for the current primary [ScrollView], scrolling to +/// the beginning. This is done using the [PrimaryScrollController] that +/// encloses the [ScrollView]. The [ScrollView.primary] flag is used to connect +/// a [ScrollView] to the enclosing [PrimaryScrollController]. +/// +/// {@tool dartpad} +/// This example shows a [IsekaiPageScaffold] with a [ListView] as a [child]. +/// The [CupertinoButton] is connected to a callback that increments a counter. +/// The [backgroundColor] can be changed. +/// +/// ** See code in examples/api/lib/cupertino/page_scaffold/cupertino_page_scaffold.0.dart ** +/// {@end-tool} +/// +/// See also: +/// +/// * [CupertinoTabScaffold], a similar widget for tabbed applications. +/// * [CupertinoPageRoute], a modal page route that typically hosts a +/// [IsekaiPageScaffold] with support for iOS-style page transitions. +class IsekaiPageScaffold extends StatefulWidget { + /// Creates a layout for pages with a navigation bar at the top. + const IsekaiPageScaffold({ + super.key, + this.navigationBar, + this.backgroundColor, + this.resizeToAvoidBottomInset = true, + required this.child, + }) : assert(child != null), + assert(resizeToAvoidBottomInset != null); + + /// The [navigationBar], typically a [CupertinoNavigationBar], is drawn at the + /// top of the screen. + /// + /// If translucent, the main content may slide behind it. + /// Otherwise, the main content's top margin will be offset by its height. + /// + /// The scaffold assumes the navigation bar will account for the [MediaQuery] + /// top padding, also consume it if the navigation bar is opaque. + /// + /// By default `navigationBar` has its text scale factor set to 1.0 and does + /// not respond to text scale factor changes from the operating system, to match + /// the native iOS behavior. To override such behavior, wrap each of the `navigationBar`'s + /// components inside a [MediaQuery] with the desired [MediaQueryData.textScaleFactor] + /// value. The text scale factor value from the operating system can be retrieved + /// in many ways, such as querying [MediaQuery.textScaleFactorOf] against + /// [CupertinoApp]'s [BuildContext]. + // TODO(xster): document its page transition animation when ready + final ObstructingPreferredSizeWidget? navigationBar; + + /// Widget to show in the main content area. + /// + /// Content can slide under the [navigationBar] when they're translucent. + /// In that case, the child's [BuildContext]'s [MediaQuery] will have a + /// top padding indicating the area of obstructing overlap from the + /// [navigationBar]. + final Widget child; + + /// The color of the widget that underlies the entire scaffold. + /// + /// By default uses [CupertinoTheme]'s `scaffoldBackgroundColor` when null. + final Color? backgroundColor; + + /// Whether the [child] should size itself to avoid the window's bottom inset. + /// + /// For example, if there is an onscreen keyboard displayed above the + /// scaffold, the body can be resized to avoid overlapping the keyboard, which + /// prevents widgets inside the body from being obscured by the keyboard. + /// + /// Defaults to true and cannot be null. + final bool resizeToAvoidBottomInset; + + @override + State createState() => _IsekaiPageScaffoldState(); +} + +class _IsekaiPageScaffoldState extends State { + void _handleStatusBarTap() { + final ScrollController? primaryScrollController = PrimaryScrollController.of(context); + // Only act on the scroll controller if it has any attached scroll positions. + if (primaryScrollController != null && primaryScrollController.hasClients) { + primaryScrollController.animateTo( + 0.0, + // Eyeballed from iOS. + duration: const Duration(milliseconds: 500), + curve: Curves.linearToEaseOut, + ); + } + } + + @override + Widget build(BuildContext context) { + Widget paddedContent = widget.child; + + final MediaQueryData existingMediaQuery = MediaQuery.of(context); + if (widget.navigationBar != null) { + // TODO(xster): Use real size after partial layout instead of preferred size. + // https://github.com/flutter/flutter/issues/12912 + final double topPadding = widget.navigationBar!.preferredSize.height + existingMediaQuery.padding.top; + + // Propagate bottom padding and include viewInsets if appropriate + final double bottomPadding = widget.resizeToAvoidBottomInset ? existingMediaQuery.viewInsets.bottom : 0.0; + + final EdgeInsets newViewInsets = widget.resizeToAvoidBottomInset + // The insets are consumed by the scaffolds and no longer exposed to + // the descendant subtree. + ? existingMediaQuery.viewInsets.copyWith(bottom: 0.0) + : existingMediaQuery.viewInsets; + + final bool fullObstruction = widget.navigationBar!.shouldFullyObstruct(context); + + // If navigation bar is opaquely obstructing, directly shift the main content + // down. If translucent, let main content draw behind navigation bar but hint the + // obstructed area. + if (fullObstruction) { + paddedContent = MediaQuery( + data: existingMediaQuery + // If the navigation bar is opaque, the top media query padding is fully consumed by the navigation bar. + .removePadding(removeTop: true) + .copyWith( + viewInsets: newViewInsets, + ), + child: Padding( + padding: EdgeInsets.only(top: topPadding, bottom: bottomPadding), + child: paddedContent, + ), + ); + } else { + paddedContent = MediaQuery( + data: existingMediaQuery.copyWith( + padding: existingMediaQuery.padding.copyWith( + top: topPadding, + ), + viewInsets: newViewInsets, + ), + child: Padding( + padding: EdgeInsets.only(bottom: bottomPadding), + child: paddedContent, + ), + ); + } + } else { + // If there is no navigation bar, still may need to add padding in order + // to support resizeToAvoidBottomInset. + final double bottomPadding = widget.resizeToAvoidBottomInset ? existingMediaQuery.viewInsets.bottom : 0.0; + paddedContent = Padding( + padding: EdgeInsets.only(bottom: bottomPadding), + child: paddedContent, + ); + } + + return DecoratedBox( + decoration: BoxDecoration( + color: CupertinoDynamicColor.maybeResolve(widget.backgroundColor, context) ?? + CupertinoTheme.of(context).scaffoldBackgroundColor, + ), + child: Stack( + children: [ + // The main content being at the bottom is added to the stack first. + paddedContent, + if (widget.navigationBar != null) + Positioned( + top: 0.0, + left: 0.0, + right: 0.0, + child: widget.navigationBar!, + ), + // Add a touch handler the size of the status bar on top of all contents + // to handle scroll to top by status bar taps. + Positioned( + top: 0.0, + left: 0.0, + right: 0.0, + height: existingMediaQuery.padding.top, + child: GestureDetector( + excludeFromSemantics: true, + onTap: _handleStatusBarTap, + ), + ), + ], + ), + ); + } +} diff --git a/lib/components/page_card.dart b/lib/components/page_card.dart new file mode 100755 index 0000000..a6d22e7 --- /dev/null +++ b/lib/components/page_card.dart @@ -0,0 +1,375 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/api/response/page_info.dart'; +import 'package:isekai_wiki/components/flutter_scale_tap/flutter_scale_tap.dart'; +import 'package:isekai_wiki/components/utils.dart'; +import 'package:isekai_wiki/pages/article.dart'; +import 'package:isekai_wiki/reactive/reactive.dart'; +import 'package:like_button/like_button.dart'; +import 'package:pull_down_button/pull_down_button.dart'; +import 'package:skeletons/skeletons.dart'; + +import '../styles.dart'; + +typedef AddFavoriteCallback = Future Function( + PageInfo pageInfo, bool localIsFavorite, bool showToast); + +typedef PageInfoCallback = Future Function(PageInfo pageInfo); + +class PageCardStyles { + static const double cardInnerHeight = 140; + static const cardInnerPadding = + EdgeInsets.only(top: 16, left: 20, right: 20, bottom: 12); + static const double footerButtonSize = 30; + static const double footerButtonInnerSize = 26; +} + +class PageCardController extends GetxController { + var isLoading = false.obs; + + var pageInfo = Rx(null); + + var isFavorite = false.obs; + + AddFavoriteCallback? onSetFavorite; + PageInfoCallback? onShare; + + Future handleFavoriteClick(bool localIsFavorite) async { + if (pageInfo.value != null && onSetFavorite != null) { + return await onSetFavorite!.call(pageInfo.value!, localIsFavorite, false); + } else { + return false; + } + } + + Future handleAddFavoriteMenuItemClick() async { + if (pageInfo.value != null && onSetFavorite != null) { + await onSetFavorite!.call(pageInfo.value!, true, true); + } + } + + Future handleRemoveFavoriteMenuItemClick() async { + if (pageInfo.value != null && onSetFavorite != null) { + await onSetFavorite!.call(pageInfo.value!, false, true); + } + } + + handleShareClick() async { + if (pageInfo.value != null && onShare != null) { + await onShare!.call(pageInfo.value!); + } + } + + void handlePageInfoClick() { + if (pageInfo.value != null) {} + } + + Future handleCardClick() async { + if (isLoading.value) { + return; + } + + if (pageInfo.value != null) { + var cPageInfo = pageInfo.value!; + await Navigator.of(Get.context!).push( + CupertinoPageRoute( + builder: (_) => ArticlePage( + targetPage: cPageInfo.title, + initialArticleData: MinimumArticleData( + title: cPageInfo.mainTitle, + description: cPageInfo.description, + mainCategory: cPageInfo.mainCategory, + updateTime: cPageInfo.updatedTime, + ), + ), + ), + ); + } + } +} + +class PageCard extends StatefulWidget { + final bool isLoading; + final PageInfo? pageInfo; + final bool isFavorite; + final AddFavoriteCallback? onSetFavorite; + final PageInfoCallback? onShare; + + const PageCard({ + super.key, + this.isLoading = false, + this.pageInfo, + this.isFavorite = false, + this.onSetFavorite, + this.onShare, + }); + + @override + State createState() => _PageCardState(); +} + +class _PageCardState extends ReactiveState { + var c = PageCardController(); + double textScale = 1; + + @override + void initState() { + super.initState(); + Get.put(c); + } + + @override + void receiveProps() { + c.isLoading.value = widget.isLoading; + c.pageInfo.value = widget.pageInfo; + c.isFavorite.value = widget.isFavorite; + c.onSetFavorite = widget.onSetFavorite; + c.onShare = widget.onShare; + } + + Widget _actionButtonSkeleton(bool isLoading, Widget child) { + return Skeleton( + isLoading: isLoading, + skeleton: const SkeletonLine( + style: SkeletonLineStyle( + width: PageCardStyles.footerButtonSize, + height: PageCardStyles.footerButtonSize), + ), + child: child, + ); + } + + Widget _buildCardHeader(BuildContext context) { + return Padding( + padding: const EdgeInsets.only(bottom: 10), + child: Skeleton( + isLoading: c.isLoading.value, + skeleton: SkeletonLine( + style: SkeletonLineStyle( + height: (Styles.pageCardTitle.fontSize! + 4) * textScale, + randomLength: true), + ), + child: Text(c.pageInfo.value?.mainTitle ?? "页面信息丢失", + style: Styles.pageCardTitle), + ), + ); + } + + Widget _buildCardBody(BuildContext context) { + return Expanded( + child: Padding( + padding: const EdgeInsets.only(bottom: 8), + child: IntrinsicHeight( + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Expanded( + flex: 1, + child: c.isLoading.value + ? SkeletonParagraph( + style: SkeletonParagraphStyle( + lines: 3, + padding: const EdgeInsets.symmetric( + vertical: 4, horizontal: 0), + lineStyle: SkeletonLineStyle( + randomLength: true, + height: Styles.pageCardDescription.fontSize! * + textScale), + ), + ) + : Text(c.pageInfo.value?.description ?? "没有简介", + overflow: TextOverflow.fade, + style: Styles.pageCardDescription), + ), + const SizedBox(width: 10), + Skeleton( + isLoading: c.isLoading.value, + skeleton: const SkeletonAvatar( + style: SkeletonAvatarStyle(width: 114, height: 114), + ), + child: Container(), + ), + ], + ), + ), + ), + ); + } + + Widget _buildCardFooter(BuildContext context) { + return ScaleTapIgnore( + child: Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + // 分类信息 + c.pageInfo.value?.mainCategory != null + ? Chip( + backgroundColor: const Color.fromARGB(1, 238, 238, 238), + label: Text(c.pageInfo.value!.mainCategory!, + style: const TextStyle(color: Colors.black54)), + materialTapTargetSize: MaterialTapTargetSize.shrinkWrap) + : const SizedBox(), + c.pageInfo.value?.mainCategory != null + ? const SizedBox(width: 10) + : const SizedBox(), + // 发布日期 + Skeleton( + isLoading: c.isLoading.value, + skeleton: const SkeletonLine( + style: SkeletonLineStyle(width: 100), + ), + child: Text( + c.pageInfo.value?.updatedTime != null + ? Utils.getFriendDate(c.pageInfo.value!.updatedTime!) + : "", + style: Styles.pageCardDescription), + ), + const Spacer(), + // 收藏键 + Obx( + () => _actionButtonSkeleton( + c.isLoading.value, + LikeButton( + size: PageCardStyles.footerButtonInnerSize, + isLiked: c.isFavorite.value, + onTap: c.handleFavoriteClick, + likeBuilder: (bool isLiked) { + return Icon( + isLiked ? Icons.favorite : Icons.favorite_border, + color: isLiked ? Colors.red : Colors.grey, + size: PageCardStyles.footerButtonInnerSize, + ); + }, + ), + ), + ), + const SizedBox(width: 18), + // 菜单键 + _actionButtonSkeleton( + c.isLoading.value, + SizedBox( + height: PageCardStyles.footerButtonSize, + width: PageCardStyles.footerButtonSize, + child: PullDownButton( + routeTheme: PullDownMenuRouteTheme( + endShadow: BoxShadow( + color: Colors.grey.withOpacity(0.6), + spreadRadius: 1, + blurRadius: 20, + offset: const Offset(0, 2), + ), + ), + itemBuilder: (context) => [ + c.isFavorite.value + ? PullDownMenuItem( + title: '取消收藏', + icon: CupertinoIcons.heart_fill, + onTap: c.handleRemoveFavoriteMenuItemClick, + ) + : PullDownMenuItem( + title: '收藏', + icon: CupertinoIcons.heart, + onTap: c.handleRemoveFavoriteMenuItemClick, + ), + const PullDownMenuDivider(), + PullDownMenuItem( + title: '分享', + icon: CupertinoIcons.share, + onTap: c.handleShareClick, + ), + const PullDownMenuDivider.large(), + /* + PullDownMenuItem( + title: '相似推荐', + onTap: () {}, + icon: CupertinoIcons.ellipsis_circle, + ), + const PullDownMenuDivider.large(), + */ + PullDownMenuItem( + title: '页面详情', + onTap: c.handlePageInfoClick, + icon: CupertinoIcons.info_circle, + ), + ], + position: PullDownMenuPosition.under, + buttonBuilder: (context, showMenu) => IconButton( + onPressed: showMenu, + padding: const EdgeInsets.all(0.0), + splashRadius: PageCardStyles.footerButtonInnerSize - 4, + iconSize: PageCardStyles.footerButtonInnerSize, + icon: const Icon( + Icons.more_horiz, + color: Colors.grey, + ), + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildCard(BuildContext context) { + return Card( + elevation: 4.0, + // 圆角 + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.all(Radius.circular(Styles.isXs ? 0 : 14.0)), + ), + // 抗锯齿 + clipBehavior: Clip.antiAlias, + semanticContainer: false, + child: Padding( + padding: PageCardStyles.cardInnerPadding, + child: SizedBox( + height: PageCardStyles.cardInnerHeight * textScale, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 标题 + _buildCardHeader(context), + // 简介、图片 + _buildCardBody(context), + // Footer + _buildCardFooter(context), + ], + ), + ), + ), + ); + } + + @override + Widget render(BuildContext context) { + textScale = MediaQuery.of(context).textScaleFactor; + + /* + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: Obx( + () => ScaleTap( + enableFeedback: !c.isLoading.value, + onPressed: c.handleCardClick, + child: GetBuilder( + init: c, + builder: (GetxController c) => _buildCard(context), + ), + ), + ), + ); + */ + return Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), + child: ScaleTap( + onPressed: c.handleCardClick, + child: GetBuilder( + init: c, + builder: (GetxController c) => _buildCard(context), + ), + ), + ); + } +} diff --git a/lib/components/recent_page_list.dart b/lib/components/recent_page_list.dart new file mode 100755 index 0000000..7ab2400 --- /dev/null +++ b/lib/components/recent_page_list.dart @@ -0,0 +1,201 @@ +import 'dart:math'; + +import 'package:flutter/cupertino.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/api/mw/list.dart'; +import 'package:isekai_wiki/api/mw/mw_api.dart'; +import 'package:isekai_wiki/api/response/page_info.dart'; +import 'package:isekai_wiki/components/page_card.dart'; +import 'package:isekai_wiki/models/favorite_list.dart'; +import 'package:isekai_wiki/pages/home.dart'; +import 'package:isekai_wiki/extension/map.dart'; + +class RecentPageListController extends GetxController { + Function? _handleReload; + ScrollController? scrollController; + var shouldRefresh = true; + + var pageList = RxList(); + var continueInfo = RxMap(); + var errorList = RxList(); + + var hasNextPage = true.obs; + var isLoading = false.obs; + + RecentPageListController({this.scrollController}); + + @override + void onInit() { + scrollController?.addListener(() { + if (scrollController!.position.atEdge && + scrollController!.position.pixels != 0) { + // 滚动到底部 + if (hasNextPage.value && !isLoading.value) { + loadNextPages(); + } + } + }); + + super.onInit(); + + loadNextPages(); + + var homeController = Get.find(); + homeController.onRefresh = refreshPages; + } + + @override + void dispose() { + var homeController = Get.find(); + homeController.onRefresh = refreshPages; + + super.dispose(); + } + + Future refreshPages() async { + continueInfo.clear(); + errorList.clear(); + hasNextPage.value = true; + shouldRefresh = true; + + await loadNextPages(); + } + + Future loadNextPages() async { + // 如果没有下一页,则阻止加载 + if (!hasNextPage.value) return; + + isLoading.value = true; + + var rcListRes = await MWApiList.getMixedRecentChanges( + limit: 10, continueInfo: continueInfo.isNotEmpty ? continueInfo : null); + if (!rcListRes.ok) { + // 发生错误,展示错误列表 + errorList.value = rcListRes.errorList ?? []; + isLoading.value = false; + hasNextPage.value = false; + if (shouldRefresh) { + pageList.clear(); + } + return; + } + + var pageIds = rcListRes.data!.map((rcInfo) => rcInfo.pageid).toList(); + var pageListRes = + await MWApiList.getPageInfoList(pageids: pageIds, extractChars: 515); + if (!pageListRes.ok) { + // 发生错误,展示错误列表 + errorList.value = pageListRes.errorList ?? []; + isLoading.value = false; + hasNextPage.value = false; + if (shouldRefresh) { + pageList.clear(); + } + return; + } + + // 加载完成,设置信息 + if (shouldRefresh) { + // 初次加载,替换全部数据 + pageList.value = pageListRes.data!; + shouldRefresh = false; + } else { + pageList.addAll(pageListRes.data!); + } + hasNextPage.value = rcListRes.continueInfo != null; + continueInfo.value = rcListRes.continueInfo ?? {}; + isLoading.value = false; + } + + Future reload() async { + if (_handleReload != null) { + await _handleReload!(); + } + } + + void setReloadHandler(Function? reloadHandler) { + _handleReload = reloadHandler; + } +} + +class RecentPageList extends StatelessWidget { + final ScrollController? scrollController; + + const RecentPageList({ + super.key, + this.scrollController, + }); + + Widget _buildSkeletonList() { + return Column( + key: key, + children: [ + for (var i = 0; i < 6; i++) PageCard(key: ValueKey(i), isLoading: true), + ], + ); + } + + Widget _buildPageCard(int index, PageInfo pageInfo, + RecentPageListController c, FavoriteListController fc) { + return PageCard( + key: ValueKey(index), + pageInfo: c.pageList[index], + isFavorite: fc.isFavorite(c.pageList[index]), + onSetFavorite: fc.setFavorite, + ); + } + + SliverChildBuilderDelegate _buildPageListDelegate() { + var c = Get.find(); + var fc = Get.find(); + + return SliverChildBuilderDelegate( + childCount: c.pageList.length + 1, + (context, index) { + if (index == 0) { + // 第一页数据,直接加载 + return Obx(() { + if (c.pageList.isEmpty) { + return _buildSkeletonList(); + } else { + return _buildPageCard(index, c.pageList[index], c, fc); + } + }); + } + + // 后续页数据 + if (index < c.pageList.length) { + return _buildPageCard(index, c.pageList[index], c, fc); + } else if (index == c.pageList.length) { + // 显示加载动画 + return Padding( + padding: const EdgeInsets.symmetric(vertical: 12), + child: Center( + child: Obx( + () => c.isLoading.value + ? const CupertinoActivityIndicator( + radius: 14, + ) + : const SizedBox( + width: 28, + height: 28, + ), + ), + ), + ); + } + + return null; + }, + ); + } + + @override + Widget build(BuildContext context) { + Get.put(RecentPageListController(scrollController: scrollController)); + + return Obx(() => SliverList( + delegate: _buildPageListDelegate(), + )); + } +} diff --git a/lib/components/state_test.dart b/lib/components/state_test.dart new file mode 100644 index 0000000..e112198 --- /dev/null +++ b/lib/components/state_test.dart @@ -0,0 +1,61 @@ +import 'package:flutter/cupertino.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/reactive/reactive.dart'; + +class StateTestController extends GetxController { + var count = 0.obs; + + @override + void onInit() { + debugPrint("StateTestController onInit"); + super.onInit(); + } + + void updateState({required int count}) { + debugPrint("StateTestController updateState"); + this.count.value = count; + } +} + +class StateTest extends StatefulWidget { + final VoidCallback? onPressed; + final int count; + + const StateTest({super.key, this.onPressed, required this.count}); + + @override + State createState() { + return StateTestState(); + } +} + +class StateTestState extends ReactiveState { + StateTestController c = StateTestController(); + + @override + void initState() { + super.initState(); + Get.put(c); + } + + @override + void receiveProps() { + c.updateState(count: widget.count); + } + + @override + Widget render(BuildContext context) { + return Column(children: [ + Center( + child: Obx( + () => Text(c.count.value.toString()), + ), + ), + CupertinoButton.filled( + child: const Text("增加"), + onPressed: () { + widget.onPressed?.call(); + }), + ]); + } +} diff --git a/lib/components/texts.dart b/lib/components/texts.dart new file mode 100755 index 0000000..f43431e --- /dev/null +++ b/lib/components/texts.dart @@ -0,0 +1,35 @@ +import 'package:flutter/cupertino.dart'; +import 'package:isekai_wiki/styles.dart'; + +class IsekaiPageLargeTitle extends StatelessWidget { + final String text; + + const IsekaiPageLargeTitle(this.text, { super.key }); + + @override + Widget build(BuildContext context) { + return Text(text, + style: const TextStyle( + color: Styles.themeNavTitleColor, + fontWeight: FontWeight.normal + ), + ); + } +} + +class IsekaiPageNavTitle extends StatelessWidget { + final String text; + + const IsekaiPageNavTitle(this.text, { super.key }); + + @override + Widget build(BuildContext context) { + return Text(text, + style: const TextStyle( + color: Styles.themeNavTitleColor, + fontWeight: FontWeight.normal, + fontSize: Styles.navTitleFontSize + ), + ); + } +} \ No newline at end of file diff --git a/lib/components/utils.dart b/lib/components/utils.dart new file mode 100755 index 0000000..891e7af --- /dev/null +++ b/lib/components/utils.dart @@ -0,0 +1,14 @@ +class Utils { + static String getFriendDate(DateTime time) { + var currentTime = DateTime.now(); + var timeDelta = currentTime.millisecondsSinceEpoch - time.millisecondsSinceEpoch; + if (timeDelta <= 86400) { + return "刚刚更新"; + } + String timeStr = "${time.month}月${time.day}日"; + if (time.year != currentTime.year) { + timeStr = "${time.year}年$timeStr"; + } + return timeStr; + } +} diff --git a/lib/extension/extension.dart b/lib/extension/extension.dart new file mode 100644 index 0000000..8df98f8 --- /dev/null +++ b/lib/extension/extension.dart @@ -0,0 +1,3 @@ +import './string.dart'; +import './list.dart'; +import './map.dart'; diff --git a/lib/extension/list.dart b/lib/extension/list.dart new file mode 100644 index 0000000..fcdf050 --- /dev/null +++ b/lib/extension/list.dart @@ -0,0 +1,47 @@ +import 'package:get/get.dart'; + +extension ListExtension on List { + bool addOrSet(int index, T value) { + if (length == index) { + add(value); + return true; + } else if (length > index) { + this[index] = value; + return true; + } + return false; + } + + T getWithSetCallback(int index, T Function() callback) { + if (length > index) { + return this[index]; + } else { + var data = callback(); + addOrSet(index, data); + return data; + } + } +} + +extension RxListExtension on RxList { + bool addOrSet(int index, T value) { + if (length == index) { + add(value); + return true; + } else if (length > index) { + this[index] = value; + return true; + } + return false; + } + + T getWithSetCallback(int index, T Function() callback) { + if (length > index) { + return this[index]; + } else { + var data = callback(); + addOrSet(index, data); + return data; + } + } +} diff --git a/lib/extension/map.dart b/lib/extension/map.dart new file mode 100644 index 0000000..101beab --- /dev/null +++ b/lib/extension/map.dart @@ -0,0 +1,25 @@ +import 'package:get/get.dart'; + +extension MapExtension on Map { + T getWithSetCallback(K key, T Function() callback) { + if (containsKey(key)) { + return this[key]!; + } else { + var data = callback(); + this[key] = data; + return data; + } + } +} + +extension RxMapExtension on RxMap { + T getWithSetCallback(K key, T Function() callback) { + if (containsKey(key)) { + return this[key]!; + } else { + var data = callback(); + this[key] = data; + return data; + } + } +} diff --git a/lib/extension/string.dart b/lib/extension/string.dart new file mode 100644 index 0000000..9d96f2f --- /dev/null +++ b/lib/extension/string.dart @@ -0,0 +1,9 @@ +extension StringExtension on String { + String capitalize() { + if (length > 1) { + return toUpperCase(); + } else { + return this[0].toUpperCase() + substring(1); + } + } +} diff --git a/lib/global.dart b/lib/global.dart new file mode 100755 index 0000000..174d4ef --- /dev/null +++ b/lib/global.dart @@ -0,0 +1,14 @@ +import 'package:package_info_plus/package_info_plus.dart'; + +typedef VoidFutureCallback = Future Function(); +typedef BoolFutureCallback = Future Function(); + +class Global { + static String isekaiWikiHomeUrl = "https://www.isekai.cn/"; + + static PackageInfo? packageInfo; + + static String wikiLang = "zh-cn"; + + static String? webOrigin; +} diff --git a/lib/main.dart b/lib/main.dart new file mode 100755 index 0000000..d72b6d5 --- /dev/null +++ b/lib/main.dart @@ -0,0 +1,55 @@ +import 'dart:io'; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_displaymode/flutter_displaymode.dart'; +import 'package:isekai_wiki/global.dart'; +import 'package:package_info_plus/package_info_plus.dart'; + +import 'app.dart'; + +Future init() async { + // 仅允许竖屏 + /*SystemChrome.setPreferredOrientations( + [DeviceOrientation.portraitUp, DeviceOrientation.portraitDown]);*/ + SystemChrome.setSystemUIOverlayStyle( + const SystemUiOverlayStyle(statusBarColor: Colors.transparent)); + + if (kIsWeb) { + // 设置web origin + Global.webOrigin = Uri.base.origin; + } +} + +Future postInit() async { + if (!kIsWeb) { + // 启用高刷 + try { + if (kDebugMode) { + var modes = await FlutterDisplayMode.supported; + print("Refresh rate list:"); + // ignore: avoid_print + modes.forEach(print); + print("Preferred refresh rate:"); + print(await FlutterDisplayMode.preferred); + } + await FlutterDisplayMode.setHighRefreshRate(); + } catch (err) { + if (kDebugMode) { + print("Cannot set to high refresh rate: "); + print(err); + } + } + } + + Global.packageInfo = await PackageInfo.fromPlatform(); +} + +void main() { + init(); + + runApp(const IsekaiWikiApp()); + + postInit(); +} diff --git a/lib/models/favorite_list.dart b/lib/models/favorite_list.dart new file mode 100644 index 0000000..a466861 --- /dev/null +++ b/lib/models/favorite_list.dart @@ -0,0 +1,62 @@ +import 'package:get/get.dart'; +import 'package:isekai_wiki/api/response/page_info.dart'; +import 'package:isekai_wiki/models/user.dart'; +import 'package:isekai_wiki/utils/dialog.dart'; + +class FavoriteListController extends GetxController { + var pageIds = RxList(); + + void updateFromPageList(List list) { + List addList = []; + List removeList = []; + for (var pageInfo in list) { + if (pageInfo.inwatchlist != null) { + if (pageInfo.inwatchlist!) { + addList.add(pageInfo.pageid); + } else { + removeList.add(pageInfo.pageid); + } + } + } + + var newPageIds = + pageIds.where((pageId) => !removeList.contains(pageId)).toList(); + for (var pageId in addList) { + if (!newPageIds.contains(pageId)) { + newPageIds.add(pageId); + } + } + + pageIds.value = newPageIds; + } + + void updateFromWatchList(List list) { + List addList = []; + for (var pageInfo in list) { + addList.add(pageInfo.pageid); + } + + for (var pageId in addList) { + if (!pageIds.contains(pageId)) { + pageIds.add(pageId); + } + } + } + + bool isFavorite(PageInfo pageInfo) { + return pageIds.contains(pageInfo.pageid); + } + + Future setFavorite( + PageInfo pageInfo, bool isFavorite, bool showToast) async { + // 如果未登录,则提示需要登录 + var uc = Get.find(); + if (!uc.isLoggedIn) { + var result = await confirm(Get.overlayContext!, "使用收藏功能需要登录", + title: "提示", positiveText: "登录"); + return false; + } + + return false; + } +} diff --git a/lib/models/history_list.dart b/lib/models/history_list.dart new file mode 100644 index 0000000..13d553e --- /dev/null +++ b/lib/models/history_list.dart @@ -0,0 +1,5 @@ +import 'package:get/get.dart'; + +class HistoryListController extends GetxController { + var pageIds = RxList(); +} diff --git a/lib/models/model.dart b/lib/models/model.dart new file mode 100644 index 0000000..7f17b52 --- /dev/null +++ b/lib/models/model.dart @@ -0,0 +1,14 @@ +import 'package:get/get.dart'; +import 'package:isekai_wiki/models/favorite_list.dart'; +import 'package:isekai_wiki/models/history_list.dart'; +import 'package:isekai_wiki/models/user.dart'; + +class InitialBinding extends Bindings { + @override + void dependencies() { + Get.put(UserController()); + + Get.lazyPut(() => FavoriteListController()); + Get.lazyPut(() => HistoryListController()); + } +} diff --git a/lib/models/user.dart b/lib/models/user.dart new file mode 100644 index 0000000..d8c4603 --- /dev/null +++ b/lib/models/user.dart @@ -0,0 +1,104 @@ +import 'dart:convert'; + +import 'package:flutter/foundation.dart'; +import 'package:get/get.dart'; +import 'package:json_annotation/json_annotation.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +part 'user.g.dart'; + +@JsonSerializable() +class UserInfo { + int userId; + String userName; + String? nickName; + String? avatarUrl; + + UserInfo( + {required this.userId, + required this.userName, + this.nickName, + this.avatarUrl}); + + factory UserInfo.fromJson(Map json) => + _$UserInfoFromJson(json); + + Map toJson() => _$UserInfoToJson(this); +} + +class UserController extends GetxController { + bool isReady = false; + + var userId = 0.obs; + + bool get isLoggedIn { + return userId.value > 0; + } + + var userName = "".obs; + var nickName = "".obs; + var avatarUrl = "".obs; + + String get getDisplayName { + return nickName.isNotEmpty ? nickName.string : userName.string; + } + + Future initialize() async { + if (!isReady) { + await loadFromStorage(); + isReady = true; + + postInit().catchError((err) { + if (kDebugMode) { + print(err); + } + }); + } + } + + Future postInit() async { + await updateProfile(); + } + + /// 更新用户资料,并检测登录状态 + Future updateProfile() async {} + + /// 从本地存储读取 + Future loadFromStorage() async { + try { + final prefs = await SharedPreferences.getInstance(); + var userInfoJson = prefs.getString("userInfo"); + if (userInfoJson == null) return; + + var userInfoObject = jsonDecode(userInfoJson); + if (userInfoObject == null) return; + + var userInfo = UserInfo.fromJson(userInfoObject); + + userId.value = userInfo.userId; + userName.value = userInfo.userName; + nickName.value = userInfo.nickName ?? ""; + avatarUrl.value = userInfo.avatarUrl ?? ""; + } catch (ex) { + if (kDebugMode) { + print(ex); + } + } + } + + /// 保存到本地存储 + Future saveToStorage() async { + final prefs = await SharedPreferences.getInstance(); + + var userInfo = UserInfo( + userId: userId.value, + userName: userName.value, + nickName: nickName.isNotEmpty ? nickName.value : null, + avatarUrl: avatarUrl.isNotEmpty ? avatarUrl.value : null, + ); + + var userInfoJson = jsonEncode(userInfo.toJson()); + + prefs.setString("userInfo", userInfoJson); + } +} diff --git a/lib/models/user.g.dart b/lib/models/user.g.dart new file mode 100644 index 0000000..cf73e13 --- /dev/null +++ b/lib/models/user.g.dart @@ -0,0 +1,21 @@ +// GENERATED CODE - DO NOT MODIFY BY HAND + +part of 'user.dart'; + +// ************************************************************************** +// JsonSerializableGenerator +// ************************************************************************** + +UserInfo _$UserInfoFromJson(Map json) => UserInfo( + userId: json['userId'] as int, + userName: json['userName'] as String, + nickName: json['nickName'] as String?, + avatarUrl: json['avatarUrl'] as String?, + ); + +Map _$UserInfoToJson(UserInfo instance) => { + 'userId': instance.userId, + 'userName': instance.userName, + 'nickName': instance.nickName, + 'avatarUrl': instance.avatarUrl, + }; diff --git a/lib/pages/about.dart b/lib/pages/about.dart new file mode 100755 index 0000000..3f54532 --- /dev/null +++ b/lib/pages/about.dart @@ -0,0 +1,79 @@ +import 'package:cupertino_lists/cupertino_lists.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_web_browser/flutter_web_browser.dart'; +import 'package:get/get.dart'; + +import '../components/dummy_icon.dart'; +import '../components/isekai_nav_bar.dart'; +import '../components/isekai_page_scaffold.dart'; +import '../global.dart'; +import '../styles.dart'; + +class AboutPageController extends GetxController { + Future handleMainPageLinkClick() async { + if (GetPlatform.isAndroid || GetPlatform.isIOS) { + await FlutterWebBrowser.openWebPage( + url: Global.isekaiWikiHomeUrl, + customTabsOptions: const CustomTabsOptions( + defaultColorSchemeParams: CustomTabsColorSchemeParams( + toolbarColor: Colors.black87, + ), + ), + ); + } else {} + } +} + +class AboutPage extends StatelessWidget { + const AboutPage({super.key}); + + @override + Widget build(BuildContext context) { + var c = Get.put(AboutPageController()); + + return IsekaiPageScaffold( + navigationBar: const IsekaiNavigationBar( + middle: Text('关于'), previousPageTitle: "设置"), + child: ListView( + children: [ + const SizedBox(height: 18), + Container( + color: Styles.panelBackgroundColor, + child: SafeArea( + top: false, + bottom: false, + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 16), + child: Column( + children: const [ + Text("异世界百科APP", style: Styles.articleTitle), + SizedBox(height: 18), + Text("使用Flutter构建"), + ], + ), + ), + ), + ), + const SizedBox(height: 18), + CupertinoListSection.insetGrouped( + backgroundColor: Styles.themePageBackgroundColor, + children: [ + CupertinoListTile.notched( + title: const Text('异世界百科', + style: TextStyle(color: Styles.linkColor)), + leading: const DummyIcon( + color: CupertinoColors.systemBlue, + icon: CupertinoIcons.globe, + ), + trailing: const CupertinoListTileChevron(), + onTap: c.handleMainPageLinkClick, + ), + ], + ), + ], + ), + ); + } +} diff --git a/lib/pages/article.dart b/lib/pages/article.dart new file mode 100755 index 0000000..74bdf95 --- /dev/null +++ b/lib/pages/article.dart @@ -0,0 +1,101 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter_html/flutter_html.dart'; +import 'package:isekai_wiki/api/restbase/page.dart'; + +import '../components/isekai_nav_bar.dart'; +import '../components/isekai_page_scaffold.dart'; +import '../styles.dart'; + +class MinimumArticleData { + final String title; + final String? description; + final String? mainCategory; + final DateTime? updateTime; + + MinimumArticleData( + {required this.title, + this.description, + this.mainCategory, + this.updateTime}); +} + +class ArticleCategoryData { + final String name; + final String identity; + + ArticleCategoryData({required this.name, required this.identity}); +} + +class ArticlePage extends StatefulWidget { + final MinimumArticleData? initialArticleData; + final String? targetPage; + + const ArticlePage({super.key, this.targetPage, this.initialArticleData}); + + @override + State createState() => _ArticlePageState(); +} + +class _ArticlePageState extends State { + bool loading = true; + String title = ""; + String description = ""; + String content = ""; + String contentHtml = ""; + List categories = []; + + Future _loadPageContent() async { + if (widget.targetPage != null) { + var resContentHtml = await RestfulPageApi.getPageHtml(widget.targetPage!); + if (resContentHtml != null) { + setState(() { + contentHtml = resContentHtml; + }); + } + } + } + + @override + void initState() { + title = widget.initialArticleData?.title ?? ""; + description = widget.initialArticleData?.description ?? ""; + if (widget.initialArticleData?.mainCategory != null) { + categories.add(widget.initialArticleData!.mainCategory!); + } + super.initState(); + _loadPageContent(); + } + + @override + Widget build(BuildContext context) { + return IsekaiPageScaffold( + navigationBar: IsekaiNavigationBar( + middle: Text(title), + ), + child: ListView( + children: [ + Container( + color: Styles.panelBackgroundColor, + child: SafeArea( + top: false, + bottom: false, + child: Padding( + padding: + const EdgeInsets.symmetric(horizontal: 12, vertical: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + if (contentHtml == "") Text(description), + Html( + data: contentHtml, + ), + ], + ), + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/pages/discover.dart b/lib/pages/discover.dart new file mode 100755 index 0000000..bddf8ac --- /dev/null +++ b/lib/pages/discover.dart @@ -0,0 +1,16 @@ +import 'package:flutter/cupertino.dart'; + +class DiscoverTab extends StatelessWidget { + const DiscoverTab({super.key}); + + @override + Widget build(BuildContext context) { + return const CustomScrollView( + slivers: [ + CupertinoSliverNavigationBar( + largeTitle: Text('发现'), + ), + ], + ); + } +} diff --git a/lib/pages/home.dart b/lib/pages/home.dart new file mode 100755 index 0000000..31af675 --- /dev/null +++ b/lib/pages/home.dart @@ -0,0 +1,271 @@ +import 'dart:async'; +import 'dart:math'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/components/recent_page_list.dart'; +import 'package:isekai_wiki/models/user.dart'; +import 'package:isekai_wiki/pages/tab_page.dart'; +import 'package:web_smooth_scroll/web_smooth_scroll.dart'; + +import '../components/collapsed_tab.dart'; +import '../global.dart'; +import '../styles.dart'; + +enum HomeTabs { newest, followed } + +class HomeController extends GetxController + with GetSingleTickerProviderStateMixin { + var showNavSearchButton = false.obs; + var isScrolling = false.obs; + + StreamController? streamController; + StreamSubscription? _streamSubscription; + + late TabController tabController; + late TabsPageController tabsPageController; + final ScrollController scrollController = ScrollController(); + + VoidFutureCallback? onRefresh; + + @override + void onInit() { + tabController = TabController(length: 2, vsync: this); + + scrollController.addListener(() { + if (scrollController.offset >= 90 && !showNavSearchButton.value) { + showNavSearchButton.value = true; + } else if (scrollController.offset < 90 && showNavSearchButton.value) { + showNavSearchButton.value = false; + } + }); + + tabsPageController = Get.find(); + + tabsPageController.streamController.stream.listen((event) { + if (event == "tap:home") { + handleTapHomeTab(); + } + }); + + super.onInit(); + } + + @override + void dispose() { + _streamSubscription?.cancel(); + + super.dispose(); + } + + Future handleTapHomeTab() async { + if (isScrolling.value) return; + + if (scrollController.offset != 0) { + isScrolling.value = true; + await scrollController.animateTo( + 0, + duration: const Duration(milliseconds: 500), + curve: Curves.fastOutSlowIn, + ); + isScrolling.value = false; + } + } + + Future handleRefresh() async { + if (onRefresh != null) { + await onRefresh!(); + } + } +} + +class HomeTab extends StatelessWidget { + final VoidCallback? onSearchClick; + + const HomeTab({super.key, this.onSearchClick}); + + Widget _buildNotificationIconButton() { + final uc = Get.find(); + + return Obx( + () => AnimatedOpacity( + opacity: uc.isLoggedIn ? 1.0 : 0.0, + duration: const Duration(milliseconds: 100), + child: CupertinoButton( + padding: EdgeInsets.zero, + child: const Icon(CupertinoIcons.search, + size: 26, color: Styles.themeNavTitleColor), + onPressed: () { + onSearchClick?.call(); + }, + ), + ), + ); + } + + Widget _buildSearchIconButton() { + final c = Get.find(); + + return Obx( + () => AnimatedOpacity( + opacity: c.showNavSearchButton.value ? 1.0 : 0.0, + duration: const Duration(milliseconds: 100), + child: CupertinoButton( + padding: EdgeInsets.zero, + child: const Icon(CupertinoIcons.search, + size: 26, color: Styles.themeNavTitleColor), + onPressed: () { + onSearchClick?.call(); + }, + ), + ), + ); + } + + @override + Widget build(BuildContext context) { + final c = Get.put(HomeController()); + + return WebSmoothScroll( + controller: c.scrollController, + child: CustomScrollView( + controller: c.scrollController, + physics: const BouncingScrollPhysics( + parent: AlwaysScrollableScrollPhysics(), + ), + slivers: [ + CupertinoSliverNavigationBar( + leading: _buildNotificationIconButton(), + backgroundColor: Styles.themeMainColor, + brightness: Brightness.dark, + largeTitle: const Text('首页', + style: TextStyle(color: Styles.themeNavTitleColor)), + border: Border.all(style: BorderStyle.none), + trailing: _buildSearchIconButton(), + ), + SliverPersistentHeader( + delegate: _SliverAppBarDelegate( + minHeight: 48, + maxHeight: 48, + child: Container( + decoration: const BoxDecoration( + color: Styles.themeMainColor, + boxShadow: [ + BoxShadow( + color: Styles.themeMainColor, + blurRadius: 0.0, + spreadRadius: 0.0, + offset: Offset(0, -2), + ), + ], + ), + padding: const EdgeInsets.only(bottom: 10, left: 12, right: 12), + child: CupertinoButton( + color: Colors.white, + padding: const EdgeInsets.all(0), + onPressed: () { + onSearchClick?.call(); + }, + child: Wrap( + spacing: 14, + alignment: WrapAlignment.spaceBetween, + children: [ + Container( + padding: const EdgeInsets.all(1), + child: const Icon(CupertinoIcons.search, + color: Colors.black54), + ), + const Text("搜索页面...", + textAlign: TextAlign.center, + style: TextStyle(color: Colors.black54)) + ], + ), + ), + ), + ), + ), + SliverPersistentHeader( + pinned: true, + delegate: _SliverAppBarDelegate( + minHeight: 40.0, + maxHeight: 40.0, + child: Container( + decoration: BoxDecoration(color: Colors.white, boxShadow: [ + BoxShadow( + color: Colors.grey.withOpacity(0.2), + spreadRadius: 2, + blurRadius: 4, + offset: const Offset(0, 2), + ) + ]), + child: Row( + children: [ + SizedBox( + child: TabBar( + isScrollable: true, + controller: c.tabController, + indicatorColor: Styles.themeMainColor, + labelColor: Styles.themeMainColor, + unselectedLabelColor: Colors.black45, + tabs: const [ + CollapsedTabText('最新'), + CollapsedTabText('关注') + ], + onTap: (int selected) {}, + ), + ), + const Expanded(child: Text('')), + ], + ), + ), + ), + ), + CupertinoSliverRefreshControl( + onRefresh: c.handleRefresh, + ), + SliverSafeArea( + top: false, + bottom: false, + minimum: const EdgeInsets.only(top: 12, bottom: 12), + sliver: RecentPageList( + key: const Key("rpl"), + scrollController: c.scrollController, + ), + ), + ], + ), + ); + } +} + +class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate { + _SliverAppBarDelegate({ + required this.minHeight, + required this.maxHeight, + required this.child, + }); + + final double minHeight; + final double maxHeight; + final Widget child; + + @override + double get minExtent => minHeight; + + @override + double get maxExtent => max(maxHeight, minHeight); + + @override + Widget build( + BuildContext context, double shrinkOffset, bool overlapsContent) { + return SizedBox.expand(child: child); + } + + @override + bool shouldRebuild(_SliverAppBarDelegate oldDelegate) { + return maxHeight != oldDelegate.maxHeight || + minHeight != oldDelegate.minHeight || + child != oldDelegate.child; + } +} diff --git a/lib/pages/search.dart b/lib/pages/search.dart new file mode 100755 index 0000000..a67f9c5 --- /dev/null +++ b/lib/pages/search.dart @@ -0,0 +1,55 @@ +import 'package:flutter/cupertino.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/components/state_test.dart'; +import 'package:isekai_wiki/styles.dart'; + +class SearchController extends GetxController { + var count1 = 0.obs; + var count2 = 0.obs; +} + +class SearchTab extends StatelessWidget { + const SearchTab({super.key}); + + @override + Widget build(BuildContext context) { + var c = Get.put(SearchController()); + + return CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar( + middle: Text('搜索'), + ), + child: ListView( + children: [ + Container( + color: Styles.panelBackgroundColor, + child: SafeArea( + top: false, + bottom: false, + child: Column( + children: [ + Obx( + () => StateTest( + count: c.count1.value, + onPressed: (() { + c.count1.value++; + }), + ), + ), + Obx( + () => StateTest( + count: c.count2.value, + onPressed: (() { + c.count2.value++; + }), + ), + ), + ], + ), + ), + ), + ], + ), + ); + } +} diff --git a/lib/pages/settings.dart b/lib/pages/settings.dart new file mode 100755 index 0000000..725e199 --- /dev/null +++ b/lib/pages/settings.dart @@ -0,0 +1,140 @@ +import 'package:cupertino_lists/cupertino_lists.dart'; +import 'package:flutter/cupertino.dart'; +import 'package:isekai_wiki/pages/about.dart'; +import 'package:isekai_wiki/styles.dart'; + +import '../components/dummy_icon.dart'; +import '../components/follow_scale.dart'; + +class SettingsTab extends StatefulWidget { + const SettingsTab({super.key}); + + @override + State createState() { + return _SettingsTabState(); + } +} + +class _SettingsTabState extends State { + Widget _buildUserSection() { + return FollowTextScale( + child: CupertinoListSection.insetGrouped( + backgroundColor: Styles.themePageBackgroundColor, + children: const [ + CupertinoListTile.notched( + title: Text('登录/注册', style: Styles.listTileLargeTitle), + leading: DummyIcon( + color: CupertinoColors.systemGrey, + icon: CupertinoIcons.person_fill, + size: 56, + rounded: true, + ), + leadingSize: 80, + leadingToTitle: 4, + trailing: CupertinoListTileChevron(), + ), + ], + )); + } + + Widget _buildArticleListsSection() { + return FollowTextScale( + child: CupertinoListSection.insetGrouped( + backgroundColor: Styles.themePageBackgroundColor, + children: [ + CupertinoListTile.notched( + title: const Text('收藏'), + leading: const DummyIcon( + color: CupertinoColors.systemYellow, + icon: CupertinoIcons.star_fill, + ), + trailing: const CupertinoListTileChevron(), + onTap: () {}, + ), + CupertinoListTile.notched( + title: const Text('阅读历史'), + leading: const DummyIcon( + color: CupertinoColors.systemBlue, + icon: CupertinoIcons.time_solid, + ), + trailing: const CupertinoListTileChevron(), + onTap: () {}, + ), + CupertinoListTile.notched( + title: const Text('贡献'), + leading: const DummyIcon( + color: CupertinoColors.systemOrange, + icon: CupertinoIcons.create, + ), + trailing: const CupertinoListTileChevron(), + onTap: () {}, + ), + ], + )); + } + + Widget _buildSettingsSection() { + return FollowTextScale( + child: CupertinoListSection.insetGrouped( + backgroundColor: Styles.themePageBackgroundColor, + children: [ + CupertinoListTile.notched( + title: const Text('设置'), + leading: const DummyIcon( + color: CupertinoColors.systemGrey, + icon: CupertinoIcons.settings, + ), + trailing: const CupertinoListTileChevron(), + onTap: () {}, + ), + CupertinoListTile.notched( + title: const Text('关于'), + leading: const DummyIcon( + color: CupertinoColors.systemBlue, + icon: CupertinoIcons.info, + ), + trailing: const CupertinoListTileChevron(), + onTap: () async { + await Navigator.of(context, rootNavigator: true).push(CupertinoPageRoute(builder: (_) => AboutPage())); + }, + ), + ], + )); + } + + SliverChildBuilderDelegate _buildSliverChildBuilderDelegate() { + return SliverChildBuilderDelegate( + (context, index) { + switch (index) { + case 0: + return _buildUserSection(); + case 1: + return _buildArticleListsSection(); + case 2: + return _buildSettingsSection(); + default: + // Do nothing. For now. + } + return null; + }, + ); + } + + @override + Widget build(BuildContext context) { + return CustomScrollView( + slivers: [ + const CupertinoSliverNavigationBar( + largeTitle: Text('设置'), + ), + SliverSafeArea( + top: false, + minimum: const EdgeInsets.only(top: 4), + sliver: SliverList( + delegate: _buildSliverChildBuilderDelegate(), + ), + ) + ], + ); + } +} diff --git a/lib/pages/tab_page.dart b/lib/pages/tab_page.dart new file mode 100755 index 0000000..50d7361 --- /dev/null +++ b/lib/pages/tab_page.dart @@ -0,0 +1,124 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:get/get.dart'; +import 'package:isekai_wiki/pages/discover.dart'; +import 'package:isekai_wiki/pages/home.dart'; +import 'package:isekai_wiki/pages/search.dart'; +import 'package:isekai_wiki/pages/settings.dart'; +import 'package:isekai_wiki/styles.dart'; + +class TabsPageController extends GetxController { + final tabController = CupertinoTabController(); + final streamController = StreamController.broadcast(); + var tabIndex = 0.obs; + + void emit(String eventName) { + streamController.add(eventName); + } + + Future handleWillPop() async { + if (Navigator.canPop(Get.context!)) { + Get.back(); + return false; + } else if (tabController.index != 0) { + tabController.index = 0; + return false; + } + return true; + } + + void handleTapTab(int tabIndex) { + if (tabIndex != this.tabIndex.value) { + this.tabIndex.value = tabIndex; + return; + } + + switch (tabIndex) { + case 0: + emit("tap:home"); + break; + } + } + + void toSearchPage() { + tabController.index = 2; + } +} + +class IsekaiWikiTabsPage extends StatelessWidget { + const IsekaiWikiTabsPage({super.key}); + + @override + Widget build(BuildContext context) { + var c = Get.put(TabsPageController()); + + return WillPopScope( + onWillPop: c.handleWillPop, + child: CupertinoTabScaffold( + controller: c.tabController, + tabBar: CupertinoTabBar( + backgroundColor: Styles.themeBottomColor, + activeColor: Styles.themeMainColor, + border: const Border( + top: BorderSide(color: CupertinoColors.systemGrey5, width: 2)), + height: 56, + onTap: c.handleTapTab, + items: const [ + BottomNavigationBarItem( + icon: Icon(CupertinoIcons.house), + label: '首页', + ), + BottomNavigationBarItem( + icon: Icon(CupertinoIcons.lightbulb), + label: '发现', + ), + BottomNavigationBarItem( + icon: Icon(CupertinoIcons.search), + label: '搜索', + ), + BottomNavigationBarItem( + icon: Icon(CupertinoIcons.settings), + label: '设置', + ), + ], + ), + tabBuilder: (context, index) { + switch (index) { + case 0: + return CupertinoTabView(builder: (context) { + return CupertinoPageScaffold( + child: HomeTab( + onSearchClick: c.toSearchPage, + ), + ); + }); + case 1: + return CupertinoTabView(builder: (context) { + return const CupertinoPageScaffold( + child: DiscoverTab(), + ); + }); + case 2: + return CupertinoTabView(builder: (context) { + return const CupertinoPageScaffold( + child: SearchTab(), + ); + }); + case 3: + return CupertinoTabView(builder: (context) { + return const CupertinoPageScaffold( + child: SettingsTab(), + ); + }); + } + return CupertinoTabView(builder: (context) { + return const CupertinoPageScaffold( + child: HomeTab(), + ); + }); + }, + ), + ); + } +} diff --git a/lib/reactive/reactive.dart b/lib/reactive/reactive.dart new file mode 100644 index 0000000..03ba0d2 --- /dev/null +++ b/lib/reactive/reactive.dart @@ -0,0 +1,54 @@ +import 'package:flutter/widgets.dart'; +import 'package:get/get.dart'; + +class ReactiveController extends GetxController { + Widget? _cachedView; + + Widget render(Widget Function() build) { + if (_cachedView != null) { + return _cachedView!; + } else { + _cachedView = build(); + return _cachedView!; + } + } +} + +abstract class ReactiveState extends State { + Widget? _cachedView; + + @override + void initState() { + super.initState(); + receiveProps(); + } + + @override + void didUpdateWidget(T oldWidget) { + super.didUpdateWidget(oldWidget); + receiveProps(); + } + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + // 此处必须重建组件,防止更新字体或者夜间模式切换时组件不刷新 + _cachedView = null; + } + + void receiveProps() {} + + Widget render(BuildContext context) { + throw Exception("Render is not impleted"); + } + + @override + Widget build(BuildContext context) { + if (_cachedView != null) { + return _cachedView!; + } else { + _cachedView = render(context); + return _cachedView!; + } + } +} diff --git a/lib/styles.dart b/lib/styles.dart new file mode 100755 index 0000000..d1345c8 --- /dev/null +++ b/lib/styles.dart @@ -0,0 +1,63 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +abstract class Styles { + static double textScaleFactor = 1; + + static bool isXs = false; + + static const CupertinoTextThemeData defaultTextTheme = + CupertinoTextThemeData(); + + static const TextStyle navLargeTitleTextStyle = TextStyle( + fontWeight: FontWeight.normal, + fontSize: 32, + color: CupertinoColors.label, + inherit: false); + + static const TextStyle productRowItemName = TextStyle( + color: Color.fromRGBO(0, 0, 0, 0.8), + fontSize: 18, + fontStyle: FontStyle.normal, + fontWeight: FontWeight.normal, + ); + + static const TextStyle productRowTotal = TextStyle( + color: Color.fromRGBO(0, 0, 0, 0.8), + fontSize: 20, + fontStyle: FontStyle.normal, + fontWeight: FontWeight.bold, + ); + + static const TextStyle pageCardTitle = TextStyle( + fontSize: 20, + fontStyle: FontStyle.normal, + fontWeight: FontWeight.bold, + ); + + static const TextStyle articleTitle = TextStyle( + fontSize: 28, + fontStyle: FontStyle.normal, + fontWeight: FontWeight.bold, + ); + + static const TextStyle pageCardDescription = TextStyle( + color: Colors.black54, + fontSize: 14, + fontStyle: FontStyle.normal, + fontWeight: FontWeight.normal, + ); + + static const TextStyle listTileLargeTitle = TextStyle(fontSize: 18); + + static const Color themeMainColor = Color.fromRGBO(65, 147, 135, 1); + static const Color themeNavTitleColor = Color.fromRGBO(255, 255, 255, 1); + static const Color themeBottomColor = Color.fromRGBO(255, 255, 255, 1); + static const Color themePageBackgroundColor = + Color.fromRGBO(240, 240, 240, 1); + static const Color themeNavSegmentTextColor = Color.fromRGBO(12, 12, 12, 1); + static const Color panelBackgroundColor = Color.fromRGBO(255, 255, 255, 1); + static const Color linkColor = CupertinoColors.link; + static const double largeTitleFontSize = 32; + static const double navTitleFontSize = 18; +} diff --git a/lib/utils/api_utils.dart b/lib/utils/api_utils.dart new file mode 100644 index 0000000..aa8dd95 --- /dev/null +++ b/lib/utils/api_utils.dart @@ -0,0 +1,24 @@ +import 'dart:io'; +import 'package:flutter/foundation.dart'; +import 'package:isekai_wiki/global.dart'; +import 'package:package_info_plus/package_info_plus.dart'; + +import '../extension/string.dart'; + +class ApiUtils { + static Future getUserAgent() async { + if (kIsWeb) { + // Web版防止出错 + return ""; + } + + String osName = Platform.operatingSystem.capitalize(); + String osVersion = Platform.operatingSystemVersion; + + Global.packageInfo ??= await PackageInfo.fromPlatform(); + + String appVersion = Global.packageInfo!.version; + + return "IsekaiWikiApp/$appVersion ($osName $osVersion)"; + } +} diff --git a/lib/utils/dialog.dart b/lib/utils/dialog.dart new file mode 100644 index 0000000..56ff799 --- /dev/null +++ b/lib/utils/dialog.dart @@ -0,0 +1,61 @@ +import 'dart:async'; +import 'package:flutter/cupertino.dart'; + +Future alert(BuildContext context, String content, {String? title}) { + var c = Completer(); + + showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: title != null ? Text(title) : null, + content: Text(content), + actions: [ + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () { + c.complete(); + Navigator.of(context).pop(); + }, + child: const Text("好"), + ), + ], + ), + ); + + return c.future; +} + +Future confirm(BuildContext context, String content, + {String? title, String? positiveText, String? negativeText}) { + var c = Completer(); + + positiveText ??= "好"; + negativeText ??= "取消"; + + showCupertinoDialog( + context: context, + builder: (context) => CupertinoAlertDialog( + title: title != null ? Text(title) : null, + content: Text(content), + actions: [ + CupertinoDialogAction( + onPressed: () { + Navigator.of(context).pop(); + c.complete(false); + }, + child: Text(negativeText!), + ), + CupertinoDialogAction( + isDefaultAction: true, + onPressed: () { + Navigator.of(context).pop(); + c.complete(true); + }, + child: Text(positiveText!), + ), + ], + ), + ); + + return c.future; +} diff --git a/macos/.gitignore b/macos/.gitignore new file mode 100755 index 0000000..746adbb --- /dev/null +++ b/macos/.gitignore @@ -0,0 +1,7 @@ +# Flutter-related +**/Flutter/ephemeral/ +**/Pods/ + +# Xcode-related +**/dgph +**/xcuserdata/ diff --git a/macos/Flutter/Flutter-Debug.xcconfig b/macos/Flutter/Flutter-Debug.xcconfig new file mode 100755 index 0000000..4b81f9b --- /dev/null +++ b/macos/Flutter/Flutter-Debug.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/Flutter-Release.xcconfig b/macos/Flutter/Flutter-Release.xcconfig new file mode 100755 index 0000000..5caa9d1 --- /dev/null +++ b/macos/Flutter/Flutter-Release.xcconfig @@ -0,0 +1,2 @@ +#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig" +#include "ephemeral/Flutter-Generated.xcconfig" diff --git a/macos/Flutter/GeneratedPluginRegistrant.swift b/macos/Flutter/GeneratedPluginRegistrant.swift new file mode 100755 index 0000000..3549e45 --- /dev/null +++ b/macos/Flutter/GeneratedPluginRegistrant.swift @@ -0,0 +1,16 @@ +// +// Generated file. Do not edit. +// + +import FlutterMacOS +import Foundation + +import package_info_plus +import shared_preferences_macos +import wakelock_macos + +func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { + FLTPackageInfoPlusPlugin.register(with: registry.registrar(forPlugin: "FLTPackageInfoPlusPlugin")) + SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin")) + WakelockMacosPlugin.register(with: registry.registrar(forPlugin: "WakelockMacosPlugin")) +} diff --git a/macos/Podfile b/macos/Podfile new file mode 100755 index 0000000..dade8df --- /dev/null +++ b/macos/Podfile @@ -0,0 +1,40 @@ +platform :osx, '10.11' + +# CocoaPods analytics sends network stats synchronously affecting flutter build latency. +ENV['COCOAPODS_DISABLE_STATS'] = 'true' + +project 'Runner', { + 'Debug' => :debug, + 'Profile' => :release, + 'Release' => :release, +} + +def flutter_root + generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'ephemeral', 'Flutter-Generated.xcconfig'), __FILE__) + unless File.exist?(generated_xcode_build_settings_path) + raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure \"flutter pub get\" is executed first" + end + + File.foreach(generated_xcode_build_settings_path) do |line| + matches = line.match(/FLUTTER_ROOT\=(.*)/) + return matches[1].strip if matches + end + raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Flutter-Generated.xcconfig, then run \"flutter pub get\"" +end + +require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root) + +flutter_macos_podfile_setup + +target 'Runner' do + use_frameworks! + use_modular_headers! + + flutter_install_all_macos_pods File.dirname(File.realpath(__FILE__)) +end + +post_install do |installer| + installer.pods_project.targets.each do |target| + flutter_additional_macos_build_settings(target) + end +end diff --git a/macos/Podfile.lock b/macos/Podfile.lock new file mode 100755 index 0000000..44051c2 --- /dev/null +++ b/macos/Podfile.lock @@ -0,0 +1,22 @@ +PODS: + - FlutterMacOS (1.0.0) + - wakelock_macos (0.0.1): + - FlutterMacOS + +DEPENDENCIES: + - FlutterMacOS (from `Flutter/ephemeral`) + - wakelock_macos (from `Flutter/ephemeral/.symlinks/plugins/wakelock_macos/macos`) + +EXTERNAL SOURCES: + FlutterMacOS: + :path: Flutter/ephemeral + wakelock_macos: + :path: Flutter/ephemeral/.symlinks/plugins/wakelock_macos/macos + +SPEC CHECKSUMS: + FlutterMacOS: ae6af50a8ea7d6103d888583d46bd8328a7e9811 + wakelock_macos: bc3f2a9bd8d2e6c89fee1e1822e7ddac3bd004a9 + +PODFILE CHECKSUM: 6eac6b3292e5142cfc23bdeb71848a40ec51c14c + +COCOAPODS: 1.11.3 diff --git a/macos/Runner.xcodeproj/project.pbxproj b/macos/Runner.xcodeproj/project.pbxproj new file mode 100644 index 0000000..c750713 --- /dev/null +++ b/macos/Runner.xcodeproj/project.pbxproj @@ -0,0 +1,632 @@ +// !$*UTF8*$! +{ + archiveVersion = 1; + classes = { + }; + objectVersion = 51; + objects = { + +/* Begin PBXAggregateTarget section */ + 33CC111A2044C6BA0003C045 /* Flutter Assemble */ = { + isa = PBXAggregateTarget; + buildConfigurationList = 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */; + buildPhases = ( + 33CC111E2044C6BF0003C045 /* ShellScript */, + ); + dependencies = ( + ); + name = "Flutter Assemble"; + productName = FLX; + }; +/* End PBXAggregateTarget section */ + +/* Begin PBXBuildFile section */ + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */ = {isa = PBXBuildFile; fileRef = 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */; }; + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC10F02044A3C60003C045 /* AppDelegate.swift */; }; + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F22044A3C60003C045 /* Assets.xcassets */; }; + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */ = {isa = PBXBuildFile; fileRef = 33CC10F42044A3C60003C045 /* MainMenu.xib */; }; + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */; }; + 953337C35CE22ED36B5FFB8C /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7B4B572955B31AF77E32F668 /* Pods_Runner.framework */; }; +/* End PBXBuildFile section */ + +/* Begin PBXContainerItemProxy section */ + 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */ = { + isa = PBXContainerItemProxy; + containerPortal = 33CC10E52044A3C60003C045 /* Project object */; + proxyType = 1; + remoteGlobalIDString = 33CC111A2044C6BA0003C045; + remoteInfo = FLX; + }; +/* End PBXContainerItemProxy section */ + +/* Begin PBXCopyFilesBuildPhase section */ + 33CC110E2044A8840003C045 /* Bundle Framework */ = { + isa = PBXCopyFilesBuildPhase; + buildActionMask = 2147483647; + dstPath = ""; + dstSubfolderSpec = 10; + files = ( + ); + name = "Bundle Framework"; + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXCopyFilesBuildPhase section */ + +/* Begin PBXFileReference section */ + 05DEFE675E467AFD44DF1FBB /* Pods-Runner.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.release.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"; sourceTree = ""; }; + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Warnings.xcconfig; sourceTree = ""; }; + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = GeneratedPluginRegistrant.swift; sourceTree = ""; }; + 33CC10ED2044A3C60003C045 /* isekai_wiki_app.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = isekai_wiki_app.app; sourceTree = BUILT_PRODUCTS_DIR; }; + 33CC10F02044A3C60003C045 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = ""; }; + 33CC10F22044A3C60003C045 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Assets.xcassets; path = Runner/Assets.xcassets; sourceTree = ""; }; + 33CC10F52044A3C60003C045 /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = Base; path = Base.lproj/MainMenu.xib; sourceTree = ""; }; + 33CC10F72044A3C60003C045 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; name = Info.plist; path = Runner/Info.plist; sourceTree = ""; }; + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MainFlutterWindow.swift; sourceTree = ""; }; + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Debug.xcconfig"; sourceTree = ""; }; + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = "Flutter-Release.xcconfig"; sourceTree = ""; }; + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; name = "Flutter-Generated.xcconfig"; path = "ephemeral/Flutter-Generated.xcconfig"; sourceTree = ""; }; + 33E51913231747F40026EE4D /* DebugProfile.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = DebugProfile.entitlements; sourceTree = ""; }; + 33E51914231749380026EE4D /* Release.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Release.entitlements; sourceTree = ""; }; + 33E5194F232828860026EE4D /* AppInfo.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = AppInfo.xcconfig; sourceTree = ""; }; + 6BAC23DD190F3E4593546FEA /* Pods-Runner.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.debug.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"; sourceTree = ""; }; + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; }; + 7B4B572955B31AF77E32F668 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; }; + 9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; }; + A8638F60382362AF2685DCE7 /* Pods-Runner.profile.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Runner.profile.xcconfig"; path = "Target Support Files/Pods-Runner/Pods-Runner.profile.xcconfig"; sourceTree = ""; }; +/* End PBXFileReference section */ + +/* Begin PBXFrameworksBuildPhase section */ + 33CC10EA2044A3C60003C045 /* Frameworks */ = { + isa = PBXFrameworksBuildPhase; + buildActionMask = 2147483647; + files = ( + 953337C35CE22ED36B5FFB8C /* Pods_Runner.framework in Frameworks */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXFrameworksBuildPhase section */ + +/* Begin PBXGroup section */ + 2A3583BBFCBF752763A0E2AB /* Pods */ = { + isa = PBXGroup; + children = ( + 6BAC23DD190F3E4593546FEA /* Pods-Runner.debug.xcconfig */, + 05DEFE675E467AFD44DF1FBB /* Pods-Runner.release.xcconfig */, + A8638F60382362AF2685DCE7 /* Pods-Runner.profile.xcconfig */, + ); + name = Pods; + path = Pods; + sourceTree = ""; + }; + 33BA886A226E78AF003329D5 /* Configs */ = { + isa = PBXGroup; + children = ( + 33E5194F232828860026EE4D /* AppInfo.xcconfig */, + 9740EEB21CF90195004384FC /* Debug.xcconfig */, + 7AFA3C8E1D35360C0083082E /* Release.xcconfig */, + 333000ED22D3DE5D00554162 /* Warnings.xcconfig */, + ); + path = Configs; + sourceTree = ""; + }; + 33CC10E42044A3C60003C045 = { + isa = PBXGroup; + children = ( + 33FAB671232836740065AC1E /* Runner */, + 33CEB47122A05771004F2AC0 /* Flutter */, + 33CC10EE2044A3C60003C045 /* Products */, + D73912EC22F37F3D000D13A0 /* Frameworks */, + 2A3583BBFCBF752763A0E2AB /* Pods */, + ); + sourceTree = ""; + }; + 33CC10EE2044A3C60003C045 /* Products */ = { + isa = PBXGroup; + children = ( + 33CC10ED2044A3C60003C045 /* isekai_wiki_app.app */, + ); + name = Products; + sourceTree = ""; + }; + 33CC11242044D66E0003C045 /* Resources */ = { + isa = PBXGroup; + children = ( + 33CC10F22044A3C60003C045 /* Assets.xcassets */, + 33CC10F42044A3C60003C045 /* MainMenu.xib */, + 33CC10F72044A3C60003C045 /* Info.plist */, + ); + name = Resources; + path = ..; + sourceTree = ""; + }; + 33CEB47122A05771004F2AC0 /* Flutter */ = { + isa = PBXGroup; + children = ( + 335BBD1A22A9A15E00E9071D /* GeneratedPluginRegistrant.swift */, + 33CEB47222A05771004F2AC0 /* Flutter-Debug.xcconfig */, + 33CEB47422A05771004F2AC0 /* Flutter-Release.xcconfig */, + 33CEB47722A0578A004F2AC0 /* Flutter-Generated.xcconfig */, + ); + path = Flutter; + sourceTree = ""; + }; + 33FAB671232836740065AC1E /* Runner */ = { + isa = PBXGroup; + children = ( + 33CC10F02044A3C60003C045 /* AppDelegate.swift */, + 33CC11122044BFA00003C045 /* MainFlutterWindow.swift */, + 33E51913231747F40026EE4D /* DebugProfile.entitlements */, + 33E51914231749380026EE4D /* Release.entitlements */, + 33CC11242044D66E0003C045 /* Resources */, + 33BA886A226E78AF003329D5 /* Configs */, + ); + path = Runner; + sourceTree = ""; + }; + D73912EC22F37F3D000D13A0 /* Frameworks */ = { + isa = PBXGroup; + children = ( + 7B4B572955B31AF77E32F668 /* Pods_Runner.framework */, + ); + name = Frameworks; + sourceTree = ""; + }; +/* End PBXGroup section */ + +/* Begin PBXNativeTarget section */ + 33CC10EC2044A3C60003C045 /* Runner */ = { + isa = PBXNativeTarget; + buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */; + buildPhases = ( + 57B2FF16A7003F1CD9EFF877 /* [CP] Check Pods Manifest.lock */, + 33CC10E92044A3C60003C045 /* Sources */, + 33CC10EA2044A3C60003C045 /* Frameworks */, + 33CC10EB2044A3C60003C045 /* Resources */, + 33CC110E2044A8840003C045 /* Bundle Framework */, + 3399D490228B24CF009A79C7 /* ShellScript */, + 041B2308AB13CA095BE44E8C /* [CP] Embed Pods Frameworks */, + ); + buildRules = ( + ); + dependencies = ( + 33CC11202044C79F0003C045 /* PBXTargetDependency */, + ); + name = Runner; + productName = Runner; + productReference = 33CC10ED2044A3C60003C045 /* isekai_wiki_app.app */; + productType = "com.apple.product-type.application"; + }; +/* End PBXNativeTarget section */ + +/* Begin PBXProject section */ + 33CC10E52044A3C60003C045 /* Project object */ = { + isa = PBXProject; + attributes = { + LastSwiftUpdateCheck = 0920; + LastUpgradeCheck = 1300; + ORGANIZATIONNAME = ""; + TargetAttributes = { + 33CC10EC2044A3C60003C045 = { + CreatedOnToolsVersion = 9.2; + LastSwiftMigration = 1100; + ProvisioningStyle = Automatic; + SystemCapabilities = { + com.apple.Sandbox = { + enabled = 1; + }; + }; + }; + 33CC111A2044C6BA0003C045 = { + CreatedOnToolsVersion = 9.2; + ProvisioningStyle = Manual; + }; + }; + }; + buildConfigurationList = 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */; + compatibilityVersion = "Xcode 9.3"; + developmentRegion = en; + hasScannedForEncodings = 0; + knownRegions = ( + en, + Base, + ); + mainGroup = 33CC10E42044A3C60003C045; + productRefGroup = 33CC10EE2044A3C60003C045 /* Products */; + projectDirPath = ""; + projectRoot = ""; + targets = ( + 33CC10EC2044A3C60003C045 /* Runner */, + 33CC111A2044C6BA0003C045 /* Flutter Assemble */, + ); + }; +/* End PBXProject section */ + +/* Begin PBXResourcesBuildPhase section */ + 33CC10EB2044A3C60003C045 /* Resources */ = { + isa = PBXResourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC10F32044A3C60003C045 /* Assets.xcassets in Resources */, + 33CC10F62044A3C60003C045 /* MainMenu.xib in Resources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXResourcesBuildPhase section */ + +/* Begin PBXShellScriptBuildPhase section */ + 041B2308AB13CA095BE44E8C /* [CP] Embed Pods Frameworks */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist", + ); + name = "[CP] Embed Pods Frameworks"; + outputFileListPaths = ( + "${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n"; + showEnvVarsInLog = 0; + }; + 3399D490228B24CF009A79C7 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + ); + outputFileListPaths = ( + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "echo \"$PRODUCT_NAME.app\" > \"$PROJECT_DIR\"/Flutter/ephemeral/.app_filename && \"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh embed\n"; + }; + 33CC111E2044C6BF0003C045 /* ShellScript */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + Flutter/ephemeral/FlutterInputs.xcfilelist, + ); + inputPaths = ( + Flutter/ephemeral/tripwire, + ); + outputFileListPaths = ( + Flutter/ephemeral/FlutterOutputs.xcfilelist, + ); + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "\"$FLUTTER_ROOT\"/packages/flutter_tools/bin/macos_assemble.sh && touch Flutter/ephemeral/tripwire"; + }; + 57B2FF16A7003F1CD9EFF877 /* [CP] Check Pods Manifest.lock */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputFileListPaths = ( + ); + inputPaths = ( + "${PODS_PODFILE_DIR_PATH}/Podfile.lock", + "${PODS_ROOT}/Manifest.lock", + ); + name = "[CP] Check Pods Manifest.lock"; + outputFileListPaths = ( + ); + outputPaths = ( + "$(DERIVED_FILE_DIR)/Pods-Runner-checkManifestLockResult.txt", + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n"; + showEnvVarsInLog = 0; + }; +/* End PBXShellScriptBuildPhase section */ + +/* Begin PBXSourcesBuildPhase section */ + 33CC10E92044A3C60003C045 /* Sources */ = { + isa = PBXSourcesBuildPhase; + buildActionMask = 2147483647; + files = ( + 33CC11132044BFA00003C045 /* MainFlutterWindow.swift in Sources */, + 33CC10F12044A3C60003C045 /* AppDelegate.swift in Sources */, + 335BBD1B22A9A15E00E9071D /* GeneratedPluginRegistrant.swift in Sources */, + ); + runOnlyForDeploymentPostprocessing = 0; + }; +/* End PBXSourcesBuildPhase section */ + +/* Begin PBXTargetDependency section */ + 33CC11202044C79F0003C045 /* PBXTargetDependency */ = { + isa = PBXTargetDependency; + target = 33CC111A2044C6BA0003C045 /* Flutter Assemble */; + targetProxy = 33CC111F2044C79F0003C045 /* PBXContainerItemProxy */; + }; +/* End PBXTargetDependency section */ + +/* Begin PBXVariantGroup section */ + 33CC10F42044A3C60003C045 /* MainMenu.xib */ = { + isa = PBXVariantGroup; + children = ( + 33CC10F52044A3C60003C045 /* Base */, + ); + name = MainMenu.xib; + path = Runner; + sourceTree = ""; + }; +/* End PBXVariantGroup section */ + +/* Begin XCBuildConfiguration section */ + 338D0CE9231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.13; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Profile; + }; + 338D0CEA231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Profile; + }; + 338D0CEB231458BD00FA5F75 /* Profile */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Profile; + }; + 33CC10F92044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 9740EEB21CF90195004384FC /* Debug.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = dwarf; + ENABLE_STRICT_OBJC_MSGSEND = YES; + ENABLE_TESTABILITY = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_DYNAMIC_NO_PIC = NO; + GCC_NO_COMMON_BLOCKS = YES; + GCC_OPTIMIZATION_LEVEL = 0; + GCC_PREPROCESSOR_DEFINITIONS = ( + "DEBUG=1", + "$(inherited)", + ); + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.13; + MTL_ENABLE_DEBUG_INFO = YES; + ONLY_ACTIVE_ARCH = YES; + SDKROOT = macosx; + SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + }; + name = Debug; + }; + 33CC10FA2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 7AFA3C8E1D35360C0083082E /* Release.xcconfig */; + buildSettings = { + ALWAYS_SEARCH_USER_PATHS = NO; + CLANG_ANALYZER_NONNULL = YES; + CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; + CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; + CLANG_CXX_LIBRARY = "libc++"; + CLANG_ENABLE_MODULES = YES; + CLANG_ENABLE_OBJC_ARC = YES; + CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; + CLANG_WARN_BOOL_CONVERSION = YES; + CLANG_WARN_CONSTANT_CONVERSION = YES; + CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES; + CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; + CLANG_WARN_DOCUMENTATION_COMMENTS = YES; + CLANG_WARN_EMPTY_BODY = YES; + CLANG_WARN_ENUM_CONVERSION = YES; + CLANG_WARN_INFINITE_RECURSION = YES; + CLANG_WARN_INT_CONVERSION = YES; + CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; + CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; + CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; + CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; + CLANG_WARN_SUSPICIOUS_MOVE = YES; + CODE_SIGN_IDENTITY = "-"; + COPY_PHASE_STRIP = NO; + DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; + ENABLE_NS_ASSERTIONS = NO; + ENABLE_STRICT_OBJC_MSGSEND = YES; + GCC_C_LANGUAGE_STANDARD = gnu11; + GCC_NO_COMMON_BLOCKS = YES; + GCC_WARN_64_TO_32_BIT_CONVERSION = YES; + GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; + GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; + GCC_WARN_UNUSED_FUNCTION = YES; + GCC_WARN_UNUSED_VARIABLE = YES; + MACOSX_DEPLOYMENT_TARGET = 10.13; + MTL_ENABLE_DEBUG_INFO = NO; + SDKROOT = macosx; + SWIFT_COMPILATION_MODE = wholemodule; + SWIFT_OPTIMIZATION_LEVEL = "-O"; + }; + name = Release; + }; + 33CC10FC2044A3C60003C045 /* Debug */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/DebugProfile.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_OPTIMIZATION_LEVEL = "-Onone"; + SWIFT_VERSION = 5.0; + }; + name = Debug; + }; + 33CC10FD2044A3C60003C045 /* Release */ = { + isa = XCBuildConfiguration; + baseConfigurationReference = 33E5194F232828860026EE4D /* AppInfo.xcconfig */; + buildSettings = { + ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; + CLANG_ENABLE_MODULES = YES; + CODE_SIGN_ENTITLEMENTS = Runner/Release.entitlements; + CODE_SIGN_STYLE = Automatic; + COMBINE_HIDPI_IMAGES = YES; + INFOPLIST_FILE = Runner/Info.plist; + LD_RUNPATH_SEARCH_PATHS = ( + "$(inherited)", + "@executable_path/../Frameworks", + ); + PROVISIONING_PROFILE_SPECIFIER = ""; + SWIFT_VERSION = 5.0; + }; + name = Release; + }; + 33CC111C2044C6BA0003C045 /* Debug */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Manual; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Debug; + }; + 33CC111D2044C6BA0003C045 /* Release */ = { + isa = XCBuildConfiguration; + buildSettings = { + CODE_SIGN_STYLE = Automatic; + PRODUCT_NAME = "$(TARGET_NAME)"; + }; + name = Release; + }; +/* End XCBuildConfiguration section */ + +/* Begin XCConfigurationList section */ + 33CC10E82044A3C60003C045 /* Build configuration list for PBXProject "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10F92044A3C60003C045 /* Debug */, + 33CC10FA2044A3C60003C045 /* Release */, + 338D0CE9231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC10FC2044A3C60003C045 /* Debug */, + 33CC10FD2044A3C60003C045 /* Release */, + 338D0CEA231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; + 33CC111B2044C6BA0003C045 /* Build configuration list for PBXAggregateTarget "Flutter Assemble" */ = { + isa = XCConfigurationList; + buildConfigurations = ( + 33CC111C2044C6BA0003C045 /* Debug */, + 33CC111D2044C6BA0003C045 /* Release */, + 338D0CEB231458BD00FA5F75 /* Profile */, + ); + defaultConfigurationIsVisible = 0; + defaultConfigurationName = Release; + }; +/* End XCConfigurationList section */ + }; + rootObject = 33CC10E52044A3C60003C045 /* Project object */; +} diff --git a/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100755 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme new file mode 100755 index 0000000..dad8744 --- /dev/null +++ b/macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme @@ -0,0 +1,87 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner.xcworkspace/contents.xcworkspacedata b/macos/Runner.xcworkspace/contents.xcworkspacedata new file mode 100755 index 0000000..21a3cc1 --- /dev/null +++ b/macos/Runner.xcworkspace/contents.xcworkspacedata @@ -0,0 +1,10 @@ + + + + + + + diff --git a/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist new file mode 100755 index 0000000..18d9810 --- /dev/null +++ b/macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist @@ -0,0 +1,8 @@ + + + + + IDEDidComputeMac32BitWarning + + + diff --git a/macos/Runner/AppDelegate.swift b/macos/Runner/AppDelegate.swift new file mode 100755 index 0000000..d53ef64 --- /dev/null +++ b/macos/Runner/AppDelegate.swift @@ -0,0 +1,9 @@ +import Cocoa +import FlutterMacOS + +@NSApplicationMain +class AppDelegate: FlutterAppDelegate { + override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool { + return true + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json new file mode 100755 index 0000000..a2ec33f --- /dev/null +++ b/macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json @@ -0,0 +1,68 @@ +{ + "images" : [ + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_16.png", + "scale" : "1x" + }, + { + "size" : "16x16", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "2x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_32.png", + "scale" : "1x" + }, + { + "size" : "32x32", + "idiom" : "mac", + "filename" : "app_icon_64.png", + "scale" : "2x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_128.png", + "scale" : "1x" + }, + { + "size" : "128x128", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "2x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_256.png", + "scale" : "1x" + }, + { + "size" : "256x256", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "2x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_512.png", + "scale" : "1x" + }, + { + "size" : "512x512", + "idiom" : "mac", + "filename" : "app_icon_1024.png", + "scale" : "2x" + } + ], + "info" : { + "version" : 1, + "author" : "xcode" + } +} diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png new file mode 100755 index 0000000..82b6f9d Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_1024.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png new file mode 100755 index 0000000..13b35eb Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_128.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png new file mode 100755 index 0000000..0a3f5fa Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_16.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png new file mode 100755 index 0000000..bdb5722 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_256.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png new file mode 100755 index 0000000..f083318 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_32.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png new file mode 100755 index 0000000..326c0e7 Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_512.png differ diff --git a/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png new file mode 100755 index 0000000..2f1632c Binary files /dev/null and b/macos/Runner/Assets.xcassets/AppIcon.appiconset/app_icon_64.png differ diff --git a/macos/Runner/Base.lproj/MainMenu.xib b/macos/Runner/Base.lproj/MainMenu.xib new file mode 100755 index 0000000..80e867a --- /dev/null +++ b/macos/Runner/Base.lproj/MainMenu.xib @@ -0,0 +1,343 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/macos/Runner/Configs/AppInfo.xcconfig b/macos/Runner/Configs/AppInfo.xcconfig new file mode 100755 index 0000000..701db73 --- /dev/null +++ b/macos/Runner/Configs/AppInfo.xcconfig @@ -0,0 +1,14 @@ +// Application-level settings for the Runner target. +// +// This may be replaced with something auto-generated from metadata (e.g., pubspec.yaml) in the +// future. If not, the values below would default to using the project name when this becomes a +// 'flutter create' template. + +// The application's name. By default this is also the title of the Flutter window. +PRODUCT_NAME = isekai_wiki_app + +// The application's bundle identifier +PRODUCT_BUNDLE_IDENTIFIER = cn.isekai.wiki.isekaiWikiApp + +// The copyright displayed in application information +PRODUCT_COPYRIGHT = Copyright © 2022 cn.isekai.wiki. All rights reserved. diff --git a/macos/Runner/Configs/Debug.xcconfig b/macos/Runner/Configs/Debug.xcconfig new file mode 100755 index 0000000..36b0fd9 --- /dev/null +++ b/macos/Runner/Configs/Debug.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Debug.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Release.xcconfig b/macos/Runner/Configs/Release.xcconfig new file mode 100755 index 0000000..dff4f49 --- /dev/null +++ b/macos/Runner/Configs/Release.xcconfig @@ -0,0 +1,2 @@ +#include "../../Flutter/Flutter-Release.xcconfig" +#include "Warnings.xcconfig" diff --git a/macos/Runner/Configs/Warnings.xcconfig b/macos/Runner/Configs/Warnings.xcconfig new file mode 100755 index 0000000..42bcbf4 --- /dev/null +++ b/macos/Runner/Configs/Warnings.xcconfig @@ -0,0 +1,13 @@ +WARNING_CFLAGS = -Wall -Wconditional-uninitialized -Wnullable-to-nonnull-conversion -Wmissing-method-return-type -Woverlength-strings +GCC_WARN_UNDECLARED_SELECTOR = YES +CLANG_UNDEFINED_BEHAVIOR_SANITIZER_NULLABILITY = YES +CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE +CLANG_WARN__DUPLICATE_METHOD_MATCH = YES +CLANG_WARN_PRAGMA_PACK = YES +CLANG_WARN_STRICT_PROTOTYPES = YES +CLANG_WARN_COMMA = YES +GCC_WARN_STRICT_SELECTOR_MATCH = YES +CLANG_WARN_OBJC_REPEATED_USE_OF_WEAK = YES +CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES +GCC_WARN_SHADOW = YES +CLANG_WARN_UNREACHABLE_CODE = YES diff --git a/macos/Runner/DebugProfile.entitlements b/macos/Runner/DebugProfile.entitlements new file mode 100755 index 0000000..08c3ab1 --- /dev/null +++ b/macos/Runner/DebugProfile.entitlements @@ -0,0 +1,14 @@ + + + + + com.apple.security.app-sandbox + + com.apple.security.cs.allow-jit + + com.apple.security.network.server + + com.apple.security.network.client + + + diff --git a/macos/Runner/Info.plist b/macos/Runner/Info.plist new file mode 100755 index 0000000..4789daa --- /dev/null +++ b/macos/Runner/Info.plist @@ -0,0 +1,32 @@ + + + + + CFBundleDevelopmentRegion + $(DEVELOPMENT_LANGUAGE) + CFBundleExecutable + $(EXECUTABLE_NAME) + CFBundleIconFile + + CFBundleIdentifier + $(PRODUCT_BUNDLE_IDENTIFIER) + CFBundleInfoDictionaryVersion + 6.0 + CFBundleName + $(PRODUCT_NAME) + CFBundlePackageType + APPL + CFBundleShortVersionString + $(FLUTTER_BUILD_NAME) + CFBundleVersion + $(FLUTTER_BUILD_NUMBER) + LSMinimumSystemVersion + $(MACOSX_DEPLOYMENT_TARGET) + NSHumanReadableCopyright + $(PRODUCT_COPYRIGHT) + NSMainNibFile + MainMenu + NSPrincipalClass + NSApplication + + diff --git a/macos/Runner/MainFlutterWindow.swift b/macos/Runner/MainFlutterWindow.swift new file mode 100755 index 0000000..2722837 --- /dev/null +++ b/macos/Runner/MainFlutterWindow.swift @@ -0,0 +1,15 @@ +import Cocoa +import FlutterMacOS + +class MainFlutterWindow: NSWindow { + override func awakeFromNib() { + let flutterViewController = FlutterViewController.init() + let windowFrame = self.frame + self.contentViewController = flutterViewController + self.setFrame(windowFrame, display: true) + + RegisterGeneratedPlugins(registry: flutterViewController) + + super.awakeFromNib() + } +} diff --git a/macos/Runner/Release.entitlements b/macos/Runner/Release.entitlements new file mode 100755 index 0000000..852fa1a --- /dev/null +++ b/macos/Runner/Release.entitlements @@ -0,0 +1,8 @@ + + + + + com.apple.security.app-sandbox + + + diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 0000000..1f45f24 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,906 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + url: "https://pub.dartlang.org" + source: hosted + version: "50.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + url: "https://pub.dartlang.org" + source: hosted + version: "5.2.0" + animations: + dependency: "direct main" + description: + name: animations + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.7" + args: + dependency: transitive + description: + name: args + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.1" + async: + dependency: "direct main" + description: + name: async + url: "https://pub.dartlang.org" + source: hosted + version: "2.9.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + build: + dependency: transitive + description: + name: build + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.1" + build_config: + dependency: transitive + description: + name: build_config + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.1" + build_daemon: + dependency: transitive + description: + name: build_daemon + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.0" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + build_runner: + dependency: "direct dev" + description: + name: build_runner + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.3" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + url: "https://pub.dartlang.org" + source: hosted + version: "7.2.7" + built_collection: + dependency: transitive + description: + name: built_collection + url: "https://pub.dartlang.org" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + url: "https://pub.dartlang.org" + source: hosted + version: "8.4.2" + characters: + dependency: transitive + description: + name: characters + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.1" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + chewie: + dependency: transitive + description: + name: chewie + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.6" + chewie_audio: + dependency: transitive + description: + name: chewie_audio + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.1" + code_builder: + dependency: transitive + description: + name: code_builder + url: "https://pub.dartlang.org" + source: hosted + version: "4.4.0" + collection: + dependency: transitive + description: + name: collection + url: "https://pub.dartlang.org" + source: hosted + version: "1.16.0" + convert: + dependency: transitive + description: + name: convert + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.1" + crypto: + dependency: transitive + description: + name: crypto + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.2" + csslib: + dependency: transitive + description: + name: csslib + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.2" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.5" + cupertino_lists: + dependency: "direct main" + description: + name: cupertino_lists + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + dart_style: + dependency: transitive + description: + name: dart_style + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.4" + fake_async: + dependency: transitive + description: + name: fake_async + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.1" + ffi: + dependency: transitive + description: + name: ffi + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + file: + dependency: transitive + description: + name: file + url: "https://pub.dartlang.org" + source: hosted + version: "6.1.4" + fixnum: + dependency: transitive + description: + name: fixnum + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.1" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_displaymode: + dependency: "direct main" + description: + name: flutter_displaymode + url: "https://pub.dartlang.org" + source: hosted + version: "0.3.2" + flutter_html: + dependency: "direct main" + description: + name: flutter_html + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.1" + flutter_layout_grid: + dependency: transitive + description: + name: flutter_layout_grid + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.6" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + flutter_localizations: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_math_fork: + dependency: transitive + description: + name: flutter_math_fork + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.0" + flutter_scale_tap: + dependency: "direct main" + description: + name: flutter_scale_tap + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.5" + flutter_svg: + dependency: transitive + description: + name: flutter_svg + url: "https://pub.dartlang.org" + source: hosted + version: "0.23.0+1" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + flutter_web_browser: + dependency: "direct main" + description: + name: flutter_web_browser + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.1" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + url: "https://pub.dartlang.org" + source: hosted + version: "3.2.0" + get: + dependency: "direct main" + description: + name: get + url: "https://pub.dartlang.org" + source: hosted + version: "4.6.5" + glob: + dependency: transitive + description: + name: glob + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + graphs: + dependency: transitive + description: + name: graphs + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.0" + html: + dependency: transitive + description: + name: html + url: "https://pub.dartlang.org" + source: hosted + version: "0.15.1" + http: + dependency: "direct main" + description: + name: http + url: "https://pub.dartlang.org" + source: hosted + version: "0.13.5" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + url: "https://pub.dartlang.org" + source: hosted + version: "3.2.1" + http_parser: + dependency: transitive + description: + name: http_parser + url: "https://pub.dartlang.org" + source: hosted + version: "4.0.2" + intl: + dependency: "direct main" + description: + name: intl + url: "https://pub.dartlang.org" + source: hosted + version: "0.17.0" + io: + dependency: transitive + description: + name: io + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.3" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.4" + json_annotation: + dependency: "direct main" + description: + name: json_annotation + url: "https://pub.dartlang.org" + source: hosted + version: "4.7.0" + json_serializable: + dependency: "direct main" + description: + name: json_serializable + url: "https://pub.dartlang.org" + source: hosted + version: "6.5.4" + like_button: + dependency: "direct main" + description: + name: like_button + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.5" + lints: + dependency: transitive + description: + name: lints + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + logging: + dependency: transitive + description: + name: logging + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.0" + matcher: + dependency: transitive + description: + name: matcher + url: "https://pub.dartlang.org" + source: hosted + version: "0.12.12" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + url: "https://pub.dartlang.org" + source: hosted + version: "0.1.5" + meta: + dependency: transitive + description: + name: meta + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.0" + mime: + dependency: transitive + description: + name: mime + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.3" + nested: + dependency: transitive + description: + name: nested + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + numerus: + dependency: transitive + description: + name: numerus + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.1" + package_config: + dependency: transitive + description: + name: package_config + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + package_info_plus: + dependency: "direct main" + description: + name: package_info_plus + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.2" + package_info_plus_platform_interface: + dependency: transitive + description: + name: package_info_plus_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + path: + dependency: transitive + description: + name: path + url: "https://pub.dartlang.org" + source: hosted + version: "1.8.2" + path_drawing: + dependency: transitive + description: + name: path_drawing + url: "https://pub.dartlang.org" + source: hosted + version: "0.5.1+1" + path_parsing: + dependency: transitive + description: + name: path_parsing + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.1" + path_provider_linux: + dependency: transitive + description: + name: path_provider_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.7" + path_provider_platform_interface: + dependency: transitive + description: + name: path_provider_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.5" + path_provider_windows: + dependency: transitive + description: + name: path_provider_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" + petitparser: + dependency: transitive + description: + name: petitparser + url: "https://pub.dartlang.org" + source: hosted + version: "5.1.0" + platform: + dependency: transitive + description: + name: platform + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" + pool: + dependency: transitive + description: + name: pool + url: "https://pub.dartlang.org" + source: hosted + version: "1.5.1" + process: + dependency: transitive + description: + name: process + url: "https://pub.dartlang.org" + source: hosted + version: "4.2.4" + provider: + dependency: "direct main" + description: + name: provider + url: "https://pub.dartlang.org" + source: hosted + version: "6.0.5" + pub_semver: + dependency: transitive + description: + name: pub_semver + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.1" + pull_down_button: + dependency: "direct main" + description: + name: pull_down_button + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.1" + quiver: + dependency: transitive + description: + name: quiver + url: "https://pub.dartlang.org" + source: hosted + version: "3.2.1" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.15" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.14" + shared_preferences_ios: + dependency: transitive + description: + name: shared_preferences_ios + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" + shared_preferences_macos: + dependency: transitive + description: + name: shared_preferences_macos + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" + shelf: + dependency: transitive + description: + name: shelf + url: "https://pub.dartlang.org" + source: hosted + version: "1.4.0" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.3" + skeletons: + dependency: "direct main" + description: + name: skeletons + url: "https://pub.dartlang.org" + source: hosted + version: "0.0.3" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_gen: + dependency: transitive + description: + name: source_gen + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.6" + source_helper: + dependency: transitive + description: + name: source_helper + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.3" + source_span: + dependency: transitive + description: + name: source_span + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + url: "https://pub.dartlang.org" + source: hosted + version: "1.10.0" + stream_channel: + dependency: transitive + description: + name: stream_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + stream_transform: + dependency: transitive + description: + name: stream_transform + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + url: "https://pub.dartlang.org" + source: hosted + version: "1.1.1" + term_glyph: + dependency: transitive + description: + name: term_glyph + url: "https://pub.dartlang.org" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.12" + timing: + dependency: transitive + description: + name: timing + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + tuple: + dependency: transitive + description: + name: tuple + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.1" + typed_data: + dependency: transitive + description: + name: typed_data + url: "https://pub.dartlang.org" + source: hosted + version: "1.3.1" + vector_math: + dependency: transitive + description: + name: vector_math + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" + video_player: + dependency: transitive + description: + name: video_player + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.10" + video_player_android: + dependency: transitive + description: + name: video_player_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.10" + video_player_avfoundation: + dependency: transitive + description: + name: video_player_avfoundation + url: "https://pub.dartlang.org" + source: hosted + version: "2.3.8" + video_player_platform_interface: + dependency: transitive + description: + name: video_player_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "6.0.1" + video_player_web: + dependency: transitive + description: + name: video_player_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.13" + wakelock: + dependency: transitive + description: + name: wakelock + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.2" + wakelock_macos: + dependency: transitive + description: + name: wakelock_macos + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.0" + wakelock_platform_interface: + dependency: transitive + description: + name: wakelock_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "0.3.0" + wakelock_web: + dependency: transitive + description: + name: wakelock_web + url: "https://pub.dartlang.org" + source: hosted + version: "0.4.0" + wakelock_windows: + dependency: transitive + description: + name: wakelock_windows + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.1" + watcher: + dependency: transitive + description: + name: watcher + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.2" + web_smooth_scroll: + dependency: "direct main" + description: + name: web_smooth_scroll + url: "https://pub.dartlang.org" + source: hosted + version: "1.0.0" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + url: "https://pub.dartlang.org" + source: hosted + version: "2.2.0" + webview_flutter: + dependency: transitive + description: + name: webview_flutter + url: "https://pub.dartlang.org" + source: hosted + version: "2.8.0" + webview_flutter_android: + dependency: transitive + description: + name: webview_flutter_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.10.4" + webview_flutter_platform_interface: + dependency: transitive + description: + name: webview_flutter_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "1.9.5" + webview_flutter_wkwebview: + dependency: transitive + description: + name: webview_flutter_wkwebview + url: "https://pub.dartlang.org" + source: hosted + version: "2.9.5" + win32: + dependency: transitive + description: + name: win32 + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.3" + xdg_directories: + dependency: transitive + description: + name: xdg_directories + url: "https://pub.dartlang.org" + source: hosted + version: "0.2.0+2" + xml: + dependency: transitive + description: + name: xml + url: "https://pub.dartlang.org" + source: hosted + version: "5.4.1" + yaml: + dependency: transitive + description: + name: yaml + url: "https://pub.dartlang.org" + source: hosted + version: "3.1.1" +sdks: + dart: ">=2.18.0 <3.0.0" + flutter: ">=3.0.0" diff --git a/pubspec.yaml b/pubspec.yaml new file mode 100755 index 0000000..260ba2a --- /dev/null +++ b/pubspec.yaml @@ -0,0 +1,112 @@ +name: isekai_wiki +description: 异世界百科APP + +# The following line prevents the package from being accidentally published to +# pub.dev using `flutter pub publish`. This is preferred for private packages. +publish_to: 'none' # Remove this line if you wish to publish to pub.dev + +# The following defines the version and build number for your application. +# A version number is three numbers separated by dots, like 1.2.43 +# followed by an optional build number separated by a +. +# Both the version and the builder number may be overridden in flutter +# build by specifying --build-name and --build-number, respectively. +# In Android, build-name is used as versionName while build-number used as versionCode. +# Read more about Android versioning at https://developer.android.com/studio/publish/versioning +# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion. +# Read more about iOS versioning at +# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html +# In Windows, build-name is used as the major, minor, and patch parts +# of the product and file versions while build-number is used as the build suffix. +version: 1.0.0+1 + +environment: + sdk: '>=2.18.0 <3.0.0' + +# Dependencies specify other packages that your package needs in order to work. +# To automatically upgrade your package dependencies to the latest versions +# consider running `flutter pub upgrade --major-versions`. Alternatively, +# dependencies can be manually updated by changing the version numbers below to +# the latest version available on pub.dev. To see which dependencies have newer +# versions available, run `flutter pub outdated`. +dependencies: + flutter: + sdk: flutter + flutter_localizations: # Add this line + sdk: flutter # Add this line + + # The following adds the Cupertino Icons font to your application. + # Use with the CupertinoIcons class for iOS style icons. + async: ^2.9.0 + cupertino_icons: ^1.0.2 + cupertino_lists: ^1.0.1 + intl: ^0.17.0 + provider: ^6.0.0 + animations: ^2.0.4 + flutter_displaymode: ^0.3.2 + flutter_scale_tap: ^1.0.5 + shared_preferences: ^2.0.15 + like_button: ^2.0.4 + skeletons: ^0.0.3 + flutter_web_browser: ^0.17.1 + web_smooth_scroll: ^1.0.0 + json_serializable: ^6.5.4 + json_annotation: ^4.7.0 + flutter_html: ^2.2.1 + package_info_plus: ^3.0.2 + pull_down_button: ^0.4.1 + http: ^0.13.5 + get: + +dev_dependencies: + flutter_test: + sdk: flutter + + # The "flutter_lints" package below contains a set of recommended lints to + # encourage good coding practices. The lint set provided by the package is + # activated in the `analysis_options.yaml` file located at the root of your + # package. See that file for information about deactivating specific lint + # rules and activating additional ones. + flutter_lints: ^2.0.0 + build_runner: ^2.3.3 + +# For information on the generic Dart part of this file, see the +# following page: https://dart.dev/tools/pub/pubspec + +# The following section is specific to Flutter packages. +flutter: + + # The following line ensures that the Material Icons font is + # included with your application, so that you can use the icons in + # the material Icons class. + uses-material-design: true + + # To add assets to your application, add an assets section, like this: + # assets: + # - images/a_dot_burr.jpeg + # - images/a_dot_ham.jpeg + + # An image asset can refer to one or more resolution-specific "variants", see + # https://flutter.dev/assets-and-images/#resolution-aware + + # For details regarding adding assets from package dependencies, see + # https://flutter.dev/assets-and-images/#from-packages + + # To add custom fonts to your application, add a fonts section here, + # in this "flutter" section. Each entry in this list should have a + # "family" key with the font family name, and a "fonts" key with a + # list giving the asset and other descriptors for the font. For + # example: + # fonts: + # - family: Schyler + # fonts: + # - asset: fonts/Schyler-Regular.ttf + # - asset: fonts/Schyler-Italic.ttf + # style: italic + # - family: Trajan Pro + # fonts: + # - asset: fonts/TrajanPro.ttf + # - asset: fonts/TrajanPro_Bold.ttf + # weight: 700 + # + # For details regarding fonts from package dependencies, + # see https://flutter.dev/custom-fonts/#from-packages diff --git a/test/widget_test.dart b/test/widget_test.dart new file mode 100755 index 0000000..9319a4c --- /dev/null +++ b/test/widget_test.dart @@ -0,0 +1,19 @@ +// This is a basic Flutter widget test. +// +// To perform an interaction with a widget in your test, use the WidgetTester +// utility in the flutter_test package. For example, you can send tap and scroll +// gestures. You can also use WidgetTester to find child widgets in the widget +// tree, read text, and verify that the values of widget properties are correct. + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:isekai_wiki/app.dart'; + +import 'package:isekai_wiki/main.dart'; + +void main() { + testWidgets('Counter increments smoke test', (WidgetTester tester) async { + // Build our app and trigger a frame. + await tester.pumpWidget(const IsekaiWikiApp()); + }); +} diff --git a/web/favicon.png b/web/favicon.png new file mode 100755 index 0000000..8aaa46a Binary files /dev/null and b/web/favicon.png differ diff --git a/web/icons/Icon-192.png b/web/icons/Icon-192.png new file mode 100755 index 0000000..b749bfe Binary files /dev/null and b/web/icons/Icon-192.png differ diff --git a/web/icons/Icon-512.png b/web/icons/Icon-512.png new file mode 100755 index 0000000..88cfd48 Binary files /dev/null and b/web/icons/Icon-512.png differ diff --git a/web/icons/Icon-maskable-192.png b/web/icons/Icon-maskable-192.png new file mode 100755 index 0000000..eb9b4d7 Binary files /dev/null and b/web/icons/Icon-maskable-192.png differ diff --git a/web/icons/Icon-maskable-512.png b/web/icons/Icon-maskable-512.png new file mode 100755 index 0000000..d69c566 Binary files /dev/null and b/web/icons/Icon-maskable-512.png differ diff --git a/web/index.html b/web/index.html new file mode 100755 index 0000000..4729397 --- /dev/null +++ b/web/index.html @@ -0,0 +1,58 @@ + + + + + + + + + + + + + + + + + + + + isekai_wiki_app + + + + + + + + + + diff --git a/web/manifest.json b/web/manifest.json new file mode 100755 index 0000000..6a67778 --- /dev/null +++ b/web/manifest.json @@ -0,0 +1,35 @@ +{ + "name": "isekai_wiki_app", + "short_name": "isekai_wiki_app", + "start_url": ".", + "display": "standalone", + "background_color": "#0175C2", + "theme_color": "#0175C2", + "description": "A new Flutter project.", + "orientation": "portrait-primary", + "prefer_related_applications": false, + "icons": [ + { + "src": "icons/Icon-192.png", + "sizes": "192x192", + "type": "image/png" + }, + { + "src": "icons/Icon-512.png", + "sizes": "512x512", + "type": "image/png" + }, + { + "src": "icons/Icon-maskable-192.png", + "sizes": "192x192", + "type": "image/png", + "purpose": "maskable" + }, + { + "src": "icons/Icon-maskable-512.png", + "sizes": "512x512", + "type": "image/png", + "purpose": "maskable" + } + ] +} diff --git a/windows/.gitignore b/windows/.gitignore new file mode 100755 index 0000000..d492d0d --- /dev/null +++ b/windows/.gitignore @@ -0,0 +1,17 @@ +flutter/ephemeral/ + +# Visual Studio user-specific files. +*.suo +*.user +*.userosscache +*.sln.docstates + +# Visual Studio build-related files. +x64/ +x86/ + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!*.[Cc]ache/ diff --git a/windows/CMakeLists.txt b/windows/CMakeLists.txt new file mode 100755 index 0000000..9954f00 --- /dev/null +++ b/windows/CMakeLists.txt @@ -0,0 +1,101 @@ +# Project-level configuration. +cmake_minimum_required(VERSION 3.14) +project(isekai_wiki LANGUAGES CXX) + +# The name of the executable created for the application. Change this to change +# the on-disk name of your application. +set(BINARY_NAME "isekai_wiki") + +# Explicitly opt in to modern CMake behaviors to avoid warnings with recent +# versions of CMake. +cmake_policy(SET CMP0063 NEW) + +# Define build configuration option. +get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG) +if(IS_MULTICONFIG) + set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release" + CACHE STRING "" FORCE) +else() + if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES) + set(CMAKE_BUILD_TYPE "Debug" CACHE + STRING "Flutter build mode" FORCE) + set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS + "Debug" "Profile" "Release") + endif() +endif() +# Define settings for the Profile build mode. +set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}") +set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}") +set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}") +set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}") + +# Use Unicode for all projects. +add_definitions(-DUNICODE -D_UNICODE) + +# Compilation settings that should be applied to most targets. +# +# Be cautious about adding new options here, as plugins use this function by +# default. In most cases, you should add new options to specific targets instead +# of modifying this function. +function(APPLY_STANDARD_SETTINGS TARGET) + target_compile_features(${TARGET} PUBLIC cxx_std_17) + target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100") + target_compile_options(${TARGET} PRIVATE /EHsc) + target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0") + target_compile_definitions(${TARGET} PRIVATE "$<$:_DEBUG>") +endfunction() + +# Flutter library and tool build rules. +set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter") +add_subdirectory(${FLUTTER_MANAGED_DIR}) + +# Application build; see runner/CMakeLists.txt. +add_subdirectory("runner") + +# Generated plugin build rules, which manage building the plugins and adding +# them to the application. +include(flutter/generated_plugins.cmake) + + +# === Installation === +# Support files are copied into place next to the executable, so that it can +# run in place. This is done instead of making a separate bundle (as on Linux) +# so that building and running from within Visual Studio will work. +set(BUILD_BUNDLE_DIR "$") +# Make the "install" step default, as it's required to run. +set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1) +if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT) + set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE) +endif() + +set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data") +set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}") + +install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + COMPONENT Runtime) + +install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) + +if(PLUGIN_BUNDLED_LIBRARIES) + install(FILES "${PLUGIN_BUNDLED_LIBRARIES}" + DESTINATION "${INSTALL_BUNDLE_LIB_DIR}" + COMPONENT Runtime) +endif() + +# Fully re-copy the assets directory on each build to avoid having stale files +# from a previous install. +set(FLUTTER_ASSET_DIR_NAME "flutter_assets") +install(CODE " + file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\") + " COMPONENT Runtime) +install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}" + DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime) + +# Install the AOT library on non-Debug builds only. +install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" + CONFIGURATIONS Profile;Release + COMPONENT Runtime) diff --git a/windows/flutter/CMakeLists.txt b/windows/flutter/CMakeLists.txt new file mode 100755 index 0000000..930d207 --- /dev/null +++ b/windows/flutter/CMakeLists.txt @@ -0,0 +1,104 @@ +# This file controls Flutter-level build steps. It should not be edited. +cmake_minimum_required(VERSION 3.14) + +set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral") + +# Configuration provided via flutter tool. +include(${EPHEMERAL_DIR}/generated_config.cmake) + +# TODO: Move the rest of this into files in ephemeral. See +# https://github.com/flutter/flutter/issues/57146. +set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper") + +# === Flutter Library === +set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll") + +# Published to parent scope for install step. +set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE) +set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE) +set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE) +set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE) + +list(APPEND FLUTTER_LIBRARY_HEADERS + "flutter_export.h" + "flutter_windows.h" + "flutter_messenger.h" + "flutter_plugin_registrar.h" + "flutter_texture_registrar.h" +) +list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/") +add_library(flutter INTERFACE) +target_include_directories(flutter INTERFACE + "${EPHEMERAL_DIR}" +) +target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib") +add_dependencies(flutter flutter_assemble) + +# === Wrapper === +list(APPEND CPP_WRAPPER_SOURCES_CORE + "core_implementations.cc" + "standard_codec.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_PLUGIN + "plugin_registrar.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/") +list(APPEND CPP_WRAPPER_SOURCES_APP + "flutter_engine.cc" + "flutter_view_controller.cc" +) +list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/") + +# Wrapper sources needed for a plugin. +add_library(flutter_wrapper_plugin STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} +) +apply_standard_settings(flutter_wrapper_plugin) +set_target_properties(flutter_wrapper_plugin PROPERTIES + POSITION_INDEPENDENT_CODE ON) +set_target_properties(flutter_wrapper_plugin PROPERTIES + CXX_VISIBILITY_PRESET hidden) +target_link_libraries(flutter_wrapper_plugin PUBLIC flutter) +target_include_directories(flutter_wrapper_plugin PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_plugin flutter_assemble) + +# Wrapper sources needed for the runner. +add_library(flutter_wrapper_app STATIC + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_APP} +) +apply_standard_settings(flutter_wrapper_app) +target_link_libraries(flutter_wrapper_app PUBLIC flutter) +target_include_directories(flutter_wrapper_app PUBLIC + "${WRAPPER_ROOT}/include" +) +add_dependencies(flutter_wrapper_app flutter_assemble) + +# === Flutter tool backend === +# _phony_ is a non-existent file to force this command to run every time, +# since currently there's no way to get a full input/output list from the +# flutter tool. +set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_") +set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE) +add_custom_command( + OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} + ${PHONY_OUTPUT} + COMMAND ${CMAKE_COMMAND} -E env + ${FLUTTER_TOOL_ENVIRONMENT} + "${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat" + windows-x64 $ + VERBATIM +) +add_custom_target(flutter_assemble DEPENDS + "${FLUTTER_LIBRARY}" + ${FLUTTER_LIBRARY_HEADERS} + ${CPP_WRAPPER_SOURCES_CORE} + ${CPP_WRAPPER_SOURCES_PLUGIN} + ${CPP_WRAPPER_SOURCES_APP} +) diff --git a/windows/flutter/generated_plugin_registrant.cc b/windows/flutter/generated_plugin_registrant.cc new file mode 100755 index 0000000..8b6d468 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.cc @@ -0,0 +1,11 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#include "generated_plugin_registrant.h" + + +void RegisterPlugins(flutter::PluginRegistry* registry) { +} diff --git a/windows/flutter/generated_plugin_registrant.h b/windows/flutter/generated_plugin_registrant.h new file mode 100755 index 0000000..dc139d8 --- /dev/null +++ b/windows/flutter/generated_plugin_registrant.h @@ -0,0 +1,15 @@ +// +// Generated file. Do not edit. +// + +// clang-format off + +#ifndef GENERATED_PLUGIN_REGISTRANT_ +#define GENERATED_PLUGIN_REGISTRANT_ + +#include + +// Registers Flutter plugins. +void RegisterPlugins(flutter::PluginRegistry* registry); + +#endif // GENERATED_PLUGIN_REGISTRANT_ diff --git a/windows/flutter/generated_plugins.cmake b/windows/flutter/generated_plugins.cmake new file mode 100755 index 0000000..b93c4c3 --- /dev/null +++ b/windows/flutter/generated_plugins.cmake @@ -0,0 +1,23 @@ +# +# Generated file, do not edit. +# + +list(APPEND FLUTTER_PLUGIN_LIST +) + +list(APPEND FLUTTER_FFI_PLUGIN_LIST +) + +set(PLUGIN_BUNDLED_LIBRARIES) + +foreach(plugin ${FLUTTER_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin}) + target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin) + list(APPEND PLUGIN_BUNDLED_LIBRARIES $) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries}) +endforeach(plugin) + +foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST}) + add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin}) + list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries}) +endforeach(ffi_plugin) diff --git a/windows/runner/CMakeLists.txt b/windows/runner/CMakeLists.txt new file mode 100755 index 0000000..17411a8 --- /dev/null +++ b/windows/runner/CMakeLists.txt @@ -0,0 +1,39 @@ +cmake_minimum_required(VERSION 3.14) +project(runner LANGUAGES CXX) + +# Define the application target. To change its name, change BINARY_NAME in the +# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer +# work. +# +# Any new source files that you add to the application should be added here. +add_executable(${BINARY_NAME} WIN32 + "flutter_window.cpp" + "main.cpp" + "utils.cpp" + "win32_window.cpp" + "${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc" + "Runner.rc" + "runner.exe.manifest" +) + +# Apply the standard set of build settings. This can be removed for applications +# that need different build settings. +apply_standard_settings(${BINARY_NAME}) + +# Add preprocessor definitions for the build version. +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}") +target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}") + +# Disable Windows macros that collide with C++ standard library functions. +target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX") + +# Add dependency libraries and include directories. Add any application-specific +# dependencies here. +target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app) +target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}") + +# Run the Flutter tool portions of the build. This must not be removed. +add_dependencies(${BINARY_NAME} flutter_assemble) diff --git a/windows/runner/Runner.rc b/windows/runner/Runner.rc new file mode 100755 index 0000000..9bb33a0 --- /dev/null +++ b/windows/runner/Runner.rc @@ -0,0 +1,121 @@ +// Microsoft Visual C++ generated resource script. +// +#pragma code_page(65001) +#include "resource.h" + +#define APSTUDIO_READONLY_SYMBOLS +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 2 resource. +// +#include "winres.h" + +///////////////////////////////////////////////////////////////////////////// +#undef APSTUDIO_READONLY_SYMBOLS + +///////////////////////////////////////////////////////////////////////////// +// English (United States) resources + +#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU) +LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US + +#ifdef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// TEXTINCLUDE +// + +1 TEXTINCLUDE +BEGIN + "resource.h\0" +END + +2 TEXTINCLUDE +BEGIN + "#include ""winres.h""\r\n" + "\0" +END + +3 TEXTINCLUDE +BEGIN + "\r\n" + "\0" +END + +#endif // APSTUDIO_INVOKED + + +///////////////////////////////////////////////////////////////////////////// +// +// Icon +// + +// Icon with lowest ID value placed first to ensure application icon +// remains consistent on all systems. +IDI_APP_ICON ICON "resources\\app_icon.ico" + + +///////////////////////////////////////////////////////////////////////////// +// +// Version +// + +#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD) +#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD +#else +#define VERSION_AS_NUMBER 1,0,0,0 +#endif + +#if defined(FLUTTER_VERSION) +#define VERSION_AS_STRING FLUTTER_VERSION +#else +#define VERSION_AS_STRING "1.0.0" +#endif + +VS_VERSION_INFO VERSIONINFO + FILEVERSION VERSION_AS_NUMBER + PRODUCTVERSION VERSION_AS_NUMBER + FILEFLAGSMASK VS_FFI_FILEFLAGSMASK +#ifdef _DEBUG + FILEFLAGS VS_FF_DEBUG +#else + FILEFLAGS 0x0L +#endif + FILEOS VOS__WINDOWS32 + FILETYPE VFT_APP + FILESUBTYPE 0x0L +BEGIN + BLOCK "StringFileInfo" + BEGIN + BLOCK "040904e4" + BEGIN + VALUE "CompanyName", "cn.isekai.wiki" "\0" + VALUE "FileDescription", "isekai_wiki" "\0" + VALUE "FileVersion", VERSION_AS_STRING "\0" + VALUE "InternalName", "isekai_wiki" "\0" + VALUE "LegalCopyright", "Copyright (C) 2022 cn.isekai.wiki. All rights reserved." "\0" + VALUE "OriginalFilename", "isekai_wiki.exe" "\0" + VALUE "ProductName", "isekai_wiki" "\0" + VALUE "ProductVersion", VERSION_AS_STRING "\0" + END + END + BLOCK "VarFileInfo" + BEGIN + VALUE "Translation", 0x409, 1252 + END +END + +#endif // English (United States) resources +///////////////////////////////////////////////////////////////////////////// + + + +#ifndef APSTUDIO_INVOKED +///////////////////////////////////////////////////////////////////////////// +// +// Generated from the TEXTINCLUDE 3 resource. +// + + +///////////////////////////////////////////////////////////////////////////// +#endif // not APSTUDIO_INVOKED diff --git a/windows/runner/flutter_window.cpp b/windows/runner/flutter_window.cpp new file mode 100755 index 0000000..b43b909 --- /dev/null +++ b/windows/runner/flutter_window.cpp @@ -0,0 +1,61 @@ +#include "flutter_window.h" + +#include + +#include "flutter/generated_plugin_registrant.h" + +FlutterWindow::FlutterWindow(const flutter::DartProject& project) + : project_(project) {} + +FlutterWindow::~FlutterWindow() {} + +bool FlutterWindow::OnCreate() { + if (!Win32Window::OnCreate()) { + return false; + } + + RECT frame = GetClientArea(); + + // The size here must match the window dimensions to avoid unnecessary surface + // creation / destruction in the startup path. + flutter_controller_ = std::make_unique( + frame.right - frame.left, frame.bottom - frame.top, project_); + // Ensure that basic setup of the controller was successful. + if (!flutter_controller_->engine() || !flutter_controller_->view()) { + return false; + } + RegisterPlugins(flutter_controller_->engine()); + SetChildContent(flutter_controller_->view()->GetNativeWindow()); + return true; +} + +void FlutterWindow::OnDestroy() { + if (flutter_controller_) { + flutter_controller_ = nullptr; + } + + Win32Window::OnDestroy(); +} + +LRESULT +FlutterWindow::MessageHandler(HWND hwnd, UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + // Give Flutter, including plugins, an opportunity to handle window messages. + if (flutter_controller_) { + std::optional result = + flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam, + lparam); + if (result) { + return *result; + } + } + + switch (message) { + case WM_FONTCHANGE: + flutter_controller_->engine()->ReloadSystemFonts(); + break; + } + + return Win32Window::MessageHandler(hwnd, message, wparam, lparam); +} diff --git a/windows/runner/flutter_window.h b/windows/runner/flutter_window.h new file mode 100755 index 0000000..6da0652 --- /dev/null +++ b/windows/runner/flutter_window.h @@ -0,0 +1,33 @@ +#ifndef RUNNER_FLUTTER_WINDOW_H_ +#define RUNNER_FLUTTER_WINDOW_H_ + +#include +#include + +#include + +#include "win32_window.h" + +// A window that does nothing but host a Flutter view. +class FlutterWindow : public Win32Window { + public: + // Creates a new FlutterWindow hosting a Flutter view running |project|. + explicit FlutterWindow(const flutter::DartProject& project); + virtual ~FlutterWindow(); + + protected: + // Win32Window: + bool OnCreate() override; + void OnDestroy() override; + LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam, + LPARAM const lparam) noexcept override; + + private: + // The project to run. + flutter::DartProject project_; + + // The Flutter instance hosted by this window. + std::unique_ptr flutter_controller_; +}; + +#endif // RUNNER_FLUTTER_WINDOW_H_ diff --git a/windows/runner/main.cpp b/windows/runner/main.cpp new file mode 100755 index 0000000..08f2f68 --- /dev/null +++ b/windows/runner/main.cpp @@ -0,0 +1,43 @@ +#include +#include +#include + +#include "flutter_window.h" +#include "utils.h" + +int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev, + _In_ wchar_t *command_line, _In_ int show_command) { + // Attach to console when present (e.g., 'flutter run') or create a + // new console when running with a debugger. + if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) { + CreateAndAttachConsole(); + } + + // Initialize COM, so that it is available for use in the library and/or + // plugins. + ::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED); + + flutter::DartProject project(L"data"); + + std::vector command_line_arguments = + GetCommandLineArguments(); + + project.set_dart_entrypoint_arguments(std::move(command_line_arguments)); + + FlutterWindow window(project); + Win32Window::Point origin(10, 10); + Win32Window::Size size(1280, 720); + if (!window.CreateAndShow(L"isekai_wiki", origin, size)) { + return EXIT_FAILURE; + } + window.SetQuitOnClose(true); + + ::MSG msg; + while (::GetMessage(&msg, nullptr, 0, 0)) { + ::TranslateMessage(&msg); + ::DispatchMessage(&msg); + } + + ::CoUninitialize(); + return EXIT_SUCCESS; +} diff --git a/windows/runner/resource.h b/windows/runner/resource.h new file mode 100755 index 0000000..66a65d1 --- /dev/null +++ b/windows/runner/resource.h @@ -0,0 +1,16 @@ +//{{NO_DEPENDENCIES}} +// Microsoft Visual C++ generated include file. +// Used by Runner.rc +// +#define IDI_APP_ICON 101 + +// Next default values for new objects +// +#ifdef APSTUDIO_INVOKED +#ifndef APSTUDIO_READONLY_SYMBOLS +#define _APS_NEXT_RESOURCE_VALUE 102 +#define _APS_NEXT_COMMAND_VALUE 40001 +#define _APS_NEXT_CONTROL_VALUE 1001 +#define _APS_NEXT_SYMED_VALUE 101 +#endif +#endif diff --git a/windows/runner/resources/app_icon.ico b/windows/runner/resources/app_icon.ico new file mode 100755 index 0000000..c04e20c Binary files /dev/null and b/windows/runner/resources/app_icon.ico differ diff --git a/windows/runner/runner.exe.manifest b/windows/runner/runner.exe.manifest new file mode 100755 index 0000000..a42ea76 --- /dev/null +++ b/windows/runner/runner.exe.manifest @@ -0,0 +1,20 @@ + + + + + PerMonitorV2 + + + + + + + + + + + + + + + diff --git a/windows/runner/utils.cpp b/windows/runner/utils.cpp new file mode 100755 index 0000000..f5bf9fa --- /dev/null +++ b/windows/runner/utils.cpp @@ -0,0 +1,64 @@ +#include "utils.h" + +#include +#include +#include +#include + +#include + +void CreateAndAttachConsole() { + if (::AllocConsole()) { + FILE *unused; + if (freopen_s(&unused, "CONOUT$", "w", stdout)) { + _dup2(_fileno(stdout), 1); + } + if (freopen_s(&unused, "CONOUT$", "w", stderr)) { + _dup2(_fileno(stdout), 2); + } + std::ios::sync_with_stdio(); + FlutterDesktopResyncOutputStreams(); + } +} + +std::vector GetCommandLineArguments() { + // Convert the UTF-16 command line arguments to UTF-8 for the Engine to use. + int argc; + wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc); + if (argv == nullptr) { + return std::vector(); + } + + std::vector command_line_arguments; + + // Skip the first argument as it's the binary name. + for (int i = 1; i < argc; i++) { + command_line_arguments.push_back(Utf8FromUtf16(argv[i])); + } + + ::LocalFree(argv); + + return command_line_arguments; +} + +std::string Utf8FromUtf16(const wchar_t* utf16_string) { + if (utf16_string == nullptr) { + return std::string(); + } + int target_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, nullptr, 0, nullptr, nullptr); + std::string utf8_string; + if (target_length == 0 || target_length > utf8_string.max_size()) { + return utf8_string; + } + utf8_string.resize(target_length); + int converted_length = ::WideCharToMultiByte( + CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string, + -1, utf8_string.data(), + target_length, nullptr, nullptr); + if (converted_length == 0) { + return std::string(); + } + return utf8_string; +} diff --git a/windows/runner/utils.h b/windows/runner/utils.h new file mode 100755 index 0000000..3879d54 --- /dev/null +++ b/windows/runner/utils.h @@ -0,0 +1,19 @@ +#ifndef RUNNER_UTILS_H_ +#define RUNNER_UTILS_H_ + +#include +#include + +// Creates a console for the process, and redirects stdout and stderr to +// it for both the runner and the Flutter library. +void CreateAndAttachConsole(); + +// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string +// encoded in UTF-8. Returns an empty std::string on failure. +std::string Utf8FromUtf16(const wchar_t* utf16_string); + +// Gets the command line arguments passed in as a std::vector, +// encoded in UTF-8. Returns an empty std::vector on failure. +std::vector GetCommandLineArguments(); + +#endif // RUNNER_UTILS_H_ diff --git a/windows/runner/win32_window.cpp b/windows/runner/win32_window.cpp new file mode 100755 index 0000000..c10f08d --- /dev/null +++ b/windows/runner/win32_window.cpp @@ -0,0 +1,245 @@ +#include "win32_window.h" + +#include + +#include "resource.h" + +namespace { + +constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW"; + +// The number of Win32Window objects that currently exist. +static int g_active_window_count = 0; + +using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd); + +// Scale helper to convert logical scaler values to physical using passed in +// scale factor +int Scale(int source, double scale_factor) { + return static_cast(source * scale_factor); +} + +// Dynamically loads the |EnableNonClientDpiScaling| from the User32 module. +// This API is only needed for PerMonitor V1 awareness mode. +void EnableFullDpiSupportIfAvailable(HWND hwnd) { + HMODULE user32_module = LoadLibraryA("User32.dll"); + if (!user32_module) { + return; + } + auto enable_non_client_dpi_scaling = + reinterpret_cast( + GetProcAddress(user32_module, "EnableNonClientDpiScaling")); + if (enable_non_client_dpi_scaling != nullptr) { + enable_non_client_dpi_scaling(hwnd); + FreeLibrary(user32_module); + } +} + +} // namespace + +// Manages the Win32Window's window class registration. +class WindowClassRegistrar { + public: + ~WindowClassRegistrar() = default; + + // Returns the singleton registar instance. + static WindowClassRegistrar* GetInstance() { + if (!instance_) { + instance_ = new WindowClassRegistrar(); + } + return instance_; + } + + // Returns the name of the window class, registering the class if it hasn't + // previously been registered. + const wchar_t* GetWindowClass(); + + // Unregisters the window class. Should only be called if there are no + // instances of the window. + void UnregisterWindowClass(); + + private: + WindowClassRegistrar() = default; + + static WindowClassRegistrar* instance_; + + bool class_registered_ = false; +}; + +WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr; + +const wchar_t* WindowClassRegistrar::GetWindowClass() { + if (!class_registered_) { + WNDCLASS window_class{}; + window_class.hCursor = LoadCursor(nullptr, IDC_ARROW); + window_class.lpszClassName = kWindowClassName; + window_class.style = CS_HREDRAW | CS_VREDRAW; + window_class.cbClsExtra = 0; + window_class.cbWndExtra = 0; + window_class.hInstance = GetModuleHandle(nullptr); + window_class.hIcon = + LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON)); + window_class.hbrBackground = 0; + window_class.lpszMenuName = nullptr; + window_class.lpfnWndProc = Win32Window::WndProc; + RegisterClass(&window_class); + class_registered_ = true; + } + return kWindowClassName; +} + +void WindowClassRegistrar::UnregisterWindowClass() { + UnregisterClass(kWindowClassName, nullptr); + class_registered_ = false; +} + +Win32Window::Win32Window() { + ++g_active_window_count; +} + +Win32Window::~Win32Window() { + --g_active_window_count; + Destroy(); +} + +bool Win32Window::CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size) { + Destroy(); + + const wchar_t* window_class = + WindowClassRegistrar::GetInstance()->GetWindowClass(); + + const POINT target_point = {static_cast(origin.x), + static_cast(origin.y)}; + HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST); + UINT dpi = FlutterDesktopGetDpiForMonitor(monitor); + double scale_factor = dpi / 96.0; + + HWND window = CreateWindow( + window_class, title.c_str(), WS_OVERLAPPEDWINDOW | WS_VISIBLE, + Scale(origin.x, scale_factor), Scale(origin.y, scale_factor), + Scale(size.width, scale_factor), Scale(size.height, scale_factor), + nullptr, nullptr, GetModuleHandle(nullptr), this); + + if (!window) { + return false; + } + + return OnCreate(); +} + +// static +LRESULT CALLBACK Win32Window::WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + if (message == WM_NCCREATE) { + auto window_struct = reinterpret_cast(lparam); + SetWindowLongPtr(window, GWLP_USERDATA, + reinterpret_cast(window_struct->lpCreateParams)); + + auto that = static_cast(window_struct->lpCreateParams); + EnableFullDpiSupportIfAvailable(window); + that->window_handle_ = window; + } else if (Win32Window* that = GetThisFromHandle(window)) { + return that->MessageHandler(window, message, wparam, lparam); + } + + return DefWindowProc(window, message, wparam, lparam); +} + +LRESULT +Win32Window::MessageHandler(HWND hwnd, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept { + switch (message) { + case WM_DESTROY: + window_handle_ = nullptr; + Destroy(); + if (quit_on_close_) { + PostQuitMessage(0); + } + return 0; + + case WM_DPICHANGED: { + auto newRectSize = reinterpret_cast(lparam); + LONG newWidth = newRectSize->right - newRectSize->left; + LONG newHeight = newRectSize->bottom - newRectSize->top; + + SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth, + newHeight, SWP_NOZORDER | SWP_NOACTIVATE); + + return 0; + } + case WM_SIZE: { + RECT rect = GetClientArea(); + if (child_content_ != nullptr) { + // Size and position the child window. + MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left, + rect.bottom - rect.top, TRUE); + } + return 0; + } + + case WM_ACTIVATE: + if (child_content_ != nullptr) { + SetFocus(child_content_); + } + return 0; + } + + return DefWindowProc(window_handle_, message, wparam, lparam); +} + +void Win32Window::Destroy() { + OnDestroy(); + + if (window_handle_) { + DestroyWindow(window_handle_); + window_handle_ = nullptr; + } + if (g_active_window_count == 0) { + WindowClassRegistrar::GetInstance()->UnregisterWindowClass(); + } +} + +Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept { + return reinterpret_cast( + GetWindowLongPtr(window, GWLP_USERDATA)); +} + +void Win32Window::SetChildContent(HWND content) { + child_content_ = content; + SetParent(content, window_handle_); + RECT frame = GetClientArea(); + + MoveWindow(content, frame.left, frame.top, frame.right - frame.left, + frame.bottom - frame.top, true); + + SetFocus(child_content_); +} + +RECT Win32Window::GetClientArea() { + RECT frame; + GetClientRect(window_handle_, &frame); + return frame; +} + +HWND Win32Window::GetHandle() { + return window_handle_; +} + +void Win32Window::SetQuitOnClose(bool quit_on_close) { + quit_on_close_ = quit_on_close; +} + +bool Win32Window::OnCreate() { + // No-op; provided for subclasses. + return true; +} + +void Win32Window::OnDestroy() { + // No-op; provided for subclasses. +} diff --git a/windows/runner/win32_window.h b/windows/runner/win32_window.h new file mode 100755 index 0000000..17ba431 --- /dev/null +++ b/windows/runner/win32_window.h @@ -0,0 +1,98 @@ +#ifndef RUNNER_WIN32_WINDOW_H_ +#define RUNNER_WIN32_WINDOW_H_ + +#include + +#include +#include +#include + +// A class abstraction for a high DPI-aware Win32 Window. Intended to be +// inherited from by classes that wish to specialize with custom +// rendering and input handling +class Win32Window { + public: + struct Point { + unsigned int x; + unsigned int y; + Point(unsigned int x, unsigned int y) : x(x), y(y) {} + }; + + struct Size { + unsigned int width; + unsigned int height; + Size(unsigned int width, unsigned int height) + : width(width), height(height) {} + }; + + Win32Window(); + virtual ~Win32Window(); + + // Creates and shows a win32 window with |title| and position and size using + // |origin| and |size|. New windows are created on the default monitor. Window + // sizes are specified to the OS in physical pixels, hence to ensure a + // consistent size to will treat the width height passed in to this function + // as logical pixels and scale to appropriate for the default monitor. Returns + // true if the window was created successfully. + bool CreateAndShow(const std::wstring& title, + const Point& origin, + const Size& size); + + // Release OS resources associated with window. + void Destroy(); + + // Inserts |content| into the window tree. + void SetChildContent(HWND content); + + // Returns the backing Window handle to enable clients to set icon and other + // window properties. Returns nullptr if the window has been destroyed. + HWND GetHandle(); + + // If true, closing this window will quit the application. + void SetQuitOnClose(bool quit_on_close); + + // Return a RECT representing the bounds of the current client area. + RECT GetClientArea(); + + protected: + // Processes and route salient window messages for mouse handling, + // size change and DPI. Delegates handling of these to member overloads that + // inheriting classes can handle. + virtual LRESULT MessageHandler(HWND window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Called when CreateAndShow is called, allowing subclass window-related + // setup. Subclasses should return false if setup fails. + virtual bool OnCreate(); + + // Called when Destroy is called. + virtual void OnDestroy(); + + private: + friend class WindowClassRegistrar; + + // OS callback called by message pump. Handles the WM_NCCREATE message which + // is passed when the non-client area is being created and enables automatic + // non-client DPI scaling so that the non-client area automatically + // responsponds to changes in DPI. All other messages are handled by + // MessageHandler. + static LRESULT CALLBACK WndProc(HWND const window, + UINT const message, + WPARAM const wparam, + LPARAM const lparam) noexcept; + + // Retrieves a class instance pointer for |window| + static Win32Window* GetThisFromHandle(HWND const window) noexcept; + + bool quit_on_close_ = false; + + // window handle for top level window. + HWND window_handle_ = nullptr; + + // window handle for hosted content. + HWND child_content_ = nullptr; +}; + +#endif // RUNNER_WIN32_WINDOW_H_