Repository: niuhuan/nhentai-cross
Branch: master
Commit: e253a48a0804
Files: 173
Total size: 378.6 KB
Directory structure:
gitextract_vgtt9c51/
├── .github/
│ └── workflows/
│ └── Release.yml
├── .gitignore
├── .metadata
├── LICENSE
├── README-zh.md
├── README.md
├── analysis_options.yaml
├── android/
│ ├── .gitignore
│ ├── app/
│ │ ├── build.gradle
│ │ └── src/
│ │ ├── debug/
│ │ │ └── AndroidManifest.xml
│ │ ├── main/
│ │ │ ├── AndroidManifest.xml
│ │ │ ├── kotlin/
│ │ │ │ └── niuhuan/
│ │ │ │ └── nhentai/
│ │ │ │ └── MainActivity.kt
│ │ │ └── res/
│ │ │ ├── drawable/
│ │ │ │ └── launch_background.xml
│ │ │ ├── drawable-v21/
│ │ │ │ └── launch_background.xml
│ │ │ ├── values/
│ │ │ │ └── styles.xml
│ │ │ └── values-night/
│ │ │ └── styles.xml
│ │ └── profile/
│ │ └── AndroidManifest.xml
│ ├── build.gradle
│ ├── gradle/
│ │ └── wrapper/
│ │ └── gradle-wrapper.properties
│ ├── gradle.properties
│ └── settings.gradle
├── ci/
│ ├── cmd/
│ │ ├── check_asset/
│ │ │ └── main.go
│ │ ├── check_release/
│ │ │ └── main.go
│ │ └── upload_asset/
│ │ └── main.go
│ ├── commons/
│ │ └── types.go
│ ├── go.mod
│ ├── linux_font.yaml
│ ├── version.code.txt
│ └── version.info.txt
├── go/
│ ├── .gitignore
│ ├── cmd/
│ │ ├── init.go
│ │ ├── main.go
│ │ ├── options.go
│ │ └── plugin.go
│ ├── go.mod
│ ├── go.sum
│ ├── hover.yaml
│ ├── mobile/
│ │ ├── bind-android-debug.sh
│ │ ├── bind-android.sh
│ │ ├── bind-ios-debug.sh
│ │ ├── bind-ios.sh
│ │ ├── lib/
│ │ │ └── .keep
│ │ └── mobile.go
│ ├── nhentai/
│ │ ├── client.go
│ │ ├── common.go
│ │ ├── constant/
│ │ │ ├── constant.go
│ │ │ ├── os.go
│ │ │ └── time.go
│ │ ├── database/
│ │ │ ├── active/
│ │ │ │ └── active.go
│ │ │ ├── cache/
│ │ │ │ └── cache.go
│ │ │ └── properties/
│ │ │ └── properties.go
│ │ ├── decodes.go
│ │ ├── download.go
│ │ ├── locks.go
│ │ └── nhentai.go
│ └── packaging/
│ ├── darwin-bundle/
│ │ └── {{.applicationName}} {{.version}}.app/
│ │ └── Contents/
│ │ └── Info.plist.tmpl
│ └── linux-appimage/
│ ├── AppRun.tmpl
│ └── {{.packageName}}.desktop.tmpl
├── ios/
│ ├── .gitignore
│ ├── Flutter/
│ │ ├── AppFrameworkInfo.plist
│ │ ├── Debug.xcconfig
│ │ └── Release.xcconfig
│ ├── Podfile
│ ├── Runner/
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets/
│ │ │ ├── AppIcon.appiconset/
│ │ │ │ └── Contents.json
│ │ │ └── LaunchImage.imageset/
│ │ │ ├── Contents.json
│ │ │ └── README.md
│ │ ├── Base.lproj/
│ │ │ ├── LaunchScreen.storyboard
│ │ │ └── Main.storyboard
│ │ ├── Info.plist
│ │ └── Runner-Bridging-Header.h
│ ├── Runner.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ ├── contents.xcworkspacedata
│ │ │ └── xcshareddata/
│ │ │ ├── IDEWorkspaceChecks.plist
│ │ │ └── WorkspaceSettings.xcsettings
│ │ └── xcshareddata/
│ │ └── xcschemes/
│ │ └── Runner.xcscheme
│ └── Runner.xcworkspace/
│ ├── contents.xcworkspacedata
│ └── xcshareddata/
│ ├── IDEWorkspaceChecks.plist
│ └── WorkspaceSettings.xcsettings
├── l10n.yaml
├── lib/
│ ├── basic/
│ │ ├── channels/
│ │ │ └── nhentai.dart
│ │ ├── common/
│ │ │ ├── common.dart
│ │ │ ├── cross.dart
│ │ │ └── error_types.dart
│ │ ├── configs/
│ │ │ ├── proxy.dart
│ │ │ ├── reader_direction.dart
│ │ │ ├── reader_type.dart
│ │ │ ├── themes.dart
│ │ │ └── version.dart
│ │ └── entities/
│ │ └── entities.dart
│ ├── l10n/
│ │ ├── app_en.arb
│ │ └── app_zh.arb
│ ├── main.dart
│ ├── main_desktop.dart
│ └── screens/
│ ├── comic_downloads_screen.dart
│ ├── comic_info_screen.dart
│ ├── comic_reader_screen.dart
│ ├── comic_search_screen.dart
│ ├── comics_screen.dart
│ ├── components/
│ │ ├── Badged.dart
│ │ ├── actions.dart
│ │ ├── content_builder.dart
│ │ ├── content_error.dart
│ │ ├── content_loading.dart
│ │ ├── images.dart
│ │ ├── mouse_and_touch_scroll_behavior.dart
│ │ └── pager.dart
│ ├── file_photo_view_screen.dart
│ ├── init_screen.dart
│ ├── settings_screen.dart
│ └── webview_screen.dart
├── linux/
│ ├── .gitignore
│ ├── CMakeLists.txt
│ ├── flutter/
│ │ ├── CMakeLists.txt
│ │ ├── generated_plugin_registrant.cc
│ │ ├── generated_plugin_registrant.h
│ │ └── generated_plugins.cmake
│ ├── main.cc
│ ├── my_application.cc
│ └── my_application.h
├── macos/
│ ├── .gitignore
│ ├── Flutter/
│ │ ├── Flutter-Debug.xcconfig
│ │ ├── Flutter-Release.xcconfig
│ │ └── GeneratedPluginRegistrant.swift
│ ├── Podfile
│ ├── Runner/
│ │ ├── AppDelegate.swift
│ │ ├── Assets.xcassets/
│ │ │ └── AppIcon.appiconset/
│ │ │ └── Contents.json
│ │ ├── Base.lproj/
│ │ │ └── MainMenu.xib
│ │ ├── Configs/
│ │ │ ├── AppInfo.xcconfig
│ │ │ ├── Debug.xcconfig
│ │ │ ├── Release.xcconfig
│ │ │ └── Warnings.xcconfig
│ │ ├── DebugProfile.entitlements
│ │ ├── Info.plist
│ │ ├── MainFlutterWindow.swift
│ │ └── Release.entitlements
│ ├── Runner.xcodeproj/
│ │ ├── project.pbxproj
│ │ ├── project.xcworkspace/
│ │ │ └── xcshareddata/
│ │ │ └── IDEWorkspaceChecks.plist
│ │ └── xcshareddata/
│ │ └── xcschemes/
│ │ └── Runner.xcscheme
│ └── Runner.xcworkspace/
│ ├── contents.xcworkspacedata
│ └── xcshareddata/
│ └── IDEWorkspaceChecks.plist
├── pubspec.yaml
├── scripts/
│ ├── README.md
│ ├── bind-android-debug.sh
│ ├── bind-ios-arm64.sh
│ ├── bind-ios.sh
│ ├── build-apk-arm.sh
│ ├── build-apk-arm64.sh
│ ├── build-apk-x64.sh
│ ├── build-apk-x86.sh
│ ├── build-ipa.sh
│ ├── build-macos-dmg.sh
│ ├── sign-apk-github-actions.sh
│ ├── thin-payload.sh
│ └── version.sh
├── test/
│ └── widget_test.dart
└── windows/
├── .gitignore
├── CMakeLists.txt
├── flutter/
│ ├── CMakeLists.txt
│ ├── generated_plugin_registrant.cc
│ ├── generated_plugin_registrant.h
│ └── generated_plugins.cmake
└── runner/
├── CMakeLists.txt
├── Runner.rc
├── flutter_window.cpp
├── flutter_window.h
├── main.cpp
├── resource.h
├── runner.exe.manifest
├── utils.cpp
├── utils.h
├── win32_window.cpp
└── win32_window.h
================================================
FILE CONTENTS
================================================
================================================
FILE: .github/workflows/Release.yml
================================================
name: Release
on:
workflow_dispatch:
env:
go_version: '1.17'
flutter_channel: 'stable'
GH_TOKEN: ${{ secrets.GH_TOKEN }}
jobs:
ci-pass:
name: CI is green
runs-on: ubuntu-latest
needs:
- check_release
- build_release_assets
steps:
- run: exit 0
check_release:
name: Check release
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
with:
repository: ${{ github.event.inputs.repo }}
ref: 'master'
- name: Checkout submodules
run: git submodule update --init --recursive
- uses: actions/setup-go@v2
with:
go-version: ${{ env.go_version }}
- name: Check release
run: |
cd ci
go run ./cmd/check_release
build_release_assets:
name: Build release assets
needs:
- check_release
strategy:
fail-fast: false
matrix:
config:
- target: linux
host: ubuntu-latest
flutter_version: '2.10.3'
- target: windows
host: windows-latest
flutter_version: '2.10.3'
- target: macos
host: macos-12
flutter_version: '2.10.3'
- target: ios
host: macos-12
flutter_version: '3.3.4'
- target: android-arm32
host: ubuntu-latest
flutter_version: '3.3.4'
- target: android-arm64
host: ubuntu-latest
flutter_version: '3.3.4'
- target: android-x86_64
host: ubuntu-latest
flutter_version: '3.3.4'
runs-on: ${{ matrix.config.host }}
env:
TARGET: ${{ matrix.config.target }}
flutter_version: ${{ matrix.config.flutter_version }}
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup golang
uses: actions/setup-go@v2
with:
go-version: ${{ env.go_version }}
- id: check_asset
name: Check asset
run: |
cd ci
go run ./cmd/check_asset
- name: Setup flutter
if: steps.check_asset.outputs.skip_build != 'true'
uses: subosito/flutter-action@v2
with:
channel: ${{ env.flutter_channel }}
flutter-version: ${{ env.flutter_version }}
architecture: x64
- name: Setup java (Android)
if: steps.check_asset.outputs.skip_build != 'true' && ( matrix.config.target == 'android-arm32' || matrix.config.target == 'android-arm64' || matrix.config.target == 'android-x86_64' )
uses: actions/setup-java@v3
with:
java-version: 8
distribution: 'zulu'
- name: Setup android tools (Android)
if: steps.check_asset.outputs.skip_build != 'true' && ( matrix.config.target == 'android-arm32' || matrix.config.target == 'android-arm64' || matrix.config.target == 'android-x86_64' )
uses: maxim-lobanov/setup-android-tools@v1
with:
packages: |
platform-tools
platforms;android-32
build-tools;30.0.2
ndk;22.1.7171670
- name: Setup msys2 (Windows)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'windows'
uses: msys2/setup-msys2@v2
with:
install: gcc make
- name: Install dependencies (Linux)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'linux'
env:
ACTIONS_ALLOW_UNSECURE_COMMANDS: 'true'
run: |
curl -JOL https://github.com/AppImage/AppImageKit/releases/download/continuous/appimagetool-x86_64.AppImage
chmod a+x appimagetool-x86_64.AppImage
mkdir -p ${GITHUB_WORKSPACE}/bin
mv appimagetool-x86_64.AppImage ${GITHUB_WORKSPACE}/bin/appimagetool
echo ::add-path::${GITHUB_WORKSPACE}/bin
sudo apt-get update
sudo apt-get install -y libgl1-mesa-dev xorg-dev
- name: Install hover (desktop)
if: steps.check_asset.outputs.skip_build != 'true' && ( matrix.config.target == 'linux' || matrix.config.target == 'windows' || matrix.config.target == 'macos')
run: |
go install github.com/go-flutter-desktop/hover@latest
- name: Install go mobile (mobile)
if: steps.check_asset.outputs.skip_build != 'true' && ( matrix.config.target == 'ios' || matrix.config.target == 'android-arm64' || matrix.config.target == 'android-arm32' || matrix.config.target == 'android-x86_64' )
run: |
go install golang.org/x/mobile/cmd/gomobile@latest
- name: Set-Version (All)
if: steps.check_asset.outputs.skip_build != 'true'
run: |
cd ci
cp version.code.txt ../lib/assets/version.txt
- name: Upgrade deps version (Android)
if: steps.check_asset.outputs.skip_build != 'true' && !startsWith(matrix.config.host, 'macos') && startsWith(matrix.config.flutter_version, '3')
run: |
sed -i "s/another_xlider: 1.0.1+2/another_xlider: ^1.0.1+2/g" pubspec.yaml
sed -i "s/flutter_styled_toast: 2.0.0/flutter_styled_toast: ^2.0.0/g" pubspec.yaml
sed -i "s/filesystem_picker: 2.0.0/filesystem_picker: ^2.0.0/g" pubspec.yaml
- name: Build (windows)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'windows'
run: |
hover build windows
cd go\build\outputs\windows-release
DEL flutter_engine.pdb
DEL flutter_engine.exp
DEL flutter_engine.lib
Compress-Archive * ../../../../build/build.zip
- name: Build (macos)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'macos'
run: |
hover build darwin-dmg
mv go/build/outputs/darwin-dmg-release/*.dmg build/build.dmg
- name: Build (linux)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'linux'
run: |
curl -JOL https://github.com/junmer/source-han-serif-ttf/raw/master/SubsetTTF/CN/SourceHanSerifCN-Regular.ttf
mkdir -p fonts
mv SourceHanSerifCN-Regular.ttf fonts/Roboto.ttf
cat ci/linux_font.yaml >> pubspec.yaml
hover build linux-appimage
mv go/build/outputs/linux-appimage-release/*.AppImage build/build.AppImage
- name: Build (ios)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'ios'
run: |
/usr/libexec/PlistBuddy -c 'Add :application-identifier string niuhuan.nhentai' ios/Runner/Info.plist
sh scripts/build-ipa.sh
- name: Build (android-arm32)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'android-arm32'
run: |
sh scripts/build-apk-arm.sh
- name: Build (android-arm64)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'android-arm64'
run: |
sh scripts/build-apk-arm64.sh
- name: Build (android-x86_64)
if: steps.check_asset.outputs.skip_build != 'true' && matrix.config.target == 'android-x86_64'
run: |
sh scripts/build-apk-x64.sh
- name: Sign APK (Android)
if: steps.check_asset.outputs.skip_build != 'true' && ( matrix.config.target == 'android-arm32' || matrix.config.target == 'android-arm64' || matrix.config.target == 'android-x86_64' )
env:
KEY_FILE_BASE64: ${{ secrets.KEY_FILE_BASE64 }}
KEY_PASSWORD: ${{ secrets.KEY_PASSWORD }}
run: |
sh scripts/sign-apk-github-actions.sh
- name: Upload Asset (All)
if: steps.check_asset.outputs.skip_build != 'true'
run: |
cd ci
go run ./cmd/upload_asset
================================================
FILE: .gitignore
================================================
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.buildlog/
.history
.svn/
# 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/
# Web related
lib/generated_plugin_registrant.dart
# 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
/go/mobile/lib/*.jar
/go/mobile/lib/*.aar
/go/mobile/lib/*.xcframework/
/lib/assets/version.txt
desiredFileName.txt
================================================
FILE: .metadata
================================================
# This file tracks properties of this Flutter project.
# Used by Flutter tool to assess capabilities and perform upgrades etc.
#
# This file should be version controlled and should not be manually edited.
version:
revision: 18116933e77adc82f80866c928266a5b4f1ed645
channel: stable
project_type: app
================================================
FILE: LICENSE
================================================
Copyright (c) 2021-2022 niuhuan
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
================================================
FILE: README-zh.md
================================================
# NHENTAI-CROSS
## [English](README.md) | 简体中文
[](https://raw.githubusercontent.com/niuhuan/nhentai-cross/master/LICENSE)
[](https://github.com/niuhuan/nhentai-cross/releases)
[](https://github.com/niuhuan/nhentai-cross/releases)
一个美观且跨平台的*NHentai客户端*,支持桌面端与移动端(Mac/Windows/Linux/Android/IOS)。
内置DNS拦截器,可以让部分国家和地区免代理使用网络加速,请您在遵守当地法律的情况下使用。(需要在设置中开启)
如果您觉得此软件对您有帮助,可以star进行支持。同时欢迎您issue,一起让软件变得更好。
仓库地址 [https://github.com/niuhuan/nhentai-cross](https://github.com/niuhuan/nhentai-cross)
## 使用前必读
- 根据地区的不同DNS拦截器不一定有效, 请使用科学上网测试本软件的可用性
## 软件截图
#### 漫画列表

#### 漫画详情

#### 漫画阅读器

## 技术架构

================================================
FILE: README.md
================================================
# NHENTAI-CROSS
## English | [简体中文](README-zh.md)
[](https://raw.githubusercontent.com/niuhuan/nhentai-cross/master/LICENSE)
[](https://github.com/niuhuan/nhentai-cross/releases)
[](https://github.com/niuhuan/nhentai-cross/releases)
A beautiful and cross platform *NHentai Client*. Support desktop and mobile phone (Mac/Windows/Linux/Android/IOS).
## Must readme
The official website uses the page to prevent DDoS attacks.
## Captures
#### Comic list

#### Comic info

#### Comic reader

## Technical architecture

================================================
FILE: analysis_options.yaml
================================================
# 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
================================================
FILE: android/.gitignore
================================================
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
# Remember to never publicly share your keystore.
# See https://flutter.dev/docs/deployment/android#reference-the-keystore-from-the-app
key.properties
**/*.keystore
**/*.jks
================================================
FILE: android/app/build.gradle
================================================
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
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 "niuhuan.nhentai"
minSdkVersion 19
targetSdkVersion 31
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"
implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9'
implementation fileTree(dir: "../../go/mobile/lib", include: ["*.jar", "*.aar"])
}
================================================
FILE: android/app/src/debug/AndroidManifest.xml
================================================
================================================
FILE: android/app/src/main/AndroidManifest.xml
================================================
================================================
FILE: android/app/src/main/kotlin/niuhuan/nhentai/MainActivity.kt
================================================
package niuhuan.nhentai
import android.content.ContentValues
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.util.DisplayMetrics
import android.util.Log
import android.view.Display
import android.view.KeyEvent
import android.view.WindowManager
import androidx.annotation.NonNull
import androidx.annotation.RequiresApi
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.engine.FlutterEngine
import io.flutter.plugin.common.EventChannel
import io.flutter.plugin.common.MethodChannel
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.newSingleThreadContext
import kotlinx.coroutines.sync.Mutex
import mobile.Mobile
import java.io.ByteArrayOutputStream
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream
import java.nio.file.Files
import java.util.concurrent.Executors
class MainActivity: FlutterActivity() {
// 为什么换成换成线程池而不继续使用携程 : 下载图片速度慢会占满携程造成拥堵, 接口无法请求
private val pool = Executors.newCachedThreadPool { runnable ->
Thread(runnable).also { it.isDaemon = true }
}
private val uiThreadHandler = Handler(Looper.getMainLooper())
private val scope = CoroutineScope(newSingleThreadContext("worker-scope"))
private val notImplementedToken = Any()
private fun MethodChannel.Result.withCoroutine(exec: () -> Any?) {
pool.submit {
try {
val data = exec()
uiThreadHandler.post {
when (data) {
notImplementedToken -> {
notImplemented()
}
is Unit, null -> {
success(null)
}
else -> {
success(data)
}
}
}
} catch (e: Exception) {
Log.e("Method", "Exception", e)
uiThreadHandler.post {
error("", e.message, "")
}
}
}
}
@RequiresApi(Build.VERSION_CODES.KITKAT)
override fun configureFlutterEngine(@NonNull flutterEngine: FlutterEngine) {
super.configureFlutterEngine(flutterEngine)
Mobile.initApplication(androidDataLocal())
// Method Channel
MethodChannel(flutterEngine.dartExecutor.binaryMessenger, "nhentai").setMethodCallHandler { call, result ->
result.withCoroutine {
when (call.method) {
"flatInvoke" -> {
Mobile.flatInvoke(
call.argument("method")!!,
call.argument("params")!!
)
}
"saveFileToImage" -> {
saveFileToImage(call.argument("path")!!)
}
"androidGetModes" -> {
modes()
}
"androidSetMode" -> {
setMode(call.argument("mode")!!)
}
"androidGetVersion" -> Build.VERSION.SDK_INT
// 现在的文件储存路径, 默认路径返回空字符串 ""
"dataLocal" -> androidDataLocal()
// 迁移到那个地方, 如果是空字符串则迁移会默认位置
"migrate" -> androidMigrate(call.argument("path")!!)
// 获取可以迁移数据地址
"androidGetExtendDirs" -> androidGetExtendDirs()
"androidSecureFlag" -> androidSecureFlag(call.argument("flag")!!)
"convertToPNG" -> convertToPNG(call.argument("path")!!)
else -> {
notImplementedToken
}
}
}
}
//
val eventMutex = Mutex()
var eventSink: EventChannel.EventSink? = null
EventChannel(flutterEngine.dartExecutor.binaryMessenger, "flatEvent")
.setStreamHandler(object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
events?.let { events ->
scope.launch {
eventMutex.lock()
eventSink = events
eventMutex.unlock()
}
}
}
override fun onCancel(arguments: Any?) {
scope.launch {
eventMutex.lock()
eventSink = null
eventMutex.unlock()
}
}
})
Mobile.eventNotify { message ->
scope.launch {
eventMutex.lock()
try {
eventSink?.let {
uiThreadHandler.post {
it.success(message)
}
}
} finally {
eventMutex.unlock()
}
}
}
//
EventChannel(flutterEngine.dartExecutor.binaryMessenger, "volume_button")
.setStreamHandler(volumeStreamHandler)
}
// save_image
private fun saveFileToImage(path: String) {
BitmapFactory.decodeFile(path)?.let { bitmap ->
val contentValues = ContentValues().apply {
put(MediaStore.MediaColumns.DISPLAY_NAME, System.currentTimeMillis().toString())
put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //this one
put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_PICTURES)
put(MediaStore.MediaColumns.IS_PENDING, 1)
}
}
contentResolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues)?.let { uri ->
contentResolver.openOutputStream(uri)?.use { fos ->
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) { //this one
contentValues.clear()
contentValues.put(MediaStore.Video.Media.IS_PENDING, 0)
contentResolver.update(uri, contentValues, null, null)
}
}
}
}
private fun androidDataLocal(): String {
val localFile = File(context!!.filesDir.absolutePath, "data.local")
if (localFile.exists()) {
val path = String(FileInputStream(localFile).use { it.readBytes() })
if (File(path).isDirectory) {
return path
}
}
return context!!.filesDir.absolutePath
}
private fun androidGetExtendDirs(): String {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
val result = context!!.getExternalFilesDirs("")?.toMutableList()?.also {
it.add(context!!.filesDir.absoluteFile)
}?.joinToString("|")
if (result != null) {
return result
}
}
throw Exception("System version too low")
}
private fun androidMigrate(path: String) {
val current = androidDataLocal()
if (current == path) {
return
}
// 删除位置配置文件
if (File(current, "data.local").exists()) {
File(current, "data.local").delete()
}
// 目标位置文件夹不存在就创建,存在则清理
val target = File(path)
if (!target.exists()) {
target.mkdirs()
}
target.listFiles().forEach { delete(it) }
// 移动所有文件夹
File(current).listFiles().forEach {
move(it, File(target, it.name))
}
val localFile = File(context!!.filesDir.absolutePath, "data.local")
if (path == context!!.filesDir.absolutePath) {
localFile.delete()
} else {
FileOutputStream(localFile).use { it.write(path.toByteArray()) }
}
}
private fun delete(f: File) {
f.delete()
}
private fun move(f: File, t: File) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (f.isDirectory) {
Files.createDirectories(t.toPath())
f.listFiles().forEach { move(it, File(t, it.name)) }
Files.delete(f.toPath())
} else {
Files.move(f.toPath(), t.toPath())
}
} else {
if (f.isDirectory) {
t.mkdirs()
f.listFiles().forEach { move(it, File(t, it.name)) }
f.delete()
} else {
FileOutputStream(t).use { o ->
FileInputStream(f).use { i ->
o.write(i.readBytes())
}
}
f.delete()
}
}
}
// fps mods
private fun mixDisplay(): Display? {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
display?.let {
return it
}
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
windowManager.defaultDisplay?.let {
return it
}
}
return null
}
private fun modes(): List {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mixDisplay()?.let { display ->
return display.supportedModes.map { mode ->
mode.toString()
}
}
}
return ArrayList()
}
private fun setMode(string: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mixDisplay()?.let { display ->
if (string == "") {
uiThreadHandler.post {
window.attributes = window.attributes.also { attr ->
attr.preferredDisplayModeId = 0
}
}
return
}
return display.supportedModes.forEach { mode ->
if (mode.toString() == string) {
uiThreadHandler.post {
window.attributes = window.attributes.also { attr ->
attr.preferredDisplayModeId = mode.modeId
}
}
return
}
}
}
}
}
// volume_buttons
private var volumeEvents: EventChannel.EventSink? = null
private val volumeStreamHandler = object : EventChannel.StreamHandler {
override fun onListen(arguments: Any?, events: EventChannel.EventSink?) {
volumeEvents = events
}
override fun onCancel(arguments: Any?) {
volumeEvents = null
}
}
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
volumeEvents?.let {
if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
uiThreadHandler.post {
it.success("DOWN")
}
return true
}
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
uiThreadHandler.post {
it.success("UP")
}
return true
}
}
return super.onKeyDown(keyCode, event)
}
private fun androidSecureFlag(flag: Boolean) {
uiThreadHandler.post {
if (flag) {
window.setFlags(WindowManager.LayoutParams.FLAG_SECURE, WindowManager.LayoutParams.FLAG_SECURE)
} else {
window.clearFlags(WindowManager.LayoutParams.FLAG_SECURE)
}
}
}
private fun convertToPNG(path: String): ByteArray {
BitmapFactory.decodeFile(path)?.let { bitmap ->
val maxWidth =
when {
Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> windowManager.currentWindowMetrics.bounds.width()
Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 -> {
val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getRealMetrics(displayMetrics)
displayMetrics.widthPixels
}
else -> throw Exception("not support")
}
if (bitmap.width > maxWidth) {
val newHeight = maxWidth * bitmap.height / bitmap.width
val newImage = Bitmap.createScaledBitmap(bitmap, maxWidth, newHeight, true)
return compressBitMap(newImage)
}
return compressBitMap(bitmap)
}
throw Exception("error pic")
}
private fun compressBitMap(bitmap: Bitmap): ByteArray {
val bos = ByteArrayOutputStream()
bos.use { bos ->
Log.d("BITMAP", bitmap.width.toString())
bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos)
}
return bos.toByteArray()
}
}
================================================
FILE: android/app/src/main/res/drawable/launch_background.xml
================================================
================================================
FILE: android/app/src/main/res/drawable-v21/launch_background.xml
================================================
================================================
FILE: android/app/src/main/res/values/styles.xml
================================================
================================================
FILE: android/app/src/main/res/values-night/styles.xml
================================================
================================================
FILE: android/app/src/profile/AndroidManifest.xml
================================================
================================================
FILE: android/build.gradle
================================================
buildscript {
ext.kotlin_version = '1.6.10'
repositories {
google()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
mavenCentral()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
================================================
FILE: android/gradle/wrapper/gradle-wrapper.properties
================================================
#Fri Jun 23 08:50:38 CEST 2017
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-6.7-all.zip
================================================
FILE: android/gradle.properties
================================================
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
================================================
FILE: android/settings.gradle
================================================
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"
================================================
FILE: ci/cmd/check_asset/main.go
================================================
package main
import (
"ci/commons"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
const owner = "niuhuan"
const repo = "nhentai-cross"
const ua = "niuhuan nhentai-cross ci"
func main() {
// get ghToken
ghToken := os.Getenv("GH_TOKEN")
if ghToken == "" {
println("Env ${GH_TOKEN} is not set")
os.Exit(1)
}
// get version
var version commons.Version
codeFile, err := ioutil.ReadFile("version.code.txt")
if err != nil {
panic(err)
}
version.Code = strings.TrimSpace(string(codeFile))
infoFile, err := ioutil.ReadFile("version.info.txt")
if err != nil {
panic(err)
}
version.Info = strings.TrimSpace(string(infoFile))
// get target
target := os.Getenv("TARGET")
if target == "" {
println("Env ${TARGET} is not set")
os.Exit(1)
}
//
var releaseFileName string
switch target {
case "macos":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-macos-intel.dmg", version.Code)
case "ios":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-ios-nosign.ipa", version.Code)
case "windows":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-windows-x86_64.zip", version.Code)
case "linux":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-linux-x86_64.AppImage", version.Code)
case "android-arm32":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-arm32.apk", version.Code)
case "android-arm64":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-arm64.apk", version.Code)
case "android-x86_64":
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-x86_64.apk", version.Code)
}
// get version
getReleaseRequest, err := http.NewRequest(
"GET",
fmt.Sprintf("https://api.github.com/repos/%v/%v/releases/tags/%v", owner, repo, version.Code),
nil,
)
if err != nil {
panic(err)
}
getReleaseRequest.Header.Set("User-Agent", ua)
getReleaseRequest.Header.Set("Authorization", "token "+ghToken)
getReleaseResponse, err := http.DefaultClient.Do(getReleaseRequest)
if err != nil {
panic(err)
}
defer getReleaseResponse.Body.Close()
if getReleaseResponse.StatusCode == 404 {
panic("NOT FOUND RELEASE")
}
buff, err := ioutil.ReadAll(getReleaseResponse.Body)
if err != nil {
panic(err)
}
var release commons.Release
err = json.Unmarshal(buff, &release)
if err != nil {
println(string(buff))
panic(err)
}
for _, asset := range release.Assets {
if asset.Name == releaseFileName {
println("::set-output name=skip_build::true")
os.Exit(0)
}
}
print("::set-output name=skip_build::false")
}
================================================
FILE: ci/cmd/check_release/main.go
================================================
package main
import (
"bytes"
"ci/commons"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
const owner = "niuhuan"
const repo = "nhentai-cross"
const ua = "niuhuan nhentai-cross ci"
const mainBranch = "master"
func main() {
// get ghToken
ghToken := os.Getenv("GH_TOKEN")
if ghToken == "" {
println("Env ${GH_TOKEN} is not set")
os.Exit(1)
}
// get version
var version commons.Version
codeFile, err := ioutil.ReadFile("version.code.txt")
if err != nil {
panic(err)
}
version.Code = strings.TrimSpace(string(codeFile))
infoFile, err := ioutil.ReadFile("version.info.txt")
if err != nil {
panic(err)
}
version.Info = strings.TrimSpace(string(infoFile))
// get version
getReleaseRequest, err := http.NewRequest(
"GET",
fmt.Sprintf("https://api.github.com/repos/%v/%v/releases/tags/%v", owner, repo, version.Code),
nil,
)
if err != nil {
panic(nil)
}
getReleaseRequest.Header.Set("User-Agent", ua)
getReleaseRequest.Header.Set("Authorization", "token "+ghToken)
getReleaseResponse, err := http.DefaultClient.Do(getReleaseRequest)
if err != nil {
panic(nil)
}
defer getReleaseResponse.Body.Close()
if getReleaseResponse.StatusCode == 404 {
url := fmt.Sprintf("https://api.github.com/repos/%v/%v/releases", owner, repo)
body := map[string]interface{}{
"tag_name": version.Code,
"target_commitish": mainBranch,
"name": version.Code,
"body": version.Info,
}
var buff []byte
buff, err = json.Marshal(&body)
if err != nil {
panic(err)
}
var createReleaseRequest *http.Request
createReleaseRequest, err = http.NewRequest("POST", url, bytes.NewBuffer(buff))
if err != nil {
panic(nil)
}
createReleaseRequest.Header.Set("User-Agent", ua)
createReleaseRequest.Header.Set("Authorization", "token "+ghToken)
var createReleaseResponse *http.Response
createReleaseResponse, err = http.DefaultClient.Do(createReleaseRequest)
if err != nil {
panic(nil)
}
defer createReleaseResponse.Body.Close()
if createReleaseResponse.StatusCode != 201 {
buff, err = ioutil.ReadAll(createReleaseResponse.Body)
if err != nil {
panic(err)
}
println(string(buff))
panic("NOT 201")
}
}
}
================================================
FILE: ci/cmd/upload_asset/main.go
================================================
package main
import (
"ci/commons"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
)
const owner = "niuhuan"
const repo = "nhentai-cross"
const ua = "niuhuan nhentai-cross ci"
func main() {
// get ghToken
ghToken := os.Getenv("GH_TOKEN")
if ghToken == "" {
println("Env ${GH_TOKEN} is not set")
os.Exit(1)
}
// get version
var version commons.Version
codeFile, err := ioutil.ReadFile("version.code.txt")
if err != nil {
panic(err)
}
version.Code = strings.TrimSpace(string(codeFile))
infoFile, err := ioutil.ReadFile("version.info.txt")
if err != nil {
panic(err)
}
version.Info = strings.TrimSpace(string(infoFile))
// get target
target := os.Getenv("TARGET")
if target == "" {
println("Env ${TARGET} is not set")
os.Exit(1)
}
//
var releaseFilePath string
var releaseFileName string
var contentType string
var contentLength int64
switch target {
case "macos":
releaseFilePath = "build/build.dmg"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-macos-intel.dmg", version.Code)
contentType = "application/octet-stream"
case "ios":
releaseFilePath = "build/nosign.ipa"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-ios-nosign.ipa", version.Code)
contentType = "application/octet-stream"
case "windows":
releaseFilePath = "build/build.zip"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-windows-x86_64.zip", version.Code)
contentType = "application/octet-stream"
case "linux":
releaseFilePath = "build/build.AppImage"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-linux-x86_64.AppImage", version.Code)
contentType = "application/octet-stream"
case "android-arm32":
releaseFilePath = "build/app/outputs/flutter-apk/app-release.apk"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-arm32.apk", version.Code)
contentType = "application/octet-stream"
case "android-arm64":
releaseFilePath = "build/app/outputs/flutter-apk/app-release.apk"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-arm64.apk", version.Code)
contentType = "application/octet-stream"
case "android-x86_64":
releaseFilePath = "build/app/outputs/flutter-apk/app-release.apk"
releaseFileName = fmt.Sprintf("nhentai-cross-%v-android-x86_64.apk", version.Code)
contentType = "application/octet-stream"
}
releaseFilePath = path.Join("..", releaseFilePath)
info, err := os.Stat(releaseFilePath)
if err != nil {
panic(err)
}
contentLength = info.Size()
// get version
getReleaseRequest, err := http.NewRequest(
"GET",
fmt.Sprintf("https://api.github.com/repos/%v/%v/releases/tags/%v", owner, repo, version.Code),
nil,
)
if err != nil {
panic(err)
}
getReleaseRequest.Header.Set("User-Agent", ua)
getReleaseRequest.Header.Set("Authorization", "token "+ghToken)
getReleaseResponse, err := http.DefaultClient.Do(getReleaseRequest)
if err != nil {
panic(err)
}
defer getReleaseResponse.Body.Close()
if getReleaseResponse.StatusCode == 404 {
panic("NOT FOUND RELEASE")
}
buff, err := ioutil.ReadAll(getReleaseResponse.Body)
if err != nil {
panic(err)
}
var release commons.Release
err = json.Unmarshal(buff, &release)
if err != nil {
println(string(buff))
panic(err)
}
file, err := os.Open(releaseFilePath)
if err != nil {
panic(err)
}
defer file.Close()
uploadUrl := fmt.Sprintf("https://uploads.github.com/repos/%v/%v/releases/%v/assets?name=%v", owner, repo, release.Id, releaseFileName)
uploadRequest, err := http.NewRequest("POST", uploadUrl, file)
if err != nil {
panic(err)
}
uploadRequest.Header.Set("User-Agent", ua)
uploadRequest.Header.Set("Authorization", "token "+ghToken)
uploadRequest.Header.Set("Content-Type", contentType)
uploadRequest.ContentLength = contentLength
uploadResponse, err := http.DefaultClient.Do(uploadRequest)
if err != nil {
panic(err)
}
if uploadResponse.StatusCode != 201 {
buff, err = ioutil.ReadAll(uploadResponse.Body)
if err != nil {
panic(err)
}
println(string(buff))
panic("NOT 201")
}
}
================================================
FILE: ci/commons/types.go
================================================
package commons
import "time"
type Version struct {
Code string `json:"code"`
Info string `json:"info"`
}
type Release struct {
Url string `json:"url"`
HtmlUrl string `json:"html_url"`
AssetsUrl string `json:"assets_url"`
UploadUrl string `json:"upload_url"`
TarballUrl string `json:"tarball_url"`
ZipballUrl string `json:"zipball_url"`
DiscussionUrl string `json:"discussion_url"`
Id int `json:"id"`
NodeId string `json:"node_id"`
TagName string `json:"tag_name"`
TargetCommitish string `json:"target_commitish"`
Name string `json:"name"`
Body string `json:"body"`
Draft bool `json:"draft"`
Prerelease bool `json:"prerelease"`
CreatedAt time.Time `json:"created_at"`
PublishedAt time.Time `json:"published_at"`
Author struct {
Login string `json:"login"`
Id int `json:"id"`
NodeId string `json:"node_id"`
AvatarUrl string `json:"avatar_url"`
GravatarId string `json:"gravatar_id"`
Url string `json:"url"`
HtmlUrl string `json:"html_url"`
FollowersUrl string `json:"followers_url"`
FollowingUrl string `json:"following_url"`
GistsUrl string `json:"gists_url"`
StarredUrl string `json:"starred_url"`
SubscriptionsUrl string `json:"subscriptions_url"`
OrganizationsUrl string `json:"organizations_url"`
ReposUrl string `json:"repos_url"`
EventsUrl string `json:"events_url"`
ReceivedEventsUrl string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"author"`
Assets []struct {
Url string `json:"url"`
BrowserDownloadUrl string `json:"browser_download_url"`
Id int `json:"id"`
NodeId string `json:"node_id"`
Name string `json:"name"`
Label string `json:"label"`
State string `json:"state"`
ContentType string `json:"content_type"`
Size int `json:"size"`
DownloadCount int `json:"download_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Uploader struct {
Login string `json:"login"`
Id int `json:"id"`
NodeId string `json:"node_id"`
AvatarUrl string `json:"avatar_url"`
GravatarId string `json:"gravatar_id"`
Url string `json:"url"`
HtmlUrl string `json:"html_url"`
FollowersUrl string `json:"followers_url"`
FollowingUrl string `json:"following_url"`
GistsUrl string `json:"gists_url"`
StarredUrl string `json:"starred_url"`
SubscriptionsUrl string `json:"subscriptions_url"`
OrganizationsUrl string `json:"organizations_url"`
ReposUrl string `json:"repos_url"`
EventsUrl string `json:"events_url"`
ReceivedEventsUrl string `json:"received_events_url"`
Type string `json:"type"`
SiteAdmin bool `json:"site_admin"`
} `json:"uploader"`
} `json:"assets"`
}
================================================
FILE: ci/go.mod
================================================
module "ci"
================================================
FILE: ci/linux_font.yaml
================================================
fonts:
- family: Roboto
fonts:
- asset: fonts/Roboto.ttf
================================================
FILE: ci/version.code.txt
================================================
v0.0.9
================================================
FILE: ci/version.info.txt
================================================
- Cross DDoS (only phone)
- 通过ddos (仅手机端)
================================================
FILE: go/.gitignore
================================================
build
.last_goflutter_check
.last_go-flutter_check
================================================
FILE: go/cmd/init.go
================================================
package main
import (
"errors"
"nhentai/nhentai"
"os"
"os/exec"
"path"
"path/filepath"
"runtime"
"strings"
)
func init() {
nhentai.InitNHentai(documentPath())
}
func documentPath() string {
applicationDir, err := os.UserHomeDir()
if err != nil {
panic(err)
}
switch runtime.GOOS {
case "windows":
// applicationDir = winDocumentPath.Join(applicationDir, "AppData", "Roaming", "nhentai")
file, err := exec.LookPath(os.Args[0])
if err != nil {
panic(err)
}
winDocumentPath, err := filepath.Abs(file)
if err != nil {
panic(err)
}
i := strings.LastIndex(winDocumentPath, "/")
if i < 0 {
i = strings.LastIndex(winDocumentPath, "\\")
}
if i < 0 {
panic(errors.New(" can't find \"/\" or \"\\\""))
}
applicationDir = path.Join(winDocumentPath[0:i+1], "data")
case "darwin":
applicationDir = path.Join(applicationDir, "Library", "Application Support", "nhentai")
case "linux":
applicationDir = path.Join(applicationDir, ".nhentai")
default:
panic(errors.New("not supported system"))
}
if _, err = os.Stat(applicationDir); err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(applicationDir, os.FileMode(0700))
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
return applicationDir
}
================================================
FILE: go/cmd/main.go
================================================
package main
import (
"fmt"
"github.com/go-flutter-desktop/go-flutter"
"github.com/pkg/errors"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"nhentai/nhentai/database/properties"
"os"
"path/filepath"
"strconv"
"strings"
)
// vmArguments may be set by hover at compile-time
var vmArguments string
func main() {
// DO NOT EDIT, add options in options.go
mainOptions := []flutter.Option{
flutter.OptionVMArguments(strings.Split(vmArguments, ";")),
flutter.WindowIcon(iconProvider),
}
// 窗口初始化大小的处理
widthStr, _ := properties.LoadProperty("window_width", "600")
heightStr, _ := properties.LoadProperty("window_height", "900")
width, _ := strconv.Atoi(widthStr)
height, _ := strconv.Atoi(heightStr)
if width <= 0 {
width = 600
}
if height <= 0 {
height = 900
}
var runOptions []flutter.Option
runOptions = append(runOptions, flutter.WindowInitialDimensions(width, height))
fullScreen, _ := properties.LoadBoolProperty("full_screen", false)
if fullScreen {
runOptions = append(runOptions, flutter.WindowMode(flutter.WindowModeMaximize))
}
// ------
err := flutter.Run(append(append(runOptions, options...), mainOptions...)...)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func iconProvider() ([]image.Image, error) {
execPath, err := os.Executable()
if err != nil {
return nil, errors.Wrap(err, "failed to resolve executable path")
}
execPath, err = filepath.EvalSymlinks(execPath)
if err != nil {
return nil, errors.Wrap(err, "failed to eval symlinks for executable path")
}
imgFile, err := os.Open(filepath.Join(filepath.Dir(execPath), "assets", "icon.png"))
if err != nil {
return nil, errors.Wrap(err, "failed to open assets/icon.png")
}
img, _, err := image.Decode(imgFile)
if err != nil {
return nil, errors.Wrap(err, "failed to decode image")
}
return []image.Image{img}, nil
}
================================================
FILE: go/cmd/options.go
================================================
package main
import (
"github.com/go-flutter-desktop/go-flutter"
"github.com/go-flutter-desktop/plugins/url_launcher"
"github.com/miguelpruivo/flutter_file_picker/go"
)
var options = []flutter.Option{
flutter.AddPlugin(&file_picker.FilePickerPlugin{}),
flutter.AddPlugin(&url_launcher.UrlLauncherPlugin{}),
flutter.AddPlugin(&Plugin{}),
}
================================================
FILE: go/cmd/plugin.go
================================================
package main
import (
"errors"
"github.com/go-flutter-desktop/go-flutter/plugin"
"github.com/go-gl/glfw/v3.3/glfw"
"nhentai/nhentai"
"nhentai/nhentai/database/properties"
"strconv"
)
type Plugin struct {
}
func (p *Plugin) InitPlugin(messenger plugin.BinaryMessenger) error {
channel := plugin.NewMethodChannel(messenger, "nhentai", plugin.StandardMethodCodec{})
channel.HandleFunc("flatInvoke", func(arguments interface{}) (interface{}, error) {
if argumentsMap, ok := arguments.(map[interface{}]interface{}); ok {
if method, ok := argumentsMap["method"].(string); ok {
if params, ok := argumentsMap["params"].(string); ok {
return nhentai.FlatInvoke(method, params)
}
}
}
return "", errors.New("method not found (nhentai channel)")
})
return nil
}
func (p *Plugin) InitPluginGLFW(window *glfw.Window) error {
window.SetSizeCallback(func(w *glfw.Window, width int, height int) {
go func() {
properties.SaveProperty("window_width", strconv.Itoa(width))
properties.SaveProperty("window_height", strconv.Itoa(height))
}()
})
window.SetMaximizeCallback(func(w *glfw.Window, iconified bool) {
go func() {
properties.SaveProperty("full_screen", strconv.FormatBool(iconified))
}()
})
return nil
}
================================================
FILE: go/go.mod
================================================
module nhentai
go 1.17
require (
github.com/go-flutter-desktop/go-flutter v0.44.0
github.com/go-flutter-desktop/plugins/url_launcher v0.1.3
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20220320163800-277f93cfa958
github.com/miguelpruivo/flutter_file_picker/go v0.0.0-20220310123445-443808b9cd35
github.com/niuhuan/nhentai-go v0.0.0-20220617164634-57974195259d
github.com/pkg/errors v0.9.1
golang.org/x/image v0.0.0-20220321031419-a8550c1d254a
gorm.io/driver/sqlite v1.3.1
gorm.io/gorm v1.23.4
)
require (
github.com/PuerkitoBio/goquery v1.8.0 // indirect
github.com/Xuanwo/go-locale v1.1.0 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/gen2brain/dlgs v0.0.0-20190708095831-3854608588f7 // indirect
github.com/go-gl/gl v0.0.0-20211025173605-bda47ffaa784 // indirect
github.com/gopherjs/gopherjs v0.0.0-20190915194858-d3ddacdb130f // indirect
github.com/jinzhu/inflection v1.0.0 // indirect
github.com/jinzhu/now v1.1.4 // indirect
github.com/json-iterator/go v1.1.12 // indirect
github.com/mattn/go-sqlite3 v1.14.9 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect
golang.org/x/mobile v0.0.0-20221012134814-c746ac228303 // indirect
golang.org/x/mod v0.4.2 // indirect
golang.org/x/net v0.0.0-20220615171555-694bf12d69de // indirect
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a // indirect
golang.org/x/text v0.3.7 // indirect
golang.org/x/tools v0.1.8-0.20211022200916-316ba0b74098 // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
)
================================================
FILE: go/go.sum
================================================
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/PuerkitoBio/goquery v1.8.0 h1:PJTF7AmFCFKk1N6V6jmKfrNH9tV5pNE6lZMkG0gta/U=
github.com/PuerkitoBio/goquery v1.8.0/go.mod h1:ypIiRMtY7COPGk+I/YbZLbxsxn9g5ejnI2HSMtkjZvI=
github.com/Xuanwo/go-locale v1.1.0 h1:51gUxhxl66oXAjI9uPGb2O0qwPECpriKQb2hl35mQkg=
github.com/Xuanwo/go-locale v1.1.0/go.mod h1:UKrHoZB3FPIk9wIG2/tVSobnHgNnceGSH3Y8DY5cASs=
github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c=
github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/gen2brain/dlgs v0.0.0-20190708095831-3854608588f7 h1:qA8Mdjwrlv/r/aMqArqO0IMHUiy6ApdW4+8DtKr7PvA=
github.com/gen2brain/dlgs v0.0.0-20190708095831-3854608588f7/go.mod h1:/eFcjDXaU2THSOOqLxOPETIbHETnamk8FA/hMjhg/gU=
github.com/go-flutter-desktop/go-flutter v0.30.0/go.mod h1:NCryd/AqiRbYSd8pMzQldYkgH1tZIFGt2ToUghZcWGA=
github.com/go-flutter-desktop/go-flutter v0.44.0 h1:0ab9WP2qxZCy2egXyjD6T7cBkORz2f9/LkETJ0F2PN8=
github.com/go-flutter-desktop/go-flutter v0.44.0/go.mod h1:Q1oxIBX2aX6rC+bWhN9aC4C05uJLXfnSNN2aNKNyBUM=
github.com/go-flutter-desktop/plugins/url_launcher v0.1.3 h1:28/xUmm3ZMqLtnlJF7zB9ZdJmF74h+cYKt65evU0pnQ=
github.com/go-flutter-desktop/plugins/url_launcher v0.1.3/go.mod h1:R8dUEKFt7nuCgeJ9UtZ3Apg1Ib9i20GDsVJl/7uma5E=
github.com/go-gl/gl v0.0.0-20190320180904-bf2b1f2f34d7/go.mod h1:482civXOzJJCPzJ4ZOX/pwvXBWSnzD4OKMdH4ClKGbk=
github.com/go-gl/gl v0.0.0-20211025173605-bda47ffaa784 h1:1Zi56D0LNfvkzM+BdoxKryvUEdyWO7LP8oRT+oSYJW0=
github.com/go-gl/gl v0.0.0-20211025173605-bda47ffaa784/go.mod h1:9YTyiznxEY1fVinfM7RvRcjRHbw2xLBJ3AAGIT0I4Nw=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1 h1:QbL/5oDUmRBzO9/Z7Seo6zf912W/a6Sr4Eu0G/3Jho0=
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20211024062804-40e447a793be/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20220320163800-277f93cfa958 h1:TL70PMkdPCt9cRhKTqsm+giRpgrd0IGEj763nNr2VFY=
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20220320163800-277f93cfa958/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/gopherjs/gopherjs v0.0.0-20181017120253-0766667cb4d1/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/gopherjs/gopherjs v0.0.0-20190915194858-d3ddacdb130f h1:TyqzGm2z1h3AGhjOoRYyeLcW4WlW81MDQkWa+rx/000=
github.com/gopherjs/gopherjs v0.0.0-20190915194858-d3ddacdb130f/go.mod h1:wJfORRmW1u3UXTncJ5qlYoELFm8eSnnEO6hX4iZ3EWY=
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
github.com/jinzhu/now v1.1.4 h1:tHnRBy1i5F2Dh8BAFxqFzxKqqvezXrL2OW1TnX+Mlas=
github.com/jinzhu/now v1.1.4/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
github.com/jtolds/gls v4.20.0+incompatible h1:xdiiI2gbIgH/gLH7ADydsJ1uDOEzR8yvV7C0MuV77Wo=
github.com/jtolds/gls v4.20.0+incompatible/go.mod h1:QJZ7F/aHp+rZTRtaJ1ow/lLfFfVYBRgL+9YlvaHOwJU=
github.com/mattn/go-sqlite3 v1.14.9 h1:10HX2Td0ocZpYEjhilsuo6WWtUqttj2Kb0KtD86/KYA=
github.com/mattn/go-sqlite3 v1.14.9/go.mod h1:NyWgC/yNuGj7Q9rpYnZvas74GogHl5/Z4A/KQRfk6bU=
github.com/miguelpruivo/flutter_file_picker/go v0.0.0-20220310123445-443808b9cd35 h1:LoiQwzAk4gm6SSechIAywbcaBhkc/NABfLJ94JxOU8Y=
github.com/miguelpruivo/flutter_file_picker/go v0.0.0-20220310123445-443808b9cd35/go.mod h1:csuW+TFyYKtiUwNvcvhcpyX4quPI7Pvv0SUogdqCW4I=
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/niuhuan/nhentai-go v0.0.0-20220617164634-57974195259d h1:+V2zonBI5M7UmqbBk1szY6RaGx5RMx71hO0TrQ3WLZ0=
github.com/niuhuan/nhentai-go v0.0.0-20220617164634-57974195259d/go.mod h1:4Vj8GRJFi4AAQgz3dRefIcPezroV0/a5Bu2oTgashQc=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d h1:zE9ykElWQ6/NYmHa3jpm/yHnI4xSofP+UP6SpjHcSeM=
github.com/smartystreets/assertions v0.0.0-20180927180507-b2de0cb4f26d/go.mod h1:OnSkiWE9lh6wB0YB77sQom3nweQdgAjqCqsofrRNTgc=
github.com/smartystreets/goconvey v1.6.7 h1:I6tZjLXD2Q1kjvNbIzB1wvQBsXmKXiVrhpRE8ZjP5jY=
github.com/smartystreets/goconvey v1.6.7/go.mod h1:syvi0/a8iFYH4r/RixwvyeAJjdLS9QV7WQ/tjFTllLA=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/exp v0.0.0-20190731235908-ec7cb31e5a56/go.mod h1:JhuoJpWY28nO4Vef9tZUw9qufEGTyX1+7lmHxV5q5G4=
golang.org/x/image v0.0.0-20190227222117-0694c2d4d067/go.mod h1:kZ7UVZpmo3dzQBMxlp+ypCbDeSB+sBbTgSJuh5dn5js=
golang.org/x/image v0.0.0-20190802002840-cff245a6509b/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
golang.org/x/image v0.0.0-20220321031419-a8550c1d254a h1:LnH9RNcpPv5Kzi15lXg42lYMPUf0x8CuPv1YnvBWZAg=
golang.org/x/image v0.0.0-20220321031419-a8550c1d254a/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/mobile v0.0.0-20190312151609-d3739f865fa6/go.mod h1:z+o9i4GpDbdi3rU15maQ/Ox0txvL9dWGYEHz965HBQE=
golang.org/x/mobile v0.0.0-20220722155234-aaac322e2105 h1:3vUV5x5+3LfQbgk7paCM6INOaJG9xXQbn79xoNkwfIk=
golang.org/x/mobile v0.0.0-20220722155234-aaac322e2105/go.mod h1:pe2sM7Uk+2Su1y7u/6Z8KJ24D7lepUjFZbhFOrmDfuQ=
golang.org/x/mobile v0.0.0-20221012134814-c746ac228303 h1:K4fp1rDuJBz0FCPAWzIJwnzwNEM7S6yobdZzMrZ/Zws=
golang.org/x/mobile v0.0.0-20221012134814-c746ac228303/go.mod h1:M32cGdzp91A8Ex9qQtyZinr19EYxzkFqDjW2oyHzTDQ=
golang.org/x/mod v0.1.0/go.mod h1:0QHyrYULN0/3qlju5TqG8bIK38QM8yzMo5ekMj3DlcY=
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220615171555-694bf12d69de h1:ogOG2+P6LjO2j55AkRScrkB2BFpd+Z8TY2wcM0Z3MGo=
golang.org/x/net v0.0.0-20220615171555-694bf12d69de/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220819030929-7fc1605a5dde/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211023085530-d6a326fbbf70/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a h1:dGzPydgVsqGcTRVwiLJ1jVbufYwmzD3LfVPLKsKg+0k=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20190312151545-0bb0c0a6e846/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20190328211700-ab21143f2384/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.8-0.20211022200916-316ba0b74098 h1:YuekqPskqwCCPM79F1X5Dhv4ezTCj+Ki1oNwiafxkA0=
golang.org/x/tools v0.1.8-0.20211022200916-316ba0b74098/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 h1:go1bK/D/BFZV2I8cIQd1NKEZ+0owSTG1fDTci4IqFcE=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gorm.io/driver/sqlite v1.3.1 h1:bwfE+zTEWklBYoEodIOIBwuWHpnx52Z9zJFW5F33WLk=
gorm.io/driver/sqlite v1.3.1/go.mod h1:wJx0hJspfycZ6myN38x1O/AqLtNS6c5o9TndewFbELg=
gorm.io/gorm v1.23.1/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
gorm.io/gorm v1.23.4 h1:1BKWM67O6CflSLcwGQR7ccfmC4ebOxQrTfOQGRE9wjg=
gorm.io/gorm v1.23.4/go.mod h1:l2lP/RyAtc1ynaTjFksBde/O8v9oOGIApu2/xRitmZk=
================================================
FILE: go/hover.yaml
================================================
#application-name: "nhentai" # Uncomment to modify this value.
#executable-name: "nhentai" # Uncomment to modify this value. Only lowercase a-z, numbers, underscores and no spaces
#package-name: "nhentai" # Uncomment to modify this value. Only lowercase a-z, numbers and no underscores or spaces
organization-name: "com.nhentai"
license: "" # MANDATORY: Fill in your SPDX license name: https://spdx.org/licenses
target: lib/main_desktop.dart
# opengl: "none" # Uncomment this line if you have trouble with your OpenGL driver (https://github.com/go-flutter-desktop/go-flutter/issues/272)
docker: false
engine-version: "" # change to a engine version commit
================================================
FILE: go/mobile/bind-android-debug.sh
================================================
gomobile bind -target=android/arm,android/arm64,android/386,android/amd64 -o lib/Mobile.aar ./
================================================
FILE: go/mobile/bind-android.sh
================================================
gomobile bind -target=android/arm -o lib/Mobile.aar ./
================================================
FILE: go/mobile/bind-ios-debug.sh
================================================
gomobile bind -target=ios -o lib/Mobile.xcframework ./
================================================
FILE: go/mobile/bind-ios.sh
================================================
gomobile bind -target=ios -o lib/Mobile.xcframework ./
================================================
FILE: go/mobile/lib/.keep
================================================
================================================
FILE: go/mobile/mobile.go
================================================
package mobile
import (
"errors"
"nhentai/nhentai"
"nhentai/nhentai/constant"
"os"
"path"
)
func Migration(source, target string) {
constant.ObtainDir(source)
constant.ObtainDir(target)
cacheDIr := path.Join(source, "cache")
downloadDir := path.Join(source, "download")
databaseDir := path.Join(source, "database")
cacheE, _ := exists(cacheDIr)
downloadE, _ := exists(downloadDir)
databaseE, _ := exists(databaseDir)
if cacheE {
os.Rename(cacheDIr, path.Join(target, "cache"))
}
if downloadE {
os.Rename(downloadDir, path.Join(target, "download"))
}
if databaseE {
os.Rename(databaseDir, path.Join(target, "database"))
}
}
func exists(name string) (bool, error) {
_, err := os.Stat(name)
if err == nil {
return true, nil
}
if errors.Is(err, os.ErrNotExist) {
return false, nil
}
return false, err
}
func InitApplication(application string) {
nhentai.InitNHentai(application)
}
func FlatInvoke(method string, params string) (string, error) {
return nhentai.FlatInvoke(method, params)
}
func EventNotify(notify EventNotifyHandler) {
// controller.EventNotify = notify.OnNotify
}
type EventNotifyHandler interface {
OnNotify(message string)
}
================================================
FILE: go/nhentai/client.go
================================================
package nhentai
import (
"crypto/md5"
"encoding/json"
"fmt"
source "github.com/niuhuan/nhentai-go"
"io/ioutil"
"net"
"net/http"
"net/url"
"nhentai/nhentai/database/active"
"nhentai/nhentai/database/cache"
"nhentai/nhentai/database/properties"
"os"
"path"
"strconv"
"time"
)
var dialer = &net.Dialer{
Timeout: 30 * time.Second,
KeepAlive: 30 * time.Second,
}
var client = &source.Client{
Client: http.Client{
Transport: &http.Transport{
Proxy: nil,
TLSHandshakeTimeout: time.Second * 20,
ExpectContinueTimeout: time.Second * 20,
ResponseHeaderTimeout: time.Second * 20,
IdleConnTimeout: time.Second * 20,
},
},
}
func initClient() {
proxy, _ := properties.LoadProperty("proxy", "")
setProxy(proxy)
}
func setProxy(proxyUrlString string) (string, error) {
var proxy func(_ *http.Request) (*url.URL, error)
if proxyUrlString != "" {
proxyUrl, proxyErr := url.Parse(proxyUrlString)
if proxyErr != nil {
return "", proxyErr
}
proxy = func(_ *http.Request) (*url.URL, error) {
return proxyUrl, proxyErr
}
}
properties.SaveProperty("proxy", proxyUrlString)
client.Client.Transport.(*http.Transport).Proxy = proxy
return "", nil
}
func getProxy(_ string) (string, error) {
return properties.LoadProperty("proxy", "")
}
func comics(params string) (string, error) {
page, err := strconv.Atoi(params)
if err != nil {
return "", err
}
return cacheable(
fmt.Sprintf("COMICS$%d", page),
time.Hour,
func() (interface{}, error) {
return client.Comics(page)
},
)
}
func comicsByTagName(params string) (string, error) {
var paramsStruct struct {
TagName string `json:"tag_name"`
Page int `json:"page"`
}
err := json.Unmarshal([]byte(params), ¶msStruct)
if err != nil {
return "", err
}
return cacheable(
fmt.Sprintf("COMICS_BY_TAG$%s$%d", paramsStruct.TagName, paramsStruct.Page),
time.Hour,
func() (interface{}, error) {
return client.ComicsByTagName(paramsStruct.TagName, paramsStruct.Page)
},
)
}
func comicsBySearchRaw(params string) (string, error) {
var paramsStruct struct {
Raw string `json:"raw"`
Page int `json:"page"`
}
err := json.Unmarshal([]byte(params), ¶msStruct)
if err != nil {
return "", err
}
return cacheable(
fmt.Sprintf("COMICS_BY_SEARCH_RAW$%s$%d", paramsStruct.Raw, paramsStruct.Page),
time.Hour,
func() (interface{}, error) {
return client.ComicByRawCondition(paramsStruct.Raw, paramsStruct.Page)
},
)
}
func comicInfo(params string) (string, error) {
id, err := strconv.Atoi(params)
if err != nil {
return "", err
}
return cacheable(
fmt.Sprintf("COMIC_INFO$%d", id),
time.Hour,
func() (interface{}, error) {
return client.ComicInfo(id)
},
)
}
func cacheImageByUrlPath(url string) (string, error) {
lock := HashLock(url)
lock.Lock()
defer lock.Unlock()
// downloadPage
p1 := active.FindDownloadPageByUrl(url)
if p1 != nil {
return path.Join(downloadPath, p1.DownloadLocalPath), nil
}
// downloadPageThumb
p2 := active.FindDownloadPageThumbByUrl(url)
if p2 != nil {
return path.Join(downloadPath, p2.DownloadLocalPath), nil
}
// downloadCover
p3 := active.FindDownloadCoverByUrl(url)
if p3 != nil {
return path.Join(downloadPath, p3.DownloadLocalPath), nil
}
// downloadCoverThumb
p4 := active.FindDownloadCoverThumbByUrl(url)
if p4 != nil {
return path.Join(downloadPath, p4.DownloadLocalPath), nil
}
// cache
cache := cache.FindImageCache(url)
// no cache
if cache == nil {
remote, err := decodeAndSaveImage(url)
if err != nil {
return "", err
}
cache = remote
}
return cacheImagePath(cache.LocalPath), nil
}
func decodeAndSaveImage(url string) (*cache.ImageCache, error) {
buff, err := decodeFromUrl(url)
if err != nil {
println(fmt.Sprintf("decode error : %s : %s", url, err.Error()))
return nil, err
}
local := fmt.Sprintf("%x", md5.Sum([]byte(url)))
real := cacheImagePath(local)
err = ioutil.WriteFile(
real,
buff, os.FileMode(0600),
)
if err != nil {
return nil, err
}
imageCache := cache.ImageCache{
Url: url,
LocalPath: local,
}
err = cache.SaveImageCache(&imageCache)
return &imageCache, err
}
================================================
FILE: go/nhentai/common.go
================================================
package nhentai
import (
"bytes"
"encoding/json"
"image"
"image/jpeg"
"io/ioutil"
"nhentai/nhentai/database/cache"
"os"
"path"
"time"
)
// PING
// @
// "104.27.195.88:443"
// t.nhentai.net
//185.177.127.78 (3115417422)
//185.177.127.77 (3115417421)
//23.237.126.122 (401440378)
// t5.nhentai.net
// 185.177.127.77 (3115417421)
// i.nhentai.net
//185.177.127.78 (3115417422)
//23.237.126.122 (401440378)
//185.177.127.77 (3115417421)
func availableWebAddresses(_ string) (string, error) {
return serialize([]string{
"104.21.66.123:443",
"172.67.159.231:443",
}, nil)
}
func availableImgAddresses(_ string) (string, error) {
return serialize([]string{
"185.107.44.3:443",
"185.177.127.78:443",
"185.177.127.77:443",
}, nil)
}
func cacheable(key string, expire time.Duration, reload func() (interface{}, error)) (string, error) {
// CACHE
cacheable, err := cache.LoadCache(key, expire)
if err != nil {
return "", err
}
if cacheable != "" {
return cacheable, nil
}
// RELOAD
cacheable, err = serialize(reload())
if err != nil {
return "", err
}
// push to cache (if cache error )
_ = cache.SaveCache(key, cacheable)
// return
return cacheable, nil
}
// 将interface序列化成字符串, 方便与flutter通信
func serialize(point interface{}, err error) (string, error) {
if err != nil {
return "", err
}
buff, err := json.Marshal(point)
return string(buff), nil
}
func convertImageToJPEG100(params string) (string, error) {
var paramsStruct struct {
Path string `json:"path"`
Dir string `json:"dir"`
}
err := json.Unmarshal([]byte(params), ¶msStruct)
if err != nil {
return "", err
}
buff, err := ioutil.ReadFile(paramsStruct.Path)
if err != nil {
return "", err
}
reader := bytes.NewReader(buff)
i, _, err := image.Decode(reader)
if err != nil {
return "", err
}
to := path.Join(paramsStruct.Dir, path.Base(paramsStruct.Path)+".jpg")
stream, err := os.Create(to)
if err != nil {
return "", err
}
defer stream.Close()
return "", jpeg.Encode(stream, i, &jpeg.Options{Quality: 100})
}
================================================
FILE: go/nhentai/constant/constant.go
================================================
package constant
import (
"gorm.io/gorm"
"gorm.io/gorm/logger"
"gorm.io/gorm/schema"
"hash/fnv"
"os"
"sync"
)
var (
CreateDirMode = os.FileMode(0700)
CreateFileMode = os.FileMode(0600)
GormConfig = &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
NamingStrategy: schema.NamingStrategy{
SingularTable: true,
},
}
)
var hashMutex []*sync.Mutex
func init() {
for i := 0; i < 32; i++ {
hashMutex = append(hashMutex, &sync.Mutex{})
}
}
// HashLock Hash一样的图片不同时处理
func HashLock(key string) *sync.Mutex {
hash := fnv.New32()
hash.Write([]byte(key))
return hashMutex[int(hash.Sum32()%uint32(len(hashMutex)))]
}
================================================
FILE: go/nhentai/constant/os.go
================================================
package constant
import (
"os"
"strings"
)
func ObtainDir(dir string) {
if _, err := os.Stat(dir); err != nil {
if os.IsNotExist(err) {
err = os.MkdirAll(dir, CreateDirMode)
if err != nil {
panic(err)
}
} else {
panic(err)
}
}
}
func ReasonableFileName(title string) string {
title = strings.ReplaceAll(title, "\\", "_")
title = strings.ReplaceAll(title, "/", "_")
title = strings.ReplaceAll(title, "*", "_")
title = strings.ReplaceAll(title, "?", "_")
title = strings.ReplaceAll(title, "<", "_")
title = strings.ReplaceAll(title, ">", "_")
title = strings.ReplaceAll(title, "|", "_")
return title
}
================================================
FILE: go/nhentai/constant/time.go
================================================
package constant
import "time"
// Timestamp 获取当前的Unix时间戳
func Timestamp() int64 {
return time.Now().UnixNano() / int64(time.Millisecond)
}
================================================
FILE: go/nhentai/database/active/active.go
================================================
package active
import (
"errors"
"github.com/niuhuan/nhentai-go"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"nhentai/nhentai/constant"
"path"
"sync"
)
var client = nhentai.Client{}
var mutex = sync.Mutex{}
var db *gorm.DB
func Init(databaseDir string) {
var err error
db, err = gorm.Open(sqlite.Open(path.Join(databaseDir, "download.db")), constant.GormConfig)
if err != nil {
panic(err)
}
db.AutoMigrate(&ViewLog{})
db.AutoMigrate(&ViewLogTag{})
db.AutoMigrate(&Download{})
db.AutoMigrate(&DownloadTag{})
db.AutoMigrate(&DownloadCover{})
db.AutoMigrate(&DownloadCoverThumb{})
db.AutoMigrate(&DownloadPage{})
db.AutoMigrate(&DownloadPageThumb{})
}
type ViewLog struct {
ID int `gorm:"primarykey" json:"id"`
MediaId int `json:"media_id"`
TitleEnglish string `json:"title_english"`
TitleJapanese string `json:"title_japanese"`
TitlePretty string `json:"title_pretty"`
Scanlator string `json:"scanlator"`
UploadDate int `json:"upload_date"`
NumPages int `json:"num_pages"`
NumFavorites int `json:"num_favorites"`
LastViewTime int64 `json:"last_view_time"`
LastViewIndex int `json:"last_view_index"`
}
type ViewLogTag struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
ID int `gorm:"primarykey" json:"id"`
Name string `json:"name"`
Count int `json:"count"`
Type string `json:"type"`
Url string `json:"url"`
}
type Download struct {
ID int `gorm:"primarykey" json:"id"`
MediaId int `json:"media_id"`
TitleEnglish string `json:"title_english"`
TitleJapanese string `json:"title_japanese"`
TitlePretty string `json:"title_pretty"`
Scanlator string `json:"scanlator"`
UploadDate int `json:"upload_date"`
NumPages int `json:"num_pages"`
NumFavorites int `json:"num_favorites"`
DownloadCreatedTime int64 `json:"download_created_time"`
DownloadStatus int `json:"download_status"` // 未完成, 1成功, 2失败
}
type DownloadTag struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
ID int `gorm:"primarykey" json:"id"`
Name string `json:"name"`
Count int `json:"count"`
Type string `json:"type"`
Url string `json:"url"`
}
type DownloadCover struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
Url string `gorm:"index:idx_url" json:"url"`
T string `json:"t"`
W int `json:"w"`
H int `json:"h"`
DownloadStatus int `json:"download_status"` // 未完成, 1成功, 2失败
DownloadLocalPath string
}
type DownloadCoverThumb struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
Url string `gorm:"index:idx_url" json:"url"`
T string `json:"t"`
W int `json:"w"`
H int `json:"h"`
DownloadStatus int `json:"download_status"` // 未完成, 1成功, 2失败
DownloadLocalPath string
}
type DownloadPage struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
PageIndex int `gorm:"primarykey" json:"page_index"`
Num int `json:"num"`
Url string `gorm:"index:idx_url" json:"url"`
T string `json:"t"`
W int `json:"w"`
H int `json:"h"`
DownloadStatus int `json:"download_status"` // 未完成, 1成功, 2失败
DownloadLocalPath string
}
type DownloadPageThumb struct {
ComicId int `gorm:"primarykey" json:"comic_id"`
PageIndex int `gorm:"primarykey" json:"page_index"`
Num int `json:"num"`
Url string `gorm:"index:idx_url" json:"url"`
DownloadStatus int `json:"download_status"` // 未完成, 1成功, 2失败
DownloadLocalPath string
}
func SaveViewInfo(info nhentai.ComicInfo) error {
viewLog := takeViewLog(info, 0)
tags := takeViewLogTags(info.Tags, info.Id)
mutex.Lock()
defer mutex.Unlock()
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{
"id",
"media_id",
"title_english",
"title_japanese",
"title_pretty",
"scanlator",
"upload_date",
"num_pages",
"num_favorites",
"last_view_time",
}),
}).Create(&viewLog).Error
if err != nil {
return err
}
return saveViewTagInTx(tx, tags)
})
}
func SaveViewIndex(info nhentai.ComicInfo, index int) error {
viewLog := takeViewLog(info, index)
tags := takeViewLogTags(info.Tags, info.Id)
mutex.Lock()
defer mutex.Unlock()
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{
"id",
"media_id",
"title_english",
"title_japanese",
"title_pretty",
"scanlator",
"upload_date",
"num_pages",
"num_favorites",
"last_view_time",
"last_view_index",
}),
}).Create(&viewLog).Error
if err != nil {
return err
}
return saveViewTagInTx(tx, tags)
})
}
func saveViewTagInTx(tx *gorm.DB, tags []ViewLogTag) error {
var err error
for i := 0; i < len(tags); i++ {
err = tx.Clauses(clause.OnConflict{
Columns: []clause.Column{
{Name: "comic_id"},
{Name: "id"},
},
DoUpdates: clause.AssignmentColumns([]string{
"comic_id",
"id",
"type",
"count",
"name",
"url",
}),
}).Create(&tags[i]).Error
if err != nil {
return err
}
}
return nil
}
func takeViewLogTags(infoTags []nhentai.ComicInfoTag, comicId int) []ViewLogTag {
tags := make([]ViewLogTag, len(infoTags))
for i := 0; i < len(infoTags); i++ {
tags[i] = ViewLogTag{
ComicId: comicId,
ID: infoTags[i].Id,
Type: infoTags[i].Type,
Count: infoTags[i].Count,
Name: infoTags[i].Name,
Url: infoTags[i].Url,
}
}
return tags
}
func takeViewLog(info nhentai.ComicInfo, index int) ViewLog {
return ViewLog{
ID: info.Id,
MediaId: info.MediaId,
TitleEnglish: info.Title.English,
TitleJapanese: info.Title.Japanese,
TitlePretty: info.Title.Pretty,
Scanlator: info.Scanlator,
UploadDate: info.UploadDate,
NumPages: info.NumPages,
NumFavorites: info.NumFavorites,
LastViewTime: constant.Timestamp(),
LastViewIndex: index,
}
}
func LoadLastViewIndexByComicId(comicId int) (int, error) {
mutex.Lock()
defer mutex.Unlock()
var viewLog ViewLog
err := db.Where("id = ?", comicId).Find(&viewLog).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return 0, nil
}
return 0, err
}
return viewLog.LastViewIndex, nil
}
func CreateDownload(info nhentai.ComicInfo) error {
download := Download{
ID: info.Id,
MediaId: info.MediaId,
TitleEnglish: info.Title.English,
TitleJapanese: info.Title.Japanese,
TitlePretty: info.Title.Pretty,
Scanlator: info.Scanlator,
UploadDate: info.UploadDate,
NumPages: info.NumPages,
NumFavorites: info.NumFavorites,
DownloadCreatedTime: constant.Timestamp(),
DownloadStatus: 0,
}
tags := takeDownloadTags(info.Tags, info.Id)
cover := DownloadCover{
ComicId: info.Id,
Url: client.CoverUrl(info.MediaId, info.Images.Cover.T),
T: info.Images.Cover.T,
W: info.Images.Cover.W,
H: info.Images.Cover.H,
DownloadStatus: 0,
DownloadLocalPath: "",
}
coverThumb := DownloadCoverThumb{
ComicId: info.Id,
Url: client.ThumbnailUrl(info.MediaId, info.Images.Thumbnail.T),
T: info.Images.Thumbnail.T,
W: info.Images.Thumbnail.W,
H: info.Images.Thumbnail.H,
DownloadStatus: 0,
DownloadLocalPath: "",
}
pages := make([]DownloadPage, len(info.Images.Pages))
pagesThumbs := make([]DownloadPageThumb, len(info.Images.Pages))
for i := 0; i < len(info.Images.Pages); i++ {
pages[i] = DownloadPage{
ComicId: info.Id,
PageIndex: i,
Num: i + 1,
Url: client.PageUrl(info.MediaId, i+1, info.Images.Pages[i].T),
T: info.Images.Pages[i].T,
W: info.Images.Pages[i].W,
H: info.Images.Pages[i].H,
DownloadStatus: 0,
DownloadLocalPath: "",
}
pagesThumbs[i] = DownloadPageThumb{
ComicId: info.Id,
PageIndex: i,
Num: i + 1,
Url: client.PageThumbnailUrl(info.MediaId, i+1, info.Images.Pages[i].T),
DownloadStatus: 0,
DownloadLocalPath: "",
}
}
mutex.Lock()
defer mutex.Unlock()
return db.Transaction(func(tx *gorm.DB) error {
err := tx.Where("id = ?", download.ID).First(&Download{}).Error
if err == nil {
return errors.New("download exists")
}
if err != gorm.ErrRecordNotFound {
return err
}
err = tx.Save(&download).Error
if err != nil {
return err
}
for i := 0; i < len(tags); i++ {
tx.Save(&(tags[i]))
if err != nil {
return err
}
}
err = tx.Save(&cover).Error
if err != nil {
return err
}
err = tx.Save(&coverThumb).Error
if err != nil {
return err
}
for i := 0; i < len(pages); i++ {
tx.Save(&(pages[i]))
if err != nil {
return err
}
}
for i := 0; i < len(pagesThumbs); i++ {
tx.Save(&(pagesThumbs[i]))
if err != nil {
return err
}
}
return nil
})
}
func takeDownloadTags(infoTags []nhentai.ComicInfoTag, comicId int) []DownloadTag {
tags := make([]DownloadTag, len(infoTags))
for i := 0; i < len(infoTags); i++ {
tags[i] = DownloadTag{
ComicId: comicId,
ID: infoTags[i].Id,
Type: infoTags[i].Type,
Count: infoTags[i].Count,
Name: infoTags[i].Name,
Url: infoTags[i].Url,
}
}
return tags
}
func LoadFirstNeedDownload() (*Download, error) {
mutex.Lock()
defer mutex.Unlock()
download := Download{}
err := db.Where("download_status = 0").Order("download_created_time DESC").First(&download).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil, nil
}
return nil, err
}
return &download, nil
}
func TheDownloadCover(id int) (*DownloadCover, error) {
mutex.Lock()
defer mutex.Unlock()
cover := DownloadCover{}
err := db.Where("comic_id = ?", id).First(&cover).Error
return &cover, err
}
func TheDownloadCoverThumb(id int) (*DownloadCoverThumb, error) {
mutex.Lock()
defer mutex.Unlock()
coverThumb := DownloadCoverThumb{}
err := db.Where("comic_id = ?", id).First(&coverThumb).Error
return &coverThumb, err
}
func TheDownloadNeedDownloadPages(id int, limit int) ([]DownloadPage, error) {
mutex.Lock()
defer mutex.Unlock()
var pages []DownloadPage
return pages, db.Where("comic_id = ? AND download_status = 0", id).
Order("page_index ASC").Limit(limit).
Find(&pages).Error
}
func TheDownloadNeedDownloadPageThumbs(id int, limit int) ([]DownloadPageThumb, error) {
mutex.Lock()
defer mutex.Unlock()
var pages []DownloadPageThumb
return pages, db.Where("comic_id = ? AND download_status = 0", id).
Order("page_index ASC").Limit(limit).
Find(&pages).Error
}
func SaveDownloadCoverStatus(comicId int, status int, path string) error {
mutex.Lock()
defer mutex.Unlock()
return db.Model(&DownloadCover{}).Where("comic_id = ?", comicId).Updates(map[string]interface{}{
"download_status": status,
"download_local_path": path,
}).Error
}
func SaveDownloadCoverThumbStatus(comicId int, status int, path string) error {
mutex.Lock()
defer mutex.Unlock()
return db.Model(&DownloadCoverThumb{}).Where("comic_id = ?", comicId).Updates(map[string]interface{}{
"download_status": status,
"download_local_path": path,
}).Error
}
func SaveDownloadPageStatus(comicId int, pageIndex, status int, path string) error {
mutex.Lock()
defer mutex.Unlock()
return db.Model(&DownloadPage{}).Where("comic_id = ? AND page_index = ?", comicId, pageIndex).Updates(map[string]interface{}{
"download_status": status,
"download_local_path": path,
}).Error
}
func SaveDownloadPageThumbStatus(comicId int, pageIndex, status int, path string) error {
mutex.Lock()
defer mutex.Unlock()
return db.Model(&DownloadPageThumb{}).Where("comic_id = ? AND page_index = ?", comicId, pageIndex).Updates(map[string]interface{}{
"download_status": status,
"download_local_path": path,
}).Error
}
func DownloadCoverOk(comicId int) bool {
mutex.Lock()
defer mutex.Unlock()
var covers []DownloadCover
err := db.Where("comic_id = ?", comicId).Group("download_status").Find(&covers).Error
if err != nil {
panic(err)
}
return len(covers) == 1 && covers[0].DownloadStatus == 1
}
func DownloadCoverThumbOk(comicId int) bool {
mutex.Lock()
defer mutex.Unlock()
var covers []DownloadCoverThumb
err := db.Where("comic_id = ?", comicId).Group("download_status").Find(&covers).Error
if err != nil {
panic(err)
}
return len(covers) == 1 && covers[0].DownloadStatus == 1
}
func DownloadPageOk(comicId int) bool {
mutex.Lock()
defer mutex.Unlock()
var pages []DownloadPage
err := db.Where("comic_id = ?", comicId).Group("download_status").Find(&pages).Error
if err != nil {
panic(err)
}
return len(pages) == 1 && pages[0].DownloadStatus == 1
}
func DownloadPageThumbOk(comicId int) bool {
mutex.Lock()
defer mutex.Unlock()
var pages []DownloadPageThumb
err := db.Where("comic_id = ?", comicId).Group("download_status").Find(&pages).Error
if err != nil {
panic(err)
}
return len(pages) == 1 && pages[0].DownloadStatus == 1
}
func SaveDownloadStatus(id int, status int) error {
mutex.Lock()
defer mutex.Unlock()
return db.Model(&Download{}).Where("id = ?", id).Updates(map[string]interface{}{
"download_status": status,
}).Error
}
func FindDownloadPageByUrl(url string) *DownloadPage {
mutex.Lock()
defer mutex.Unlock()
page := DownloadPage{}
err := db.Where("url = ? AND download_status = 1", url).First(&page).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
panic(err)
}
return nil
}
return &page
}
func FindDownloadPageThumbByUrl(url string) *DownloadPageThumb {
mutex.Lock()
defer mutex.Unlock()
page := DownloadPageThumb{}
err := db.Where("url = ? AND download_status = 1", url).First(&page).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
panic(err)
}
return nil
}
return &page
}
func FindDownloadCoverByUrl(url string) *DownloadCover {
mutex.Lock()
defer mutex.Unlock()
page := DownloadCover{}
err := db.Where("url = ? AND download_status = 1", url).First(&page).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
panic(err)
}
return nil
}
return &page
}
func FindDownloadCoverThumbByUrl(url string) *DownloadCoverThumb {
mutex.Lock()
defer mutex.Unlock()
page := DownloadCoverThumb{}
err := db.Where("url = ? AND download_status = 1", url).First(&page).Error
if err != nil {
if err != gorm.ErrRecordNotFound {
panic(err)
}
return nil
}
return &page
}
func HasDownload(comicId int) bool {
mutex.Lock()
defer mutex.Unlock()
var download Download
err := db.Where("id = ?", comicId).First(&download).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return false
}
panic(err)
}
return true
}
func ListDownloadComicInfo() []DownloadComicInfo {
mutex.Lock()
defer mutex.Unlock()
var err error
var downloads []Download
var tags []DownloadTag
var thumbs []DownloadCoverThumb
var covers []DownloadCover
var pages []DownloadPage
err = db.Find(&downloads).Error
if err != nil {
panic(err)
}
err = db.Find(&tags).Error
if err != nil {
panic(err)
}
err = db.Find(&covers).Error
if err != nil {
panic(err)
}
err = db.Find(&thumbs).Error
if err != nil {
panic(err)
}
err = db.Order("page_index ASC").Find(&pages).Error
if err != nil {
panic(err)
}
var infos = make([]DownloadComicInfo, len(downloads))
for i := 0; i < len(infos); i++ {
infos[i] = DownloadComicInfo{
ComicInfo: nhentai.ComicInfo{
Id: downloads[i].ID,
MediaId: downloads[i].MediaId,
Title: nhentai.ComicInfoTitle{
English: downloads[i].TitleEnglish,
Japanese: downloads[i].TitleJapanese,
Pretty: downloads[i].TitlePretty,
},
Images: nhentai.ComicInfoImages{
Pages: filterPages(pages, downloads[i].ID),
Cover: filterCover(covers, downloads[i].ID),
Thumbnail: filterCoverThumb(thumbs, downloads[i].ID),
},
Scanlator: downloads[i].Scanlator,
UploadDate: downloads[i].UploadDate,
Tags: filterTags(tags, downloads[i].ID),
NumPages: downloads[i].NumPages,
NumFavorites: downloads[i].NumFavorites,
},
DownloadStatus: downloads[i].DownloadStatus,
}
}
return infos
}
func filterPages(pages []DownloadPage, id int) []nhentai.ImageInfo {
rsp := make([]nhentai.ImageInfo, 0)
for i := 0; i < len(pages); i++ {
if pages[i].ComicId == id {
rsp = append(rsp, nhentai.ImageInfo{
T: pages[i].T,
W: pages[i].W,
H: pages[i].H,
})
}
}
return rsp
}
func filterTags(tags []DownloadTag, id int) []nhentai.ComicInfoTag {
rsp := make([]nhentai.ComicInfoTag, 0)
for i := 0; i < len(tags); i++ {
if tags[i].ComicId == id {
rsp = append(rsp, nhentai.ComicInfoTag{
Id: tags[i].ID,
Name: tags[i].Name,
Count: tags[i].Count,
Type: tags[i].Type,
Url: tags[i].Url,
})
}
}
return rsp
}
func filterCover(covers []DownloadCover, id int) nhentai.ImageInfo {
for i := 0; i < len(covers); i++ {
if covers[i].ComicId == id {
return nhentai.ImageInfo{
T: covers[i].T,
W: covers[i].W,
H: covers[i].H,
}
}
}
return nhentai.ImageInfo{}
}
func filterCoverThumb(covers []DownloadCoverThumb, id int) nhentai.ImageInfo {
for i := 0; i < len(covers); i++ {
if covers[i].ComicId == id {
return nhentai.ImageInfo{
T: covers[i].T,
W: covers[i].W,
H: covers[i].H,
}
}
}
return nhentai.ImageInfo{}
}
type DownloadComicInfo struct {
nhentai.ComicInfo
DownloadStatus int `json:"download_status"`
}
func ResetAllDownload() {
mutex.Lock()
defer mutex.Unlock()
var err error
err = db.Exec("UPDATE download set download_status = 0 WHERE download_status = 2").Error
if err != nil {
panic(err)
}
err = db.Exec("UPDATE download_cover set download_status = 0 WHERE download_status = 2").Error
if err != nil {
panic(err)
}
err = db.Exec("UPDATE download_cover_thumb set download_status = 0 WHERE download_status = 2").Error
if err != nil {
panic(err)
}
err = db.Exec("UPDATE download_page set download_status = 0 WHERE download_status = 2").Error
if err != nil {
panic(err)
}
err = db.Exec("UPDATE download_page_thumb set download_status = 0 WHERE download_status = 2").Error
if err != nil {
panic(err)
}
}
func MarkComicDeleting(id int) {
mutex.Lock()
defer mutex.Unlock()
err := db.Model(&Download{}).Where("id = ?", id).Update("download_status", 3).Error
if err != nil {
panic(err)
}
}
func LoadFirstNeedDelete() *Download {
mutex.Lock()
defer mutex.Unlock()
download := Download{}
err := db.Where("download_status = 3").Order("download_created_time ASC").First(&download).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil
}
panic(err)
}
return &download
}
func DeletedComic(id int) {
mutex.Lock()
defer mutex.Unlock()
err := db.Transaction(func(tx *gorm.DB) error {
var err error
err = tx.Unscoped().Delete(&Download{}, "id = ?", id).Error
if err != nil {
return err
}
err = tx.Unscoped().Delete(&DownloadCover{}, "comic_id = ?", id).Error
if err != nil {
return err
}
err = tx.Unscoped().Delete(&DownloadPage{}, "comic_id = ?", id).Error
if err != nil {
return err
}
err = tx.Unscoped().Delete(&DownloadTag{}, "comic_id = ?", id).Error
if err != nil {
return err
}
err = tx.Unscoped().Delete(&DownloadCoverThumb{}, "comic_id = ?", id).Error
if err != nil {
return err
}
err = tx.Unscoped().Delete(&DownloadPageThumb{}, "comic_id = ?", id).Error
if err != nil {
return err
}
return nil
})
if err != nil {
panic(err)
}
}
================================================
FILE: go/nhentai/database/cache/cache.go
================================================
package cache
import (
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"nhentai/nhentai/constant"
"path"
"sync"
"time"
)
var mutex = sync.Mutex{}
var db *gorm.DB
type NetworkCache struct {
gorm.Model
K string `gorm:"index:uk_k,unique"`
V string
}
type ImageCache struct {
gorm.Model
Url string `gorm:"index:uk_url,unique" json:"fileServer"`
LocalPath string `json:"localPath"`
FileSize int64 `json:"fileSize"`
}
func Init(databaseDir string) {
var err error
db, err = gorm.Open(sqlite.Open(path.Join(databaseDir, "cache.db")), constant.GormConfig)
if err != nil {
panic(err)
}
db.AutoMigrate(&NetworkCache{})
db.AutoMigrate(&ImageCache{})
}
func LoadCache(key string, expire time.Duration) (string, error) {
mutex.Lock()
defer mutex.Unlock()
var cache NetworkCache
err := db.First(&cache, "k = ? AND updated_at > ?", key, time.Now().Add(expire*-1)).Error
if err == nil {
return cache.V, nil
}
if gorm.ErrRecordNotFound == err {
return "", nil
}
return "", err
}
func SaveCache(key string, value string) error {
mutex.Lock()
defer mutex.Unlock()
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "k"}},
DoUpdates: clause.AssignmentColumns([]string{"created_at", "updated_at", "v"}),
}).Create(&NetworkCache{
K: key,
V: value,
}).Error
}
func RemoveCache(key string) error {
mutex.Lock()
defer mutex.Unlock()
err := db.Unscoped().Delete(&NetworkCache{}, "k = ?", key).Error
if err == gorm.ErrRecordNotFound {
return nil
}
return err
}
func RemoveCaches(like string) error {
mutex.Lock()
defer mutex.Unlock()
err := db.Unscoped().Delete(&NetworkCache{}, "k LIKE ?", like).Error
if err == gorm.ErrRecordNotFound {
return nil
}
return err
}
func RemoveAllCache() error {
mutex.Lock()
defer mutex.Unlock()
err := db.Unscoped().Delete(&NetworkCache{}, "1 = 1").Error
if err != nil {
return err
}
return db.Raw("VACUUM").Error
}
func RemoveEarliestCache(earliest time.Time) error {
mutex.Lock()
defer mutex.Unlock()
err := db.Unscoped().Where("strftime('%s',updated_at) < strftime('%s',?)", earliest).
Delete(&NetworkCache{}).Error
if err != nil {
return err
}
return db.Raw("VACUUM").Error
}
func SaveImageCache(remote *ImageCache) error {
mutex.Lock()
defer mutex.Unlock()
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "url"}},
DoUpdates: clause.AssignmentColumns([]string{
"updated_at",
"file_size",
"local_path",
}),
}).Create(remote).Error
}
func FindImageCache(url string) *ImageCache {
mutex.Lock()
defer mutex.Unlock()
var imageCache ImageCache
err := db.First(&imageCache, "url = ?", url).Error
if err != nil {
if err == gorm.ErrRecordNotFound {
return nil
} else {
panic(err)
}
}
return &imageCache
}
func RemoveAllImageCache() error {
mutex.Lock()
defer mutex.Unlock()
err := db.Unscoped().Delete(&ImageCache{}, "1 = 1").Error
if err != nil {
return err
}
return db.Raw("VACUUM").Error
}
func EarliestImageCache(earliest time.Time, pageSize int) ([]ImageCache, error) {
mutex.Lock()
defer mutex.Unlock()
var images []ImageCache
err := db.Where("strftime('%s',updated_at) < strftime('%s',?)", earliest).
Order("updated_at").Limit(pageSize).Find(&images).Error
return images, err
}
func DeleteImageCache(images []ImageCache) error {
mutex.Lock()
defer mutex.Unlock()
if len(images) == 0 {
return nil
}
ids := make([]uint, len(images))
for i := 0; i < len(images); i++ {
ids[i] = images[i].ID
}
return db.Unscoped().Model(&ImageCache{}).Delete("id in ?", ids).Error
}
================================================
FILE: go/nhentai/database/properties/properties.go
================================================
package properties
import (
"errors"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
"nhentai/nhentai/constant"
"path"
"strconv"
)
var db *gorm.DB
func Init(databaseDir string) {
var err error
db, err = gorm.Open(sqlite.Open(path.Join(databaseDir, "properties.db")), constant.GormConfig)
if err != nil {
panic(err)
}
db.AutoMigrate(&Property{})
}
type Property struct {
gorm.Model
K string `gorm:"index:uk_k,unique"`
V string
}
func LoadProperty(name string, defaultValue string) (string, error) {
var property Property
err := db.First(&property, "k", name).Error
if err == nil {
return property.V, nil
}
if gorm.ErrRecordNotFound == err {
return defaultValue, nil
}
panic(errors.New("?"))
}
func SaveProperty(name string, value string) error {
return db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "k"}},
DoUpdates: clause.AssignmentColumns([]string{"created_at", "updated_at", "v"}),
}).Create(&Property{
K: name,
V: value,
}).Error
}
func LoadBoolProperty(name string, defaultValue bool) (bool, error) {
stringValue, err := LoadProperty(name, strconv.FormatBool(defaultValue))
if err != nil {
return false, err
}
return strconv.ParseBool(stringValue)
}
func LoadIntProperty(name string, defaultValue int) (int, error) {
var property Property
err := db.First(&property, "k", name).Error
if err == nil {
return strconv.Atoi(property.V)
}
if gorm.ErrRecordNotFound == err {
return defaultValue, nil
}
panic(errors.New("?"))
}
================================================
FILE: go/nhentai/decodes.go
================================================
package nhentai
import (
"errors"
_ "golang.org/x/image/webp"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io/ioutil"
"net/http"
"nhentai/nhentai/database/cache"
"sync"
)
var mutexCounter = -1
var busMutex *sync.Mutex
var subMutexes []*sync.Mutex
func init() {
busMutex = &sync.Mutex{}
for i := 0; i < 5; i++ {
subMutexes = append(subMutexes, &sync.Mutex{})
}
}
// takeMutex 下载图片获取一个锁, 这样只能同时下载5张图片
func takeMutex() *sync.Mutex {
busMutex.Lock()
defer busMutex.Unlock()
mutexCounter = (mutexCounter + 1) % len(subMutexes)
return subMutexes[mutexCounter]
}
// 下载图片并decode
func decodeFromUrl(url string) ([]byte, error) {
m := takeMutex()
m.Lock()
defer m.Unlock()
request, err := http.NewRequest("GET", url, nil)
if err != nil {
return nil, err
}
response, err := client.Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
buff, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
println("NOT 200")
println(string(buff))
return nil, errors.New("code is not 200")
}
return buff, nil
}
// decodeFromCache 仅下载使用
func decodeFromRemote(url string) ([]byte, error) {
cache := cache.FindImageCache(url)
if cache != nil {
return ioutil.ReadFile(cacheImagePath(cache.LocalPath))
}
return nil, errors.New("not found")
}
================================================
FILE: go/nhentai/download.go
================================================
package nhentai
import (
"fmt"
"io/ioutil"
"nhentai/nhentai/constant"
"nhentai/nhentai/database/active"
"os"
"path"
"sync"
"time"
)
var initDownloadFlag bool
var downloadThreadCount = 1
var downloadThreadFetch = 100
var downloadRunning = false
var downloadRestart = false
func initDownload() {
if initDownloadFlag {
return
}
active.ResetAllDownload()
initDownloadFlag = true
downloadRunning = true
go downloadBegin()
}
// 下载周期中, 每个下载单元会调用此方法, 如果返回true应该停止当前动作
func downloadHasStop() bool {
if !downloadRunning {
return true
}
if downloadRestart {
downloadRestart = false
return true
}
return false
}
// 删除第一个需要删除的漫画, 成功删除返回true
func downloadDelete() bool {
needDelete := active.LoadFirstNeedDelete()
if needDelete != nil {
relativeFolder := fmt.Sprintf("%d/%d", needDelete.ID, needDelete.MediaId)
absoluteFolder := path.Join(downloadPath, relativeFolder)
err := os.RemoveAll(absoluteFolder)
if err != nil {
panic(err)
}
active.DeletedComic(needDelete.ID)
return true
}
return false
}
// 下载启动/重新启动会暂停三秒
func downloadBegin() {
time.Sleep(time.Second * 3)
// 每次下载完一个漫画, 或者启动的时候, 首先进行删除任务
for downloadDelete() {
}
if downloadHasStop() {
return
}
go downloadLoadComic()
}
// 加载第一个需要下载的漫画
func downloadLoadComic() {
if downloadHasStop() {
go downloadBegin()
return
}
// 找到第一个要下载的漫画, 查库有错误就停止, 因为这些错误很少出现, 一旦出现必然是严重的, 例如数据库文件突然被删除
downloadingComic, err := active.LoadFirstNeedDownload()
if err != nil {
panic(err)
}
if downloadingComic == nil {
println("没有找到要下载的漫画")
go downloadBegin()
return
}
go downloadProcessDownloadingComic(downloadingComic)
}
func downloadProcessDownloadingComic(downloadingComic *active.Download) {
if downloadHasStop() {
go downloadBegin()
return
}
//
relativeFolder := fmt.Sprintf("%d/%d", downloadingComic.ID, downloadingComic.MediaId)
absoluteFolder := path.Join(downloadPath, relativeFolder)
constant.ObtainDir(absoluteFolder)
// 下载封面
cover, err := active.TheDownloadCover(downloadingComic.ID)
if err != nil {
panic(err)
}
if cover.DownloadStatus == 0 {
buff, err := downloadDecodeUrl(cover.Url)
if buff != nil {
coverName := "cover"
relativeCover := path.Join(relativeFolder, coverName)
absoluteCover := path.Join(absoluteFolder, coverName)
err = ioutil.WriteFile(absoluteCover, buff, constant.CreateFileMode)
if err != nil {
panic(err)
}
active.SaveDownloadCoverStatus(downloadingComic.ID, 1, relativeCover)
} else {
active.SaveDownloadCoverStatus(downloadingComic.ID, 2, "")
}
}
// 下载封面缩略图
coverThumb, err := active.TheDownloadCoverThumb(downloadingComic.ID)
if err != nil {
panic(err)
}
if coverThumb.DownloadStatus == 0 {
buff, err := downloadDecodeUrl(coverThumb.Url)
if buff != nil {
coverName := "cover_thumb"
relativeCoverThumb := path.Join(relativeFolder, coverName)
absoluteCoverThumb := path.Join(absoluteFolder, coverName)
err = ioutil.WriteFile(absoluteCoverThumb, buff, constant.CreateFileMode)
if err != nil {
panic(err)
}
active.SaveDownloadCoverThumbStatus(downloadingComic.ID, 1, relativeCoverThumb)
} else {
active.SaveDownloadCoverThumbStatus(downloadingComic.ID, 2, "")
}
}
// 暂停检测
if downloadHasStop() {
go downloadBegin()
return
}
// 下载漫画
// WARNING 无限循环
for {
downloadingPictures, err := active.TheDownloadNeedDownloadPages(downloadingComic.ID, downloadThreadFetch)
if err != nil {
panic(err)
}
if len(downloadingPictures) == 0 {
break
}
// 多线程下载漫画
hasStop := func() bool {
channel := make(chan int, downloadThreadCount)
defer close(channel)
wg := sync.WaitGroup{}
for i := 0; i < len(downloadingPictures); i++ {
// 暂停检测
if downloadHasStop() {
wg.Wait()
return true
}
channel <- 0
wg.Add(1)
// 不放入携程, 防止i已经变化
pagePoint := &(downloadingPictures[i])
go func() {
// 下载漫画
buff, err := downloadDecodeUrl(pagePoint.Url)
if buff != nil {
pageName := fmt.Sprintf("p_%d", pagePoint.PageIndex)
relativePageName := path.Join(relativeFolder, pageName)
absolutePageName := path.Join(absoluteFolder, pageName)
err = ioutil.WriteFile(absolutePageName, buff, constant.CreateFileMode)
if err != nil {
panic(err)
}
active.SaveDownloadPageStatus(downloadingComic.ID, pagePoint.PageIndex, 1, relativePageName)
} else {
active.SaveDownloadPageStatus(downloadingComic.ID, pagePoint.PageIndex, 2, "")
}
// 下载漫画
<-channel
wg.Done()
}()
}
wg.Wait()
return false
}()
if hasStop {
go downloadBegin()
return
}
}
// 下载漫画
// WARNING 无限循环
for {
downloadingPictureThumbs, err := active.TheDownloadNeedDownloadPageThumbs(downloadingComic.ID, downloadThreadFetch)
if err != nil {
panic(err)
}
if len(downloadingPictureThumbs) == 0 {
break
}
// 多线程下载漫画
hasStop := func() bool {
channel := make(chan int, downloadThreadCount)
defer close(channel)
wg := sync.WaitGroup{}
for i := 0; i < len(downloadingPictureThumbs); i++ {
// 暂停检测
if downloadHasStop() {
wg.Wait()
return true
}
channel <- 0
wg.Add(1)
// 不放入携程, 防止i已经变化
pagePoint := &(downloadingPictureThumbs[i])
go func() {
//
buff, err := downloadDecodeUrl(pagePoint.Url)
if buff != nil {
pageThumbName := fmt.Sprintf("p_%d_t", pagePoint.PageIndex)
relativePageThumbName := path.Join(relativeFolder, pageThumbName)
absolutePageThumbName := path.Join(absoluteFolder, pageThumbName)
err = ioutil.WriteFile(absolutePageThumbName, buff, constant.CreateFileMode)
if err != nil {
panic(err)
}
err = active.SaveDownloadPageThumbStatus(downloadingComic.ID, pagePoint.PageIndex, 1, relativePageThumbName)
if err != nil {
panic(err)
}
} else {
err = active.SaveDownloadPageThumbStatus(downloadingComic.ID, pagePoint.PageIndex, 2, "")
if err != nil {
panic(err)
}
}
//
<-channel
wg.Done()
}()
}
wg.Wait()
return false
}()
if hasStop {
go downloadBegin()
return
}
}
// 总结下载进度
if active.DownloadCoverOk(downloadingComic.ID) && active.DownloadCoverThumbOk(downloadingComic.ID) &&
active.DownloadPageOk(downloadingComic.ID) && active.DownloadPageThumbOk(downloadingComic.ID) {
err := active.SaveDownloadStatus(downloadingComic.ID, 1)
if err != nil {
panic(err)
}
} else {
err := active.SaveDownloadStatus(downloadingComic.ID, 2)
if err != nil {
panic(err)
}
}
go downloadBegin()
}
func downloadDecodeUrl(url string) ([]byte, error) {
buff, err := decodeFromRemote(url)
if buff != nil {
return buff, nil
}
for i := 0; i < 5; i++ {
buff, err = decodeFromUrl(url)
if err != nil {
continue
}
if buff != nil {
return buff, nil
}
}
return nil, err
}
================================================
FILE: go/nhentai/locks.go
================================================
package nhentai
import (
"hash/fnv"
"sync"
)
var hashMutex []*sync.Mutex
func init() {
for i := 0; i < 32; i++ {
hashMutex = append(hashMutex, &sync.Mutex{})
}
}
// HashLock Hash一样的图片不同时处理
func HashLock(key string) *sync.Mutex {
hash := fnv.New32()
hash.Write([]byte(key))
return hashMutex[int(hash.Sum32()%uint32(len(hashMutex)))]
}
================================================
FILE: go/nhentai/nhentai.go
================================================
package nhentai
import (
"encoding/json"
"github.com/niuhuan/nhentai-go"
"github.com/pkg/errors"
"io/ioutil"
"nhentai/nhentai/constant"
"nhentai/nhentai/database/active"
"nhentai/nhentai/database/cache"
"nhentai/nhentai/database/properties"
"path"
"strconv"
)
var initFlag bool
var cachePath string
var downloadPath string
func InitNHentai(documentDir string) {
if initFlag {
return
}
initFlag = true
databaseDir := path.Join(documentDir, "database")
constant.ObtainDir(databaseDir)
properties.Init(databaseDir)
cache.Init(databaseDir)
active.Init(databaseDir)
cachePath = path.Join(documentDir, "cache")
constant.ObtainDir(cachePath)
downloadPath = path.Join(documentDir, "download")
constant.ObtainDir(downloadPath)
initClient()
go initDownload()
}
func cacheImagePath(aliasPath string) string {
return path.Join(cachePath, aliasPath)
}
var methods = map[string]func(string) (string, error){
"availableWebAddresses": availableWebAddresses,
"availableImgAddresses": availableImgAddresses,
"setProxy": setProxy,
"getProxy": getProxy,
"comics": comics,
"comicsByTagName": comicsByTagName,
"comicsBySearchRaw": comicsBySearchRaw,
"comicInfo": comicInfo,
"cacheImageByUrlPath": cacheImageByUrlPath,
"loadProperty": loadProperty,
"saveProperty": saveProperty,
"saveViewInfo": saveViewInfo,
"saveViewIndex": saveViewIndex,
"loadLastViewIndexByComicId": loadLastViewIndexByComicId,
"downloadComic": downloadComic,
"hasDownload": hasDownload,
"listDownloadComicInfo": listDownloadComicInfo,
"downloadSetDelete": downloadSetDelete,
"httpGet": httpGet,
"convertImageToJPEG100": convertImageToJPEG100,
"setCookie": setCookie,
"setUserAgent": setUserAgent,
}
func setUserAgent(s string) (string, error) {
client.UserAgent = s
return "", nil
}
func setCookie(s string) (string, error) {
client.Cookie = s
return "", nil
}
func FlatInvoke(method string, params string) (string, error) {
if method, ok := methods[method]; ok {
return method(params)
}
return "", errors.New("method not found (nhentai main)")
}
func saveProperty(params string) (string, error) {
var paramsStruct struct {
Name string `json:"name"`
Value string `json:"value"`
}
json.Unmarshal([]byte(params), ¶msStruct)
return "", properties.SaveProperty(paramsStruct.Name, paramsStruct.Value)
}
func loadProperty(params string) (string, error) {
var paramsStruct struct {
Name string `json:"name"`
DefaultValue string `json:"defaultValue"`
}
json.Unmarshal([]byte(params), ¶msStruct)
return properties.LoadProperty(paramsStruct.Name, paramsStruct.DefaultValue)
}
func saveViewInfo(params string) (string, error) {
var comic nhentai.ComicInfo
json.Unmarshal([]byte(params), &comic)
return "", active.SaveViewInfo(comic)
}
func saveViewIndex(params string) (string, error) {
var paramsStruct struct {
Info nhentai.ComicInfo `json:"info"`
Index int `json:"index"`
}
json.Unmarshal([]byte(params), ¶msStruct)
return "", active.SaveViewIndex(paramsStruct.Info, paramsStruct.Index)
}
func loadLastViewIndexByComicId(params string) (string, error) {
comicId, err := strconv.Atoi(params)
if err != nil {
return "", err
}
return serialize(active.LoadLastViewIndexByComicId(comicId))
}
func downloadComic(params string) (string, error) {
var comic nhentai.ComicInfo
json.Unmarshal([]byte(params), &comic)
return "", active.CreateDownload(comic)
}
func hasDownload(params string) (string, error) {
comicId, err := strconv.Atoi(params)
if err != nil {
return "", err
}
return strconv.FormatBool(active.HasDownload(comicId)), nil
}
func listDownloadComicInfo(s string) (string, error) {
return serialize(active.ListDownloadComicInfo(), nil)
}
func downloadSetDelete(params string) (string, error) {
comicId, err := strconv.Atoi(params)
if err != nil {
return "", err
}
active.MarkComicDeleting(comicId)
downloadRestart = true
return "", nil
}
func httpGet(url string) (string, error) {
rsp, err := client.Get(url)
if err != nil {
return "", err
}
defer rsp.Body.Close()
buff, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return "", err
}
return string(buff), nil
}
================================================
FILE: go/packaging/darwin-bundle/{{.applicationName}} {{.version}}.app/Contents/Info.plist.tmpl
================================================
CFBundleDevelopmentRegion
English
CFBundleExecutable
{{.executableName}}
CFBundleGetInfoString
{{.description}}
CFBundleIconFile
icon.icns
NSHighResolutionCapable
CFBundleIdentifier
{{.organizationName}}.{{.packageName}}
CFBundleInfoDictionaryVersion
6.0
CFBundleLongVersionString
{{.version}}
CFBundleName
{{.applicationName}}
CFBundlePackageType
APPL
CFBundleShortVersionString
{{.version}}
CFBundleSignature
{{.organizationName}}.{{.packageName}}
CFBundleVersion
{{.version}}
CSResourcesFileMapped
NSHumanReadableCopyright
NSPrincipalClass
NSApplication
================================================
FILE: go/packaging/linux-appimage/AppRun.tmpl
================================================
#!/bin/sh
cd "$(dirname "$0")"
exec ./build/{{.executableName}}
================================================
FILE: go/packaging/linux-appimage/{{.packageName}}.desktop.tmpl
================================================
[Desktop Entry]
Version=1.0
Type=Application
Terminal=false
Categories=
Comment={{.description}}
Name={{.applicationName}}
Icon={{.iconPath}}
Exec={{.executablePath}}
================================================
FILE: ios/.gitignore
================================================
**/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
================================================
FILE: ios/Flutter/AppFrameworkInfo.plist
================================================
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
================================================
FILE: ios/Flutter/Debug.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "Generated.xcconfig"
================================================
FILE: ios/Flutter/Release.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "Generated.xcconfig"
================================================
FILE: ios/Podfile
================================================
# 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
================================================
FILE: ios/Runner/AppDelegate.swift
================================================
import UIKit
import Flutter
import Mobile
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let applicationSupportsPath = NSSearchPathForDirectoriesInDomains(.applicationSupportDirectory, .userDomainMask, true)[0]
MobileMigration(documentsPath, applicationSupportsPath)
MobileInitApplication(applicationSupportsPath)
let controller = self.window.rootViewController as! FlutterViewController
let channel = FlutterMethodChannel.init(name: "nhentai", binaryMessenger: controller as! FlutterBinaryMessenger)
channel.setMethodCallHandler { (call, result) in
Thread {
if call.method == "flatInvoke" {
if let args = call.arguments as? Dictionary,
let method = args["method"] as? String,
let params = args["params"] as? String{
var error: NSError?
let data = MobileFlatInvoke(method, params, &error)
if error != nil {
result(FlutterError(code: "", message: error?.localizedDescription, details: ""))
}else{
result(data)
}
}else{
result(FlutterError(code: "", message: "params error", details: ""))
}
}
else if call.method == "saveFileToImage"{
if let args = call.arguments as? Dictionary,
let path = args["path"] as? String{
do {
let fileURL: URL = URL(fileURLWithPath: path)
let imageData = try Data(contentsOf: fileURL)
if let uiImage = UIImage(data: imageData) {
UIImageWriteToSavedPhotosAlbum(uiImage, nil, nil, nil)
result("OK")
}else{
result(FlutterError(code: "", message: "Error loading image ", details: ""))
}
} catch {
result(FlutterError(code: "", message: "Error loading image : \(error)", details: ""))
}
}else{
result(FlutterError(code: "", message: "params error", details: ""))
}
}
else{
result(FlutterMethodNotImplemented)
}
}.start()
}
GeneratedPluginRegistrant.register(with: self)
return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}
}
================================================
FILE: ios/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"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"
}
}
================================================
FILE: ios/Runner/Assets.xcassets/LaunchImage.imageset/Contents.json
================================================
{
"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"
}
}
================================================
FILE: ios/Runner/Assets.xcassets/LaunchImage.imageset/README.md
================================================
# 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.
================================================
FILE: ios/Runner/Base.lproj/LaunchScreen.storyboard
================================================
================================================
FILE: ios/Runner/Base.lproj/Main.storyboard
================================================
================================================
FILE: ios/Runner/Info.plist
================================================
UIFileSharingEnabled
LSSupportsOpeningDocumentsInPlace
LSApplicationCategoryType
public.app-category.entertainment
NSPhotoLibraryAddUsageDescription
Save images
NSPhotoLibraryUsageDescription
Usage images
CFBundleLocalizations
zh
en
CFBundleDevelopmentRegion
$(DEVELOPMENT_LANGUAGE)
CFBundleExecutable
$(EXECUTABLE_NAME)
CFBundleIdentifier
$(PRODUCT_BUNDLE_IDENTIFIER)
CFBundleInfoDictionaryVersion
6.0
CFBundleName
nhentai
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
================================================
FILE: ios/Runner/Runner-Bridging-Header.h
================================================
#import "GeneratedPluginRegistrant.h"
================================================
FILE: ios/Runner.xcodeproj/project.pbxproj
================================================
// !$*UTF8*$!
{
archiveVersion = 1;
classes = {
};
objectVersion = 52;
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 */; };
62952ADFC370BEF926A4F77B /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = CB240B0E3D4CEE5A30176A71 /* 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 */; };
DDC69A7A275E58C100118CCB /* Mobile.xcframework in Frameworks */ = {isa = PBXBuildFile; fileRef = DDC69A79275E58C100118CCB /* Mobile.xcframework */; };
/* 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 = ""; };
3B3967151E833CAA004F5970 /* AppFrameworkInfo.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = AppFrameworkInfo.plist; path = Flutter/AppFrameworkInfo.plist; sourceTree = ""; };
4B2752C74691B678911F7767 /* 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 = ""; };
5B0F53137A8E31481FC50D89 /* 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 = ""; };
68115AA88E6B5269DEDB93D6 /* 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 = ""; };
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 = ""; };
CB240B0E3D4CEE5A30176A71 /* Pods_Runner.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Runner.framework; sourceTree = BUILT_PRODUCTS_DIR; };
DDC69A79275E58C100118CCB /* Mobile.xcframework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.xcframework; name = Mobile.xcframework; path = ../go/mobile/lib/Mobile.xcframework; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
97C146EB1CF9000F007C117D /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
62952ADFC370BEF926A4F77B /* Pods_Runner.framework in Frameworks */,
DDC69A7A275E58C100118CCB /* Mobile.xcframework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
74F492A9073C29BACAC4C529 /* Pods */ = {
isa = PBXGroup;
children = (
4B2752C74691B678911F7767 /* Pods-Runner.debug.xcconfig */,
5B0F53137A8E31481FC50D89 /* Pods-Runner.release.xcconfig */,
68115AA88E6B5269DEDB93D6 /* Pods-Runner.profile.xcconfig */,
);
path = Pods;
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 = (
DDC69A79275E58C100118CCB /* Mobile.xcframework */,
9740EEB11CF90186004384FC /* Flutter */,
97C146F01CF9000F007C117D /* Runner */,
97C146EF1CF9000F007C117D /* Products */,
74F492A9073C29BACAC4C529 /* Pods */,
DBE6F67E3D483577BA88D014 /* 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 = "";
};
DBE6F67E3D483577BA88D014 /* Frameworks */ = {
isa = PBXGroup;
children = (
CB240B0E3D4CEE5A30176A71 /* Pods_Runner.framework */,
);
name = Frameworks;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
97C146ED1CF9000F007C117D /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 97C147051CF9000F007C117D /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
F3AD040E0E519A573BB3125F /* [CP] Check Pods Manifest.lock */,
9740EEB61CF901F6004384FC /* Run Script */,
97C146EA1CF9000F007C117D /* Sources */,
97C146EB1CF9000F007C117D /* Frameworks */,
97C146EC1CF9000F007C117D /* Resources */,
9705A1C41CF9048500538489 /* Embed Frameworks */,
3B06AD1E1E4923F5004D2608 /* Thin Binary */,
45B4C6EDA02A2684AB90F0C8 /* [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 */
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";
};
45B4C6EDA02A2684AB90F0C8 /* [CP] Embed Pods Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
files = (
);
inputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-input-files.xcfilelist",
);
name = "[CP] Embed Pods Frameworks";
outputFileListPaths = (
"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks-${CONFIGURATION}-output-files.xcfilelist",
);
runOnlyForDeploymentPostprocessing = 0;
shellPath = /bin/sh;
shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Runner/Pods-Runner-frameworks.sh\"\n";
showEnvVarsInLog = 0;
};
9740EEB61CF901F6004384FC /* Run Script */ = {
isa = PBXShellScriptBuildPhase;
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";
};
F3AD040E0E519A573BB3125F /* [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 */
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;
FRAMEWORK_SEARCH_PATHS = ../go/mobile/lib;
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;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = niuhuan.nhentai;
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;
FRAMEWORK_SEARCH_PATHS = ../go/mobile/lib;
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;
FRAMEWORK_SEARCH_PATHS = ../go/mobile/lib;
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;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = niuhuan.nhentai;
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;
IPHONEOS_DEPLOYMENT_TARGET = 11.0;
LD_RUNPATH_SEARCH_PATHS = (
"$(inherited)",
"@executable_path/Frameworks",
);
PRODUCT_BUNDLE_IDENTIFIER = niuhuan.nhentai;
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 */;
}
================================================
FILE: ios/Runner.xcodeproj/project.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: ios/Runner.xcodeproj/project.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
================================================
PreviewsEnabled
================================================
FILE: ios/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
================================================
================================================
FILE: ios/Runner.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: ios/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: ios/Runner.xcworkspace/xcshareddata/WorkspaceSettings.xcsettings
================================================
PreviewsEnabled
================================================
FILE: l10n.yaml
================================================
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
untranslated-messages-file: desiredFileName.txt
================================================
FILE: lib/basic/channels/nhentai.dart
================================================
import 'dart:convert';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:nhentai/basic/entities/entities.dart';
const nHentai = NHentai._();
class NHentai {
const NHentai._();
static const _channel = MethodChannel("nhentai");
/// 平铺调用, 为了直接与golang进行通信
Future _flatInvoke(String method, dynamic params) async {
return await _channel.invokeMethod("flatInvoke", {
"method": method,
"params": params is String ? params : jsonEncode(params),
});
}
/// 设置代理
Future setProxy(String proxyUrl) {
return _flatInvoke("setProxy", proxyUrl);
}
/// 获取代理
Future getProxy() {
return _flatInvoke("getProxy", "");
}
/// 获取漫画
Future comics(int page) async {
return ComicPageData.fromJson(
jsonDecode(await _flatInvoke("comics", "$page")),
);
}
/// 获取漫画
Future comicsByTagName(String tagName, int page) async {
return ComicPageData.fromJson(jsonDecode(
await _flatInvoke("comicsByTagName", {
"tag_name": tagName,
"page": page,
}),
));
}
/// 获取漫画
Future comicsBySearchRaw(String raw, int page) async {
return ComicPageData.fromJson(jsonDecode(
await _flatInvoke("comicsBySearchRaw", {
"raw": raw,
"page": page,
}),
));
}
/// 漫画详情
Future comicInfo(int comicId) async {
return ComicInfo.formJson(jsonDecode(
await _flatInvoke("comicInfo", "$comicId"),
));
}
/// 加载图片 (返回路径)
Future cacheImageByUrlPath(String url) async {
return await _flatInvoke("cacheImageByUrlPath", url);
}
/// 手机端保存图片
Future saveFileToImage(String path) async {
return _channel.invokeMethod("saveFileToImage", {
"path": path,
});
}
/// 桌面端保存图片
Future convertImageToJPEG100(String path, String dir) async {
return _flatInvoke("convertImageToJPEG100", {
"path": path,
"dir": dir,
});
}
/// 安卓版本号
Future androidVersion() async {
if (Platform.isAndroid) {
return await _channel.invokeMethod("androidVersion", {});
}
return 0;
}
/// 读取配置文件
Future loadProperty(String propertyName, String defaultValue) async {
return await _flatInvoke("loadProperty", {
"name": propertyName,
"defaultValue": defaultValue,
});
}
/// 保存配置文件
Future saveProperty(String propertyName, String value) {
return _flatInvoke("saveProperty", {
"name": propertyName,
"value": value,
});
}
/// 更新浏览记录 (打开详情页面时)
Future saveViewInfo(ComicInfo info) {
return _flatInvoke("saveViewInfo", info);
}
/// 更新浏览记录 (打开页面滚动时)
Future saveViewIndex(ComicInfo info, int index) {
return _flatInvoke("saveViewIndex", {
"info": info,
"index": index,
});
}
/// 获取最后浏览的页数
Future loadLastViewIndexByComicId(int comicId) async {
return int.parse(await _flatInvoke("loadLastViewIndexByComicId", comicId));
}
/// 创建一个下载
Future downloadComic(ComicInfo comicInfo) {
return _flatInvoke("downloadComic", comicInfo);
}
/// 检查有没有下载过
Future hasDownload(int comicId) async {
return "true" == await _flatInvoke("hasDownload", "$comicId");
}
/// 获取所有下载列表
Future> listDownloadComicInfo() async {
return List.of(jsonDecode(await _flatInvoke("listDownloadComicInfo", "")))
.map((e) => DownloadComicInfo.formJson(e))
.toList()
.cast();
}
/// 删除一个下载
Future downloadSetDelete(int comicId) async {
return _flatInvoke("downloadSetDelete", "$comicId");
}
/// HTTP-GET-STRING
Future httpGet(String url) async {
return await _flatInvoke("httpGet", url);
}
Future setCookie(String cookies) async {
return await _flatInvoke("setCookie", cookies);
}
Future setUserAgent(String s) async {
return await _flatInvoke("setUserAgent", s);
}
}
================================================
FILE: lib/basic/common/common.dart
================================================
import 'package:app_links/app_links.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter_styled_toast/flutter_styled_toast.dart';
/// 显示一个toast
void defaultToast(BuildContext context, String title) {
showToast(
title,
context: context,
position: StyledToastPosition.center,
animation: StyledToastAnimation.scale,
reverseAnimation: StyledToastAnimation.fade,
duration: const Duration(seconds: 4),
animDuration: const Duration(seconds: 1),
curve: Curves.elasticOut,
reverseCurve: Curves.linear,
);
}
/// 显示一个确认框, 用户关闭弹窗以及选择否都会返回false, 仅当用户选择确定时返回true
Future confirmDialog(BuildContext context, String title,
{String content = ""}) async {
return await showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: content == ""
? []
: [
Text(content),
],
),
),
actions: [
MaterialButton(
child: Text(AppLocalizations.of(context)!.cancel),
onPressed: () {
Navigator.of(context).pop(false);
},
),
MaterialButton(
child: Text(AppLocalizations.of(context)!.ok),
onPressed: () {
Navigator.of(context).pop(true);
},
),
],
)) ??
false;
}
/// 显示一个消息提示框
Future alertDialog(BuildContext context, String title, String content) {
return showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: [
Text(content),
],
),
),
actions: [
MaterialButton(
child: Text('确定'),
onPressed: () {
Navigator.of(context).pop();
},
),
],
));
}
/// stream-filter的替代方法
List filteredList(List list, bool Function(T) filter) {
List result = [];
list.forEach((element) {
if (filter(element)) {
result.add(element);
}
});
return result;
}
/// 创建一个单选对话框, 用户取消选择返回null, 否则返回所选内容
Future chooseListDialog(
BuildContext context, String title, List items,
{String? tips}) async {
List widgets = [];
if (tips != null) {
widgets.add(Container(
padding: const EdgeInsets.fromLTRB(15, 5, 15, 15),
child: Text(tips),
));
}
widgets.addAll(items.map((e) => SimpleDialogOption(
onPressed: () {
Navigator.of(context).pop(e);
},
child: Text('$e'),
)));
return showDialog(
context: context,
builder: (BuildContext context) {
return SimpleDialog(
title: Text(title),
children: widgets,
);
},
);
}
/// 创建一个单选对话框, 用户取消选择返回null, 否则返回所选内容(value)
Future chooseMapDialog(
BuildContext buildContext, Map values, String title) async {
return await showDialog(
context: buildContext,
builder: (BuildContext context) {
return SimpleDialog(
title: Text(title),
children: values.entries
.map((e) => SimpleDialogOption(
child: Text(e.key),
onPressed: () {
Navigator.of(context).pop(e.value);
},
))
.toList(),
);
},
);
}
/// 输入对话框1
var _controller = TextEditingController.fromValue(TextEditingValue(text: ''));
Future displayTextInputDialog(
BuildContext context,
String title,
String hint,
String src,
String desc,
) {
_controller.text = src;
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: [
TextField(
controller: _controller,
decoration: InputDecoration(hintText: hint),
),
desc.isEmpty
? Container()
: Container(
padding: const EdgeInsets.only(top: 20, bottom: 10),
child: Text(
desc,
style: TextStyle(
fontSize: 12,
color: Theme.of(context)
.textTheme
.bodyText1
?.color
?.withOpacity(.5)),
),
),
],
),
),
actions: [
MaterialButton(
child: const Text('取消'),
onPressed: () {
Navigator.of(context).pop();
},
),
MaterialButton(
child: const Text('确认'),
onPressed: () {
Navigator.of(context).pop(_controller.text);
},
),
],
);
},
);
}
/// 将字符串前面加0直至满足len位
String add0(int num, int len) {
var rsp = "$num";
while (rsp.length < len) {
rsp = "0$rsp";
}
return rsp;
}
/// 格式化时间 2012-34-56
String formatTimeToDate(String str) {
try {
var c = DateTime.parse(str);
return "${add0(c.year, 4)}-${add0(c.month, 2)}-${add0(c.day, 2)}";
} catch (e) {
return "-";
}
}
//
// /// 格式化时间 2012-34-56 12:34:56
// String formatTimeToDateTime(String str) {
// try {
// var c = DateTime.parse(str).add(Duration(hours: currentTimeOffsetHour()));
// return "${add0(c.year, 4)}-${add0(c.month, 2)}-${add0(c.day, 2)} ${add0(c.hour, 2)}:${add0(c.minute, 2)}";
// } catch (e) {
// return "-";
// }
// }
/// 输入对话框2
final TextEditingController _textEditController =
TextEditingController(text: '');
Future inputString(BuildContext context, String title,
{String hint = ""}) async {
_textEditController.clear();
return showDialog(
context: context,
builder: (context) {
return AlertDialog(
content: Card(
child: SingleChildScrollView(
child: ListBody(
children: [
Text(title),
Container(
child: TextField(
controller: _textEditController,
decoration: new InputDecoration(
labelText: "$hint",
),
),
),
],
),
),
),
actions: [
MaterialButton(
onPressed: () {
Navigator.pop(context);
},
child: Text('取消'),
),
MaterialButton(
onPressed: () {
Navigator.pop(context, _textEditController.text);
},
child: Text('确定'),
),
],
);
},
);
}
================================================
FILE: lib/basic/common/cross.dart
================================================
/// 与平台交互的操作
import 'dart:io';
import 'package:clipboard/clipboard.dart';
import 'package:filesystem_picker/filesystem_picker.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:url_launcher/url_launcher.dart';
import 'common.dart';
/// 复制内容到剪切板
void copyToClipBoard(BuildContext context, String string) {
if (Platform.isWindows || Platform.isMacOS) {
FlutterClipboard.copy(string);
defaultToast(context, "已复制到剪切板");
} else if (Platform.isAndroid) {
FlutterClipboard.copy(string);
defaultToast(context, "已复制到剪切板");
}
}
/// 打开web页面
Future openUrl(String url) async {
if (await canLaunch(url)) {
await launch(
url,
forceSafariVC: false,
);
}
}
/// 保存图片
Future saveImage(String path, BuildContext context) async {
Future? future;
if (Platform.isIOS) {
future = nHentai.saveFileToImage(path);
} else if (Platform.isAndroid) {
future = _saveImageAndroid(path, context);
} else if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
String? folder = await chooseFolder(context);
if (folder != null) {
future = nHentai.convertImageToJPEG100(path, folder);
}
} else {
defaultToast(context, '暂不支持该平台');
return;
}
if (future == null) {
defaultToast(context, '保存取消');
return;
}
try {
await future;
defaultToast(context, '保存成功');
} catch (e, s) {
print("$e\n$s");
defaultToast(context, '保存失败');
}
}
/// 保存图片且保持静默, 用于批量导出到相册
Future saveImageQuiet(String path, BuildContext context) async {
if (Platform.isIOS) {
return nHentai.saveFileToImage(path);
} else if (Platform.isAndroid) {
return _saveImageAndroid(path, context);
} else {
throw Exception("only mobile");
}
}
Future _saveImageAndroid(String path, BuildContext context) async {
var p = await Permission.storage.request();
if (!p.isGranted) {
return;
}
return nHentai.saveFileToImage(path);
}
/// 选择一个文件夹用于保存文件
Future chooseFolder(BuildContext context) async {
return FilesystemPicker.open(
title: '选择一个文件夹',
pickText: '将文件保存到这里',
context: context,
fsType: FilesystemType.folder,
rootDirectory: Directory(await currentChooserRoot()),
);
}
/// 复制对话框
void confirmCopy(BuildContext context, String content) async {
if (await confirmDialog(context, "复制", content: content)) {
copyToClipBoard(context, content);
}
}
Future currentChooserRoot() async {
if (Platform.isAndroid) {
if (await nHentai.androidVersion() >= 30) {
if (!(await Permission.manageExternalStorage.request()).isGranted) {
throw Exception("申请权限被拒绝");
}
} else {
if (!(await Permission.storage.request()).isGranted) {
throw Exception("申请权限被拒绝");
}
}
}
if (Platform.isWindows) {
return '/';
} else if (Platform.isMacOS) {
return '/Users';
} else if (Platform.isLinux) {
return '/';
} else if (Platform.isAndroid) {
return '/storage/emulated/0';
} else {
throw 'error';
}
}
================================================
FILE: lib/basic/common/error_types.dart
================================================
const ERROR_TYPE_NETWORK = "NETWORK_ERROR";
const ERROR_TYPE_PERMISSION = "PERMISSION_ERROR";
const ERROR_TYPE_TIME = "TIME_ERROR";
const ERROR_TYPE_UNDER_REVIEW = "UNDER_VIEW_ERROR";
// 错误的类型, 方便照展示和谐的提示
String errorType(String error) {
// EXCEPTION
// Get "https://****": net/http: TLS handshake timeout
// Get "https://****": proxyconnect tcp: dial tcp 192.168.123.217:1080: connect: connection refused
// Get "https://****": context deadline exceeded (Client.Timeout exceeded while awaiting headers)
if (error.contains("timeout") ||
error.contains("connection refused") ||
error.contains("deadline") ||
error.contains("connection abort")) {
return ERROR_TYPE_NETWORK;
}
if (error.contains("permission denied")) {
return ERROR_TYPE_PERMISSION;
}
if (error.contains("time is not synchronize")) {
return ERROR_TYPE_TIME;
}
if (error.contains("under review")) {
return ERROR_TYPE_UNDER_REVIEW;
}
return "";
}
================================================
FILE: lib/basic/configs/proxy.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
const _propertyName = "proxy";
late String _proxy;
Future initProxy() async {
_proxy = await nHentai.getProxy();
}
String currentProxy() {
return _proxy;
}
Future chooseProxy(BuildContext context) async {
final newProxy = await displayTextInputDialog(
context,
AppLocalizations.of(context)!.proxy,
"socks5://host:port/",
_proxy,
AppLocalizations.of(context)!.inputProxyDesc);
if (newProxy != null) {
await nHentai.saveProperty(_propertyName, newProxy);
_proxy = newProxy;
}
}
Widget proxySetting() {
return StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return ListTile(
title: Text(
AppLocalizations.of(context)!.proxy,
),
subtitle: Text(_proxy),
onTap: () async {
await chooseProxy(context);
setState(() {});
},
);
},
);
}
================================================
FILE: lib/basic/configs/reader_direction.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
enum ReaderDirection {
topToBottom,
leftToRight,
rightToLeft,
}
const _propertyName = "readerDirection";
late ReaderDirection _readerDirection;
Future initReaderDirection() async {
_readerDirection = _fromString(await nHentai.loadProperty(_propertyName, ""));
}
ReaderDirection _fromString(String valueForm) {
for (var value in ReaderDirection.values) {
if (value.toString() == valueForm) {
return value;
}
}
return ReaderDirection.values.first;
}
ReaderDirection currentReaderDirection() {
return _readerDirection;
}
String readerDirectionName(ReaderDirection direction, BuildContext context) {
switch (direction) {
case ReaderDirection.topToBottom:
return AppLocalizations.of(context)!.topToBottom;
case ReaderDirection.leftToRight:
return AppLocalizations.of(context)!.leftToRight;
case ReaderDirection.rightToLeft:
return AppLocalizations.of(context)!.rightToLeft;
}
}
Future chooseReaderDirection(BuildContext context) async {
final Map map = {};
for (var element in ReaderDirection.values) {
map[readerDirectionName(element, context)] = element;
}
final newReaderDirection = await chooseMapDialog(
context,
map,
AppLocalizations.of(context)!.chooseReaderDirection,
);
if (newReaderDirection != null) {
await nHentai.saveProperty(_propertyName, "$newReaderDirection");
_readerDirection = newReaderDirection;
}
}
================================================
FILE: lib/basic/configs/reader_type.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
enum ReaderType {
webtoon,
gallery,
}
const _propertyName = "readerType";
late ReaderType _readerType;
Future initReaderType() async {
_readerType = _fromString(await nHentai.loadProperty(_propertyName, ""));
}
ReaderType _fromString(String valueForm) {
for (var value in ReaderType.values) {
if (value.toString() == valueForm) {
return value;
}
}
return ReaderType.values.first;
}
ReaderType currentReaderType() {
return _readerType;
}
String readerTypeName(ReaderType type, BuildContext context) {
switch (type) {
case ReaderType.webtoon:
return AppLocalizations.of(context)!.webtoon;
case ReaderType.gallery:
return AppLocalizations.of(context)!.gallery;
}
}
Future chooseReaderType(BuildContext context) async {
final Map map = {};
for (var element in ReaderType.values) {
map[readerTypeName(element, context)] = element;
}
final newReaderType = await chooseMapDialog(
context,
map,
AppLocalizations.of(context)!.chooseReaderType,
);
if (newReaderType != null) {
await nHentai.saveProperty(_propertyName, "$newReaderType");
_readerType = newReaderType;
}
}
================================================
FILE: lib/basic/configs/themes.dart
================================================
/// 主题
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:event/event.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
// 字体相关
const _fontFamilyProperty = "fontFamily";
String? _fontFamily;
Future initFont() async {
var defaultFont = "";
_fontFamily = await nHentai.loadProperty(_fontFamilyProperty, defaultFont);
}
ThemeData _fontThemeData(bool dark) {
return ThemeData(
brightness: dark ? Brightness.dark : Brightness.light,
fontFamily: _fontFamily == "" ? null : _fontFamily,
);
}
Future inputFont(BuildContext context) async {
var font = await displayTextInputDialog(
context, "字体", "请输入字体", "$_fontFamily",
"请输入字体的名称, 例如宋体/黑体, 如果您保存后没有发生变化, 说明字体无法使用或名称错误, 可以去参考C:\\Windows\\Fonts寻找您的字体。",
);
if (font != null) {
await nHentai.saveProperty(_fontFamilyProperty, font);
_fontFamily = font;
_changeThemeByCode(_themeCode);
}
}
Widget fontSetting() {
return StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return ListTile(
title: Text("字体"),
subtitle: Text("$_fontFamily"),
onTap: () async {
await inputFont(context);
setState(() {});
},
);
},
);
}
// 主题相关
// 主题包
abstract class _ThemePackage {
String code();
String name();
ThemeData themeData(ThemeData rawData);
}
class _OriginTheme extends _ThemePackage {
@override
String code() => "origin";
@override
String name() => "ORIGIN";
@override
ThemeData themeData(ThemeData rawData) => rawData;
}
class _PinkTheme extends _ThemePackage {
@override
String code() => "pink";
@override
String name() => "PINK";
@override
ThemeData themeData(ThemeData rawData) =>
rawData.copyWith(
brightness: Brightness.light,
colorScheme: ColorScheme.light(
secondary: Colors.pink.shade200,
),
appBarTheme: AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.light,
color: Colors.pink.shade200,
iconTheme: const IconThemeData(
color: Colors.white,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
selectedItemColor: Colors.pink[300],
unselectedItemColor: Colors.grey[500],
),
dividerColor: Colors.grey.shade200,
primaryColor: Colors.pink.shade200,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.pink.shade200,
selectionColor: Colors.pink.shade300.withAlpha(150),
selectionHandleColor: Colors.pink.shade300.withAlpha(200),
),
inputDecorationTheme: InputDecorationTheme(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.pink.shade200),
),
),
);
}
class _BlackTheme extends _ThemePackage {
@override
String code() => "black";
@override
String name() => "BLACK";
@override
ThemeData themeData(ThemeData rawData) =>
rawData.copyWith(
brightness: Brightness.light,
colorScheme: ColorScheme.light(
secondary: Colors.pink.shade200,
),
appBarTheme: AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.light,
color: Colors.grey.shade800,
iconTheme: const IconThemeData(
color: Colors.white,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey[400],
backgroundColor: Colors.grey.shade800,
),
dividerColor: Colors.grey.shade200,
primaryColor: Colors.pink.shade200,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.pink.shade200,
selectionColor: Colors.pink.shade300.withAlpha(150),
selectionHandleColor: Colors.pink.shade300.withAlpha(200),
),
inputDecorationTheme: InputDecorationTheme(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.pink.shade200),
),
),
);
}
class _DarkTheme extends _ThemePackage {
@override
String code() => "dark";
@override
String name() => "DARK";
@override
ThemeData themeData(ThemeData rawData) =>
rawData.copyWith(
brightness: Brightness.light,
colorScheme: ColorScheme.light(
secondary: Colors.pink.shade200,
),
appBarTheme: const AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.light,
color: Color(0xFF1E1E1E),
iconTheme: IconThemeData(
color: Colors.white,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
selectedItemColor: Colors.white,
unselectedItemColor: Colors.grey.shade300,
backgroundColor: Colors.grey.shade900,
),
primaryColor: Colors.pink.shade200,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.pink.shade200,
selectionColor: Colors.pink.shade300.withAlpha(150),
selectionHandleColor: Colors.pink.shade300.withAlpha(200),
),
inputDecorationTheme: InputDecorationTheme(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.pink.shade200),
),
),
);
}
class _DustyBlueTheme extends _ThemePackage {
@override
String code() => "dustyBlue";
@override
String name() => "DUSTY BLUE";
@override
ThemeData themeData(ThemeData rawData) =>
rawData.copyWith(
scaffoldBackgroundColor: Color.alphaBlend(
Color(0x11999999), Color(0xff20253b)),
cardColor: Color.alphaBlend(Color(0x11AAAAAA), Color(0xff20253b)),
brightness: Brightness.light,
colorScheme: ColorScheme.light(
secondary: Colors.blue.shade200,
),
appBarTheme: AppBarTheme(
systemOverlayStyle: SystemUiOverlayStyle.light,
color: Color(0xff20253b),
iconTheme: IconThemeData(
color: Colors.white,
),
),
bottomNavigationBarTheme: BottomNavigationBarThemeData(
backgroundColor: Color(0xff191b26),
selectedItemColor: Colors.blue.shade200,
unselectedItemColor: Colors.grey.shade500,
),
dividerColor: Colors.grey.shade800,
primaryColor: Colors.blue.shade200,
textSelectionTheme: TextSelectionThemeData(
cursorColor: Colors.blue.shade200,
selectionColor: Colors.blue.shade900,
selectionHandleColor: Colors.blue.shade800,
),
inputDecorationTheme: InputDecorationTheme(
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.blue.shade500),
),
),
);
}
var _darkTheme = _DarkTheme();
var _dustyBlueTheme = _DustyBlueTheme();
final _themePackages = <_ThemePackage>[
_OriginTheme(),
_PinkTheme(),
_BlackTheme(),
_darkTheme,
_dustyBlueTheme,
];
// 主题更换事件
var themeEvent = Event();
const _themePropertyName = "theme";
const _defaultThemeCode = "dark";
String? _themeCode;
ThemeData? _themeData;
ThemeData? _currentDarkTheme;
bool _androidNightMode = false;
String currentThemeName() {
for (var package in _themePackages) {
if (_themeCode == package.code()) {
return package.name();
}
}
return "";
}
ThemeData? currentThemeData() {
return _themeData;
}
ThemeData? currentDarkTheme() {
return _currentDarkTheme;
}
// 根据Code选择主题, 并发送主题更换事件
void _changeThemeByCode(String? themeCode) {
_ThemePackage? _themePackage;
for (var package in _themePackages) {
if (themeCode == package.code()) {
_themeCode = themeCode;
_themePackage = package;
break;
}
}
if (_themePackage != null) {
_themeData = _themePackage.themeData(
_fontThemeData(
_themePackage == _darkTheme || _themePackage == _dustyBlueTheme),
);
}
_currentDarkTheme = _androidNightMode
? _darkTheme.themeData(_fontThemeData(true))
: _themeData;
themeEvent.broadcast();
}
// 为了匹配安卓夜间模式增加的配置文件
const _nightModePropertyName = "androidNightMode";
Future initTheme() async {
_androidNightMode =
await nHentai.loadProperty(_nightModePropertyName, "true") == "true";
_changeThemeByCode(
await nHentai.loadProperty(_themePropertyName, _defaultThemeCode),
);
}
// 选择主题的对话框
Future chooseTheme(BuildContext buildContext) async {
var androidVersion = 0; // todo
String? theme = await showDialog(
context: buildContext,
builder: (BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, StateSetter setState) {
var list = [];
if (androidVersion >= 29) {
Future onChange(bool? v) async {
if (v != null) {
await nHentai.saveProperty(
_nightModePropertyName, "$v");
_androidNightMode = v;
}
_changeThemeByCode(_themeCode);
}
list.add(
SimpleDialogOption(
child: GestureDetector(
onTap: () {
onChange(!_androidNightMode);
},
child: Container(
margin: const EdgeInsets.only(top: 3, bottom: 3),
decoration: BoxDecoration(
border: Border(
top: BorderSide(
color: Theme
.of(context)
.dividerColor,
width: 0.5,
),
bottom: BorderSide(
color: Theme
.of(context)
.dividerColor,
width: 0.5
),
),
),
child: Row(
children: [
Checkbox(
value: _androidNightMode,
onChanged: onChange,
),
Text(AppLocalizations.of(context)!.themeIntoDarkFlowSystem),
],
),
),
),
),
);
}
list.addAll(_themePackages
.map((e) =>
SimpleDialogOption(
child: Text(e.name()),
onPressed: () {
Navigator.of(context).pop(e.code());
},
)
));
return SimpleDialog(
title: Text(AppLocalizations.of(context)!.chooseTheme),
children: list,
);
});
},
);
if (theme != null) {
nHentai.saveProperty(_themePropertyName, theme);
_changeThemeByCode(theme);
}
}
Widget themeSetting(BuildContext context) {
return StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return
ListTile(
onTap: () async {
await chooseTheme(context);
setState(() {});
},
title: Text(AppLocalizations.of(context)!.theme),
subtitle: Text(currentThemeName()),
);
},);
}
================================================
FILE: lib/basic/configs/version.dart
================================================
import 'package:flutter/gestures.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'dart:async' show Future;
import 'dart:convert';
import 'package:event/event.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
import 'package:nhentai/basic/common/cross.dart';
import 'package:nhentai/screens/components/Badged.dart';
const _releasesUrl = "https://github.com/niuhuan/nhentai-cross/releases";
const _versionUrl =
"https://api.github.com/repos/niuhuan/nhentai-cross/releases/latest";
const _versionAssets = 'lib/assets/version.txt';
RegExp _versionExp = RegExp(r"^v\d+\.\d+.\d+$");
late String _version;
String? _latestVersion;
String? _latestVersionInfo;
const _propertyName = "checkVersionPeriod";
late int _period = -1;
Future initVersion() async {
// 当前版本
try {
_version = (await rootBundle.loadString(_versionAssets)).trim();
} catch (e) {
_version = "dirty";
}
// 检查周期
_period = int.parse(await nHentai.loadProperty(_propertyName, "0"));
if (_period > 0) {
if (DateTime.now().millisecondsSinceEpoch > _period) {
await nHentai.saveProperty(_propertyName, "0");
_period = 0;
}
}
}
var versionEvent = Event();
String currentVersion() {
return _version;
}
String? latestVersion() {
return _latestVersion;
}
String? latestVersionInfo() {
return _latestVersionInfo;
}
Future autoCheckNewVersion() {
if (_period != 0) {
// -1 不检查, >0 未到检查时间
return Future.value();
}
return _versionCheck();
}
Future manualCheckNewVersion(BuildContext context) async {
try {
defaultToast(context, AppLocalizations.of(context)!.checkingNewVersion);
await _versionCheck();
defaultToast(context, AppLocalizations.of(context)!.success);
} catch (e) {
defaultToast(context, AppLocalizations.of(context)!.failed + " : $e");
}
}
bool dirtyVersion() {
return !_versionExp.hasMatch(_version);
}
// maybe exception
Future _versionCheck() async {
if (_versionExp.hasMatch(_version)) {
var json = jsonDecode(await nHentai.httpGet(_versionUrl));
if (json["name"] != null) {
String latestVersion = (json["name"]);
if (latestVersion != _version) {
_latestVersion = latestVersion;
_latestVersionInfo = json["body"] ?? "";
}
}
} // else dirtyVersion
versionEvent.broadcast();
}
String _periodText(BuildContext context) {
if (_period < 0) {
return AppLocalizations.of(context)!.disabled;
}
if (_period == 0) {
return AppLocalizations.of(context)!.enabled;
}
return AppLocalizations.of(context)!.nextTime +
" : " +
formatDateTimeToDateTime(
DateTime.fromMillisecondsSinceEpoch(_period),
);
}
Future _choosePeriod(BuildContext context) async {
var result = await chooseMapDialog(
context,
{
AppLocalizations.of(context)!.enable: 0,
AppLocalizations.of(context)!.aWeek: 1,
AppLocalizations.of(context)!.aMonth: 2,
AppLocalizations.of(context)!.aYear: 3,
AppLocalizations.of(context)!.disable: 4,
},
AppLocalizations.of(context)!.autoCheckNewVersion,
// todo tips: "重启后红点会消失",
);
switch (result) {
case 0:
await nHentai.saveProperty(_propertyName, "0");
_period = 0;
break;
case 1:
var time = DateTime.now().millisecondsSinceEpoch + (1000 * 3600 * 24 * 7);
await nHentai.saveProperty(_propertyName, "$time");
_period = time;
break;
case 2:
var time =
DateTime.now().millisecondsSinceEpoch + (1000 * 3600 * 24 * 30);
await nHentai.saveProperty(_propertyName, "$time");
_period = time;
break;
case 3:
var time =
DateTime.now().millisecondsSinceEpoch + (1000 * 3600 * 24 * 365);
await nHentai.saveProperty(_propertyName, "$time");
_period = time;
break;
case 4:
await nHentai.saveProperty(_propertyName, "-1");
_period = -1;
break;
}
}
Widget autoUpdateCheckSetting() {
return StatefulBuilder(
builder: (BuildContext context, void Function(void Function()) setState) {
return ListTile(
title: Text(AppLocalizations.of(context)!.autoCheckNewVersion),
subtitle: Text(_periodText(context)),
onTap: () async {
await _choosePeriod(context);
setState(() {});
},
);
},
);
}
String formatDateTimeToDateTime(DateTime c) {
try {
return "${add0(c.year, 4)}-${add0(c.month, 2)}-${add0(c.day, 2)} ${add0(c.hour, 2)}:${add0(c.minute, 2)}";
} catch (e) {
return "-";
}
}
class VersionInfo extends StatefulWidget {
const VersionInfo({Key? key}) : super(key: key);
@override
State createState() => _VersionInfoState();
}
class _VersionInfoState extends State {
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.only(left: 20, right: 20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'软件版本 : $_version',
style: const TextStyle(
height: 1.3,
),
),
Row(
children: [
const Text(
"检查更新 : ",
style: TextStyle(
height: 1.3,
),
),
"dirty" == _version
? _buildDirty()
: _buildNewVersion(_latestVersion),
Expanded(child: Container()),
],
),
_buildNewVersionInfo(_latestVersionInfo),
],
),
);
}
Widget _buildNewVersion(String? latestVersion) {
if (latestVersion != null) {
return Text.rich(
TextSpan(
children: [
WidgetSpan(
child: Badged(
child: Container(
padding: const EdgeInsets.only(right: 12),
child: Text(
latestVersion,
style: const TextStyle(height: 1.3),
),
),
badge: "1",
),
),
const TextSpan(text: " "),
TextSpan(
text: "去下载",
style: TextStyle(
height: 1.3,
color: Theme.of(context).colorScheme.primary,
),
recognizer: TapGestureRecognizer()
..onTap = () => openUrl(_releasesUrl),
),
],
),
);
}
return Text.rich(
TextSpan(
children: [
const TextSpan(text: "未检测到新版本", style: TextStyle(height: 1.3)),
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Container(
padding: const EdgeInsets.all(4),
margin: const EdgeInsets.only(left: 3, right: 3),
decoration: const BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(20)),
),
),
),
TextSpan(
text: "检查更新",
style: TextStyle(
height: 1.3,
color: Theme.of(context).colorScheme.primary,
),
recognizer: TapGestureRecognizer()
..onTap = () => manualCheckNewVersion(context),
),
],
),
);
}
Widget _buildDirty() {
return Text.rich(
TextSpan(
text: "下载RELEASE版",
style: TextStyle(
height: 1.3,
color: Theme.of(context).colorScheme.primary,
),
recognizer: TapGestureRecognizer()..onTap = () => openUrl(_releasesUrl),
),
);
}
Widget _buildNewVersionInfo(String? latestVersionInfo) {
if (latestVersionInfo != null) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Divider(),
const Text("更新内容:"),
Container(
padding: EdgeInsets.all(15),
child: Text(
latestVersionInfo,
style: TextStyle(),
),
),
],
);
}
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Divider(),
Container(
padding: EdgeInsets.all(15),
child: Text.rich(
TextSpan(
text: "去RELEASE仓库",
style: TextStyle(
height: 1.3,
color: Theme.of(context).colorScheme.primary,
),
recognizer: TapGestureRecognizer()
..onTap = () => openUrl(_releasesUrl),
),
),
),
],
);
}
}
================================================
FILE: lib/basic/entities/entities.dart
================================================
import 'package:flutter/cupertino.dart';
class PageData {
late int pageCount;
PageData.fromJson(Map json) {
pageCount = json["page_count"] ?? 0;
}
PageData(this.pageCount);
}
class ComicPageData extends PageData {
late List records;
ComicPageData.fromJson(Map json) : super.fromJson(json) {
records = (json["records"] ?? [])
.map((e) => ComicSimple.fromJson(e))
.toList()
.cast();
}
ComicPageData(int pageCount, this.records) : super(pageCount);
}
class ComicSimple {
late int id;
late int mediaId;
late String title;
late List tagIds;
late String lang;
late String thumb;
late int thumbWidth;
late int thumbHeight;
ComicSimple.fromJson(Map json) {
id = json["id"] ?? 0;
title = json["title"] ?? "";
mediaId = json["media_id"] ?? 0;
tagIds = (json["records"] ?? []).cast();
lang = json["lang"] ?? "";
thumb = json["thumb"] ?? "";
thumbWidth = json["thumb_width"] ?? 1;
thumbHeight = json["thumb_height"] ?? 1;
}
}
class ComicInfo {
late int id;
late int mediaId;
late ComicInfoTitle title;
late ComicImages images;
late String scanlator;
late int uploadDate;
late List tags;
late int numPages;
late int numFavorites;
ComicInfo.formJson(Map json) {
id = json["id"] ?? 0;
mediaId = json["media_id"] ?? 0;
title = ComicInfoTitle.fromJson(json["title"]);
images = ComicImages.formJson(json["images"]);
scanlator = json["scanlator"] ?? "";
uploadDate = json["upload_date"] ?? 0;
tags = (json["tags"] ?? [])
.map((e) => ComicInfoTag.formJson(e))
.toList()
.cast();
numPages = json["num_pages"] ?? 0;
numFavorites = json["num_favorites"] ?? 0;
}
Map toJson() {
return {
"id": id,
"media_id": mediaId,
"title": title,
"images": images,
"scanlator": scanlator,
"upload_date": uploadDate,
"tags": tags,
"num_pages": numPages,
"num_favorites": numFavorites,
};
}
}
class ComicInfoTitle {
late String english;
late String japanese;
late String pretty;
ComicInfoTitle.fromJson(Map json) {
english = json["english"] ?? "";
japanese = json["japanese"] ?? "";
pretty = json["pretty"] ?? "";
}
Map toJson() {
return {
"english": english,
"japanese": japanese,
"pretty": pretty,
};
}
}
class ComicImages {
late List pages;
late ImageInfo cover;
late ImageInfo thumbnail;
ComicImages.formJson(Map json) {
pages = List.of(json["pages"])
.map((e) => ImageInfo.formJson(e))
.toList()
.cast();
cover = ImageInfo.formJson(json["cover"]);
thumbnail = ImageInfo.formJson(json["thumbnail"]);
}
Map toJson() {
return {
"pages": pages,
"cover": cover,
"thumbnail": thumbnail,
};
}
}
class ImageInfo {
late String t;
late int w;
late int h;
ImageInfo.formJson(Map json) {
t = json["t"];
w = json["w"];
h = json["h"];
}
Map toJson() {
return {
"t": t,
"w": w,
"h": h,
};
}
}
class ComicInfoTag {
late int id;
late String name;
late int count;
late String type;
late String url;
ComicInfoTag.formJson(Map json) {
id = json["id"];
name = json["name"];
count = json["count"];
type = json["type"];
url = json["url"];
}
Map toJson() {
return {
"id": id,
"name": name,
"count": count,
"type": type,
"url": url,
};
}
}
class DownloadComicInfo extends ComicInfo {
late int downloadStatus;
DownloadComicInfo.formJson(Map json) : super.formJson(json) {
downloadStatus = json["download_status"] ?? 0;
}
}
================================================
FILE: lib/l10n/app_en.arb
================================================
{
"initializing": "Initializing",
"settings": "Settings",
"none": "None",
"webAddress": "Web IP redirect",
"chooseWebAddress": "Choose web domain IP",
"imgAddress": "Image domain IP redirect",
"chooseImgAddress": "Choose Image domain IP",
"theme": "Theme",
"chooseTheme": "Choose theme",
"themeIntoDarkFlowSystem": "Flow system to dark mode",
"loading": "Loading",
"errorAndTapRetry": "Error, tap to retry",
"allComics": "All comics",
"search": "Search",
"searchContent": "Search content",
"yes": "Yes",
"no": "No",
"ok": "Ok",
"cancel": "Cancel",
"addFilter": "Add filter",
"exclusion": "Exclusion",
"type": "Type",
"content": "Content",
"tag": "Tag",
"chooseAction": "Choose action",
"saveImage": "Save image",
"previewImage": "Preview image",
"questionDownloadComic": "Download this comic?",
"download": "Download",
"checkingNewVersion": "Checking new version",
"success": "Success",
"failed": "Failed",
"autoCheckNewVersion": "Auto check new version",
"disabled": "Disabled",
"disable": "Disable",
"enabled": "Enabled",
"enable": "Enable",
"nextTime": "Next time",
"aWeek": "A week",
"aMonth": "A month",
"aYear": "A year",
"delete": "Delete",
"deleting": "Deleting",
"chooseReaderDirection": "Choose reader direction",
"topToBottom": "Top to bottom",
"leftToRight": "Left to right",
"rightToLeft": "Right to left",
"chooseReaderType": "Choose reader type",
"webtoon": "WebToon",
"gallery": "Gallery",
"proxy": "Proxy",
"inputProxyDesc": "socks5://host:port/"
}
================================================
FILE: lib/l10n/app_zh.arb
================================================
{
"initializing": "启动中",
"settings": "设置",
"none": "无",
"webAddress": "网站IP重定向",
"chooseWebAddress": "选择网站IP",
"imgAddress": "图片IP重定向",
"chooseImgAddress": "选择图片IP",
"theme": "主题",
"chooseTheme": "选择主题",
"themeIntoDarkFlowSystem": "随手机进入黑暗模式",
"loading": "加载中",
"errorAndTapRetry": "出错了, 点击重试",
"allComics": "所有漫画",
"search": "搜索",
"searchContent": "搜索内容",
"yes": "是",
"no": "否",
"ok": "确认",
"cancel": "取消",
"addFilter": "增加过滤条件",
"exclusion": "排除",
"type": "类型",
"content": "内容",
"tag": "标签",
"chooseAction": "请选择",
"saveImage": "保存图片",
"previewImage": "预览图片",
"questionDownloadComic": "下载这个漫画吗?",
"download": "下载",
"checkingNewVersion": "正在检查更新",
"success": "成功",
"failed": "失败",
"autoCheckNewVersion": "自动检查更新",
"disabled": "已禁用",
"disable": "禁用",
"enabled": "已开启",
"enable": "开启",
"nextTime": "下一次",
"aWeek": "一周后",
"aMonth": "一个月后",
"aYear": "一年后",
"delete": "删除",
"deleting": "删除中",
"chooseReaderDirection": "选贼阅读器方向",
"topToBottom": "从上到下",
"leftToRight": "从左到右",
"rightToLeft": "从右到左",
"chooseReaderType": "选择阅读器类型",
"webtoon": "WebToon",
"gallery": "相册",
"proxy": "代理",
"inputProxyDesc": "socks5://host:port/"
}
================================================
FILE: lib/main.dart
================================================
import 'dart:io';
import 'package:event/event.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:nhentai/screens/comic_info_screen.dart';
import 'package:nhentai/screens/components/mouse_and_touch_scroll_behavior.dart';
import 'package:nhentai/screens/init_screen.dart';
import 'basic/common/common.dart';
import 'basic/configs/themes.dart';
void main() async {
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
@override
State createState() => MyAppState();
}
class MyAppState extends State {
@override
void initState() {
themeEvent.subscribe(_onChangeTheme);
super.initState();
}
@override
void dispose() {
themeEvent.unsubscribe(_onChangeTheme);
super.dispose();
}
void _onChangeTheme(EventArgs? args) {
setState(() {});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
scrollBehavior: mouseAndTouchScrollBehavior,
debugShowCheckedModeBanner: false,
theme: currentThemeData(),
darkTheme: currentDarkTheme(),
home: const InitScreen(),
localizationsDelegates: const [
AppLocalizations.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: AppLocalizations.supportedLocales,
);
}
}
================================================
FILE: lib/main_desktop.dart
================================================
import 'main.dart' as original_main;
// This file is the default main entry-point for go-flutter application.
void main() {
original_main.main();
}
================================================
FILE: lib/screens/comic_downloads_screen.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
import 'package:nhentai/basic/entities/entities.dart';
import 'package:nhentai/screens/components/actions.dart';
import 'package:nhentai/screens/components/content_builder.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'comic_info_screen.dart';
import 'components/images.dart';
class ComicDownloadsScreen extends StatefulWidget {
const ComicDownloadsScreen({Key? key}) : super(key: key);
@override
State createState() => _ComicDownloadsScreenState();
}
class _ComicDownloadsScreenState extends State {
late Future> _future;
@override
void initState() {
_future = nHentai.listDownloadComicInfo();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.download),
actions: [
...alwaysInActions(),
],
),
body: ContentBuilder(
future: _future,
successBuilder: (BuildContext context,
AsyncSnapshot> snapshot) {
var crossCount = 2;
var _data = snapshot.requireData;
return WaterfallFlow.builder(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(top: 10, bottom: 10),
itemCount: _data.length,
gridDelegate: SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
crossAxisCount: crossCount,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemBuilder: (BuildContext context, int index) {
return _buildImageCard(_data[index]);
},
);
},
onRefresh: () async {},
),
);
}
Widget _buildImageCard(DownloadComicInfo item) {
return GestureDetector(
onTap: () {
if (item.downloadStatus == 4) return;
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return ComicInfoScreen(item.id, item.title.pretty);
},
));
},
onLongPress: () async {
if (item.downloadStatus == 4) return;
var action = await chooseMapDialog(
context,
{
AppLocalizations.of(context)!.delete: 1,
},
AppLocalizations.of(context)!.chooseAction,
);
if (action != null) {
switch (action) {
case 1:
setState(() {
item.downloadStatus = 3;
});
await nHentai.downloadSetDelete(item.id);
break;
}
}
},
child: Card(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
var width = constraints.maxWidth;
var height = constraints.maxWidth *
item.images.thumbnail.h /
item.images.thumbnail.w;
return SizedBox(
width: width,
height: height,
child: Stack(
children: [
NHentaiImage(
url:
"https://t2.nhentai.net/galleries/${item.mediaId}/thumb.jpg",
size: Size(width, height),
disablePreview: true,
),
_buildDownloadStatus(item.downloadStatus),
],
),
);
},
),
),
);
}
Widget _buildDownloadStatus(int downloadStatus) {
late IconData iconData;
late Color color;
switch (downloadStatus) {
case 1:
iconData = Icons.download_done_sharp;
color = Colors.green;
break;
case 2:
iconData = Icons.error_outline;
color = Colors.yellow;
break;
case 3:
iconData = Icons.auto_delete_outlined;
color = Colors.red;
break;
default:
iconData = Icons.query_builder;
color = Colors.grey;
break;
}
return Align(
alignment: Alignment.topRight,
child: Container(
margin: EdgeInsets.only(top: 3, right: 3),
padding: EdgeInsets.all(1),
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(3),
),
child: Icon(iconData, color: Colors.white, size: 14),
),
);
}
}
================================================
FILE: lib/screens/comic_info_screen.dart
================================================
import 'dart:io';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:date_format/date_format.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
import 'package:nhentai/basic/entities/entities.dart';
import 'package:nhentai/screens/comic_reader_screen.dart';
import 'package:nhentai/screens/comic_search_screen.dart';
import 'package:nhentai/screens/comics_screen.dart';
import 'package:nhentai/screens/components/actions.dart';
import 'package:nhentai/screens/components/content_builder.dart';
import 'package:nhentai/screens/components/images.dart';
import 'package:nhentai/screens/webview_screen.dart';
class ComicInfoScreen extends StatefulWidget {
final int comicId;
final String comicTitle;
const ComicInfoScreen(this.comicId, this.comicTitle, {Key? key})
: super(key: key);
@override
State createState() => _ComicInfoScreenState();
}
class _ComicInfoScreenState extends State {
late Future _future;
late Future _hasDownloadFuture;
Future _loadComic() async {
var info = await nHentai.comicInfo(widget.comicId);
var _ = nHentai.saveViewInfo(info); // 在后台线程保存浏览记录
return info;
}
@override
void initState() {
_future = _loadComic();
_hasDownloadFuture = nHentai.hasDownload(widget.comicId);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Text(snapshot.requireData.title.pretty);
}
return Text(widget.comicTitle);
},
),
actions: [
...(Platform.isAndroid || Platform.isIOS) && widget.comicTitle.isEmpty
? [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (BuildContext context) {
return const WebViewScreen();
}));
},
icon: const Icon(Icons.wb_auto)),
]
: [],
FutureBuilder(
future: _future,
builder:
(BuildContext context, AsyncSnapshot snapshot1) {
if (snapshot1.hasError ||
snapshot1.connectionState != ConnectionState.done) {
return Container();
}
return FutureBuilder(
future: _hasDownloadFuture,
builder: (BuildContext context, AsyncSnapshot snapshot2) {
if (snapshot2.hasError ||
snapshot2.connectionState != ConnectionState.done) {
return Container();
}
if (snapshot2.requireData) {
// todo downloading
return IconButton(
onPressed: () {},
icon: const Icon(Icons.download_done),
);
} else {
// todo reload
return IconButton(
onPressed: () async {
var confirm = await confirmDialog(
context,
AppLocalizations.of(context)!.questionDownloadComic,
);
if (confirm) {
await nHentai.downloadComic(snapshot1.requireData);
setState(() {
_hasDownloadFuture =
nHentai.hasDownload(widget.comicId);
});
}
},
icon: const Icon(Icons.download),
);
}
},
);
},
),
...alwaysInActions(),
],
),
floatingActionButton: FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done &&
!snapshot.hasError) {
return Padding(
padding: const EdgeInsets.only(right: 30, bottom: 30),
child: FloatingActionButton(
onPressed: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return ComicReaderScreen(snapshot.requireData);
}));
},
child: const Icon(Icons.menu_book),
),
);
}
return Container();
},
),
body: ContentBuilder(
future: _future,
onRefresh: () async {
setState(() {
_future = _loadComic();
});
},
successBuilder:
(BuildContext context, AsyncSnapshot snapshot) {
var item = snapshot.data!;
var mq = MediaQuery.of(context);
var imageWidth =
(mq.size.width < mq.size.height) ? mq.size.width : mq.size.height;
imageWidth = imageWidth / 2;
var subColor = Color.alphaBlend(
Colors.grey.shade500.withAlpha(80),
(Theme.of(context).textTheme.bodyText1?.color ?? Colors.black),
);
return ListView(
children: [
Container(height: 20),
Align(
alignment: Alignment.center,
child: SizedBox(
width: imageWidth,
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: HorizontalStretchNHentaiImage(
url: coverImageUrl(item.mediaId),
originSize: Size(
item.images.cover.w.toDouble(),
item.images.cover.h.toDouble(),
),
),
),
),
),
Container(height: 20),
Container(
margin: const EdgeInsets.only(left: 20, right: 20),
child: Text(
item.title.english,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
Container(height: 10),
Container(
margin: const EdgeInsets.only(left: 20, right: 20),
child: Text(
item.title.japanese,
textAlign: TextAlign.center,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
),
),
),
Container(height: 10),
Align(
alignment: Alignment.center,
child: Text.rich(TextSpan(
style: TextStyle(
fontSize: 12,
color: subColor,
),
children: [
WidgetSpan(
child: Icon(
Icons.calendar_today_outlined,
size: 12,
color: subColor,
),
),
const TextSpan(text: " "),
TextSpan(
text: formatDate(
DateTime.fromMillisecondsSinceEpoch(
item.uploadDate * 1000,
),
[yyyy, "-", mm, "-", dd, " ", HH, ":", nn, ":", ss],
),
),
const TextSpan(text: " "),
],
)),
),
Container(height: 10),
Align(
alignment: Alignment.center,
child: Text.rich(
TextSpan(
style: TextStyle(
fontSize: 15,
color: subColor,
),
children: [
TextSpan(
children: [
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Icon(
Icons.image,
size: 14,
color: subColor,
),
),
const TextSpan(text: " "),
TextSpan(text: "${item.images.pages.length}"),
],
),
const TextSpan(text: " "),
TextSpan(
children: [
WidgetSpan(
alignment: PlaceholderAlignment.middle,
child: Icon(
Icons.favorite_outline,
size: 15,
color: subColor,
),
),
const TextSpan(text: " "),
TextSpan(text: "${item.numFavorites}"),
],
),
],
),
),
),
Container(height: 10),
Container(
margin: const EdgeInsets.only(left: 20, right: 20),
child: Wrap(
children: (item.tags.map(_buildTag)).toList(),
),
),
],
);
},
),
);
}
Widget _buildTag(ComicInfoTag e) {
return GestureDetector(
onTap: () {
Navigator.of(context)
.push(MaterialPageRoute(builder: (BuildContext context) {
return ComicsScreen(
searchStruct: ComicSearchStruct(
searchContext: "",
conditions: [
ComicSearchCondition('tag', e.name, false),
],
),
);
}));
},
child: Card(
child: Text.rich(TextSpan(
style: const TextStyle(fontSize: 10),
children: [
WidgetSpan(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: Container(
color: Colors.grey.withAlpha(20),
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(e.name),
),
),
),
WidgetSpan(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: Container(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text("${e.count}"),
),
),
),
],
)),
),
);
}
}
================================================
FILE: lib/screens/comic_reader_screen.dart
================================================
import 'dart:async';
import 'dart:io';
import 'package:another_xlider/another_xlider.dart';
import 'package:event/event.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:modal_bottom_sheet/modal_bottom_sheet.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/configs/proxy.dart';
import 'package:nhentai/basic/configs/reader_direction.dart';
import 'package:nhentai/basic/configs/reader_type.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:nhentai/basic/entities/entities.dart';
import 'package:nhentai/screens/components/images.dart';
import 'package:photo_view/photo_view_gallery.dart';
class ComicReaderScreen extends StatefulWidget {
final ComicInfo comicInfo;
const ComicReaderScreen(this.comicInfo, {Key? key}) : super(key: key);
@override
State createState() => _ComicReaderScreenState();
}
class _ComicReaderScreenState extends State {
late ReaderType _readerType;
late ReaderDirection _readerDirection;
late int _startIndex;
late Future _future;
Future _init() async {
var last = await nHentai.loadLastViewIndexByComicId(widget.comicInfo.id);
_readerType = currentReaderType();
_readerDirection = currentReaderDirection();
_startIndex = last;
}
@override
void initState() {
_future = _init();
super.initState();
}
Future _reload() async {
// Navigator.of(context)
// .pushReplacement(MaterialPageRoute(builder: (BuildContext context) {
// return ComicReaderScreen(widget.comicInfo);
// }));
setState(() {
_future = _init();
});
}
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(),
);
}
final screen = Scaffold(
backgroundColor: Colors.black,
body: _ComicReader(
widget.comicInfo,
readerType: _readerType,
readerDirection: _readerDirection,
reload: _reload,
startIndex: _startIndex,
),
);
return readerKeyboardHolder(screen);
},
);
}
}
class _ComicReader extends StatefulWidget {
final ComicInfo comicInfo;
final ReaderType readerType;
final ReaderDirection readerDirection;
final FutureOr Function() reload;
final int startIndex;
const _ComicReader(
this.comicInfo, {
required this.readerType,
required this.readerDirection,
required this.reload,
required this.startIndex,
Key? key,
}) : super(key: key);
@override
// ignore: no_logic_in_create_state
State createState() {
switch (readerType) {
case ReaderType.webtoon:
return _ComicReaderWebToonState();
case ReaderType.gallery:
return _ComicReaderGalleryState();
}
}
}
abstract class _ComicReaderState extends State<_ComicReader> {
late final ReaderDirection _direction = currentReaderDirection();
Widget _buildViewer();
_needJumpTo(int pageIndex, bool animation);
late bool _fullScreen;
late int _current;
late int _slider;
Future _onFullScreenChange(bool fullScreen) async {
setState(() {
SystemChrome.setEnabledSystemUIOverlays(
fullScreen ? [] : SystemUiOverlay.values);
_fullScreen = fullScreen;
});
}
void _onCurrentChange(int index) {
if (index != _current) {
setState(() {
_current = index;
_slider = index;
var _ = nHentai.saveViewIndex(widget.comicInfo, index); // 在后台线程入库
});
}
}
@override
void initState() {
_fullScreen = false;
_current = widget.startIndex;
_slider = widget.startIndex;
_readerControllerEvent.subscribe(_onPageControl);
super.initState();
}
@override
void dispose() {
_readerControllerEvent.unsubscribe(_onPageControl);
if (Platform.isAndroid || Platform.isIOS) {
SystemChrome.setEnabledSystemUIOverlays(SystemUiOverlay.values);
}
super.dispose();
}
void _onPageControl(_ReaderControllerEventArgs? args) {
if (args != null) {
var event = args.key;
switch (event) {
case "UP":
if (_current > 0) {
_needJumpTo(_current - 1, true);
}
break;
case "DOWN":
if (_current < widget.comicInfo.images.pages.length - 1) {
_needJumpTo(_current + 1, true);
}
break;
}
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
_buildViewer(),
_buildFrame(),
],
);
}
Widget _buildFrame() {
return Column(
children: [
_fullScreen ? Container() : _buildAppBar(),
Expanded(
child: GestureDetector(
behavior: HitTestBehavior.translucent,
onTap: () {
_onFullScreenChange(!_fullScreen);
},
child: Container(),
),
),
_fullScreen ? Container() : _buildBottomBar(),
_fullScreen ? Container() : _buildEdgePadding(),
],
);
}
Widget _buildAppBar() {
return AppBar(
title: Text(widget.comicInfo.title.pretty),
actions: [
IconButton(
onPressed: _onMoreSetting,
icon: const Icon(Icons.more_horiz),
),
],
);
}
Widget _buildBottomBar() {
return Container(
height: 45,
color: const Color(0x88000000),
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: _buildSlider()),
],
),
);
}
Widget _buildEdgePadding() {
return Container(
color: const Color(0x88000000),
child: SafeArea(
top: false,
child: Container(),
),
);
}
Widget _buildSlider() {
return Column(
children: [
Expanded(child: Container()),
SizedBox(
height: 25,
child: FlutterSlider(
axis: Axis.horizontal,
values: [_slider.toDouble()],
min: 0,
max: (widget.comicInfo.images.pages.length - 1).toDouble(),
onDragging: (handlerIndex, lowerValue, upperValue) {
_slider = (lowerValue.toInt());
},
onDragCompleted: (handlerIndex, lowerValue, upperValue) {
_slider = (lowerValue.toInt());
if (_slider != _current) {
_needJumpTo(_slider, false);
}
},
trackBar: FlutterSliderTrackBar(
inactiveTrackBar: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.grey.shade300,
),
activeTrackBar: BoxDecoration(
borderRadius: BorderRadius.circular(4),
color: Theme.of(context).colorScheme.secondary,
),
),
step: const FlutterSliderStep(
step: 1,
isPercentRange: false,
),
tooltip: FlutterSliderTooltip(custom: (value) {
double a = value + 1;
return Container(
padding: const EdgeInsets.all(8),
decoration: ShapeDecoration(
color: Colors.black.withAlpha(0xCC),
shape: RoundedRectangleBorder(
borderRadius: BorderRadiusDirectional.circular(3)),
),
child: Text(
'${a.toInt()}',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
),
),
);
}),
),
),
Expanded(child: Container()),
],
);
}
//
_onMoreSetting() async {
await showMaterialModalBottomSheet(
context: context,
backgroundColor: const Color(0xAA000000),
builder: (context) {
return SizedBox(
height: MediaQuery.of(context).size.height / 2,
child: _SettingPanel(),
);
},
);
if (_direction != currentReaderDirection() ||
widget.readerType != currentReaderType()) {
widget.reload();
}
}
//
double _appBarHeight() {
return Scaffold.of(context).appBarMaxHeight ?? 0;
}
double _bottomBarHeight() {
return 45;
}
}
class _SettingPanel extends StatefulWidget {
@override
State createState() => _SettingPanelState();
}
class _SettingPanelState extends State<_SettingPanel> {
@override
Widget build(BuildContext context) {
return ListView(
children: [
Row(
children: [
_bottomIcon(
icon: Icons.crop_sharp,
title: readerDirectionName(currentReaderDirection(), context),
onPressed: () async {
await chooseReaderDirection(context);
setState(() {});
},
),
_bottomIcon(
icon: Icons.view_day_outlined,
title: readerTypeName(currentReaderType(), context),
onPressed: () async {
await chooseReaderType(context);
setState(() {});
},
),
_bottomIcon(
icon: Icons.shuffle,
title: AppLocalizations.of(context)!.proxy,
onPressed: () async {
await chooseProxy(context);
setState(() {});
},
),
],
),
],
);
}
Widget _bottomIcon({
required IconData icon,
required String title,
required void Function() onPressed,
}) {
return Expanded(
child: Center(
child: Column(
children: [
IconButton(
iconSize: 55,
icon: Column(
children: [
Container(height: 3),
Icon(
icon,
size: 25,
color: Colors.white,
),
Container(height: 3),
Text(
title,
style: const TextStyle(color: Colors.white, fontSize: 10),
maxLines: 1,
textAlign: TextAlign.center,
),
Container(height: 3),
],
),
onPressed: onPressed,
)
],
),
),
);
}
}
class _ComicReaderWebToonState extends _ComicReaderState {
ScrollController? _controller;
List _offsets = [];
List _sizes = [];
@override
void dispose() {
_controller?.dispose();
super.dispose();
}
@override
Widget _buildViewer() {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
if (_direction == ReaderDirection.topToBottom) {
_offsets = widget.comicInfo.images.pages
.map((e) => constraints.maxWidth * e.h / e.w)
.toList()
.cast();
} else {
var height = constraints.maxHeight -
super._appBarHeight() -
super._bottomBarHeight() -
MediaQuery.of(context).padding.bottom;
_offsets = widget.comicInfo.images.pages
.map((e) => height * e.w / e.h)
.toList()
.cast();
}
if (_direction == ReaderDirection.topToBottom) {
_sizes = widget.comicInfo.images.pages
.map((e) =>
Size(constraints.maxWidth, constraints.maxWidth * e.h / e.w))
.toList()
.cast();
} else {
var height = constraints.maxHeight -
super._appBarHeight() -
super._bottomBarHeight() -
MediaQuery.of(context).padding.bottom;
_sizes = widget.comicInfo.images.pages
.map((e) => Size(height * e.w / e.h, height))
.toList()
.cast();
}
if (_controller == null) {
_controller = ScrollController(initialScrollOffset: _initOffset());
_controller!.addListener(_onScroll);
}
return ListView.builder(
scrollDirection: _direction == ReaderDirection.topToBottom
? Axis.vertical
: Axis.horizontal,
reverse: _direction == ReaderDirection.rightToLeft,
controller: _controller,
padding: EdgeInsets.only(
top: super._appBarHeight(),
bottom: _direction == ReaderDirection.topToBottom
? 130
: (super._bottomBarHeight() +
MediaQuery.of(context).padding.bottom)
),
itemCount: widget.comicInfo.images.pages.length,
itemBuilder: (BuildContext context, int index) {
return NHentaiImage(
url: pageImageUrl(widget.comicInfo.mediaId, index + 1),
size: _sizes[index],
fit: BoxFit.contain,
);
},
);
},
);
}
_onScroll() {
double cOff = _controller!.offset;
double off = 0;
int i = 0;
for (; i < _offsets.length; i++) {
if (cOff == off) {
// 最顶端, 以及每个图片的开始
// 0 == 0
super._onCurrentChange(i);
return;
}
// 第二轮, 假设第一张的300px, 现在是299px
if (cOff < off) {
super._onCurrentChange(i - 1);
return;
}
off += _offsets[i];
}
// 特殊情况1: i = 0, 如果没图片, i = 0
// 特殊情况2: i = _offset.length 如果下方padding超过一屏 i 最后还++, 但是已经达到了length, 这个index是不存在的
if (i == 0) {
return;
}
super._onCurrentChange(i - 1);
}
double _initOffset() {
double off = 0;
for (var i = 1; i <= widget.startIndex && i < _offsets.length; i++) {
off += _offsets[i - 1];
}
return off;
}
@override
_needJumpTo(int pageIndex, bool animation) {
if (_offsets.length > pageIndex) {
double off = 0;
for (int i = 0; i < pageIndex; i++) {
off += _offsets[i];
}
if (animation) {
_controller?.animateTo(
off,
duration: const Duration(milliseconds: 250),
curve: Curves.ease,
);
} else {
_controller?.jumpTo(off);
}
}
}
}
class _ComicReaderGalleryState extends _ComicReaderState {
late PageController _pageController;
late PhotoViewGallery _gallery;
@override
void initState() {
_pageController = PageController(initialPage: widget.startIndex);
_gallery = PhotoViewGallery.builder(
scrollDirection: _direction == ReaderDirection.topToBottom
? Axis.vertical
: Axis.horizontal,
reverse: _direction == ReaderDirection.rightToLeft,
backgroundDecoration: const BoxDecoration(color: Colors.black),
loadingBuilder: (context, event) => LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return buildLoading(constraints.maxWidth, constraints.maxHeight);
},
),
pageController: _pageController,
onPageChanged: _onGalleryPageChange,
itemCount: widget.comicInfo.images.pages.length,
allowImplicitScrolling: true,
builder: (BuildContext context, int index) {
return PhotoViewGalleryPageOptions(
filterQuality: FilterQuality.high,
imageProvider: NHentaiImageProvider(
pageImageUrl(widget.comicInfo.mediaId, index + 1)),
errorBuilder: (b, e, s) {
print("$e,$s");
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return buildError(constraints.maxWidth, constraints.maxHeight);
},
);
},
);
},
);
super.initState();
}
@override
void dispose() {
_pageController.dispose();
super.dispose();
}
@override
Widget _buildViewer() {
return Column(
children: [
Container(height: _fullScreen ? 0 : super._appBarHeight()),
Expanded(
child: Stack(
children: [
_gallery,
],
),
),
Container(height: _fullScreen ? 0 : super._bottomBarHeight()),
],
);
}
@override
_needJumpTo(int pageIndex, bool animation) {
if (animation) {
_pageController.animateToPage(
pageIndex,
duration: const Duration(milliseconds: 400),
curve: Curves.ease,
);
} else {
_pageController.jumpToPage(pageIndex);
}
}
void _onGalleryPageChange(int to) {
super._onCurrentChange(to);
}
}
////////////////////////////////
// 仅支持安卓
// 监听后会拦截安卓手机音量键
// 仅最后一次监听生效
// event可能为DOWN/UP
Event<_ReaderControllerEventArgs> _readerControllerEvent =
Event<_ReaderControllerEventArgs>();
class _ReaderControllerEventArgs extends EventArgs {
final String key;
_ReaderControllerEventArgs(this.key);
}
const _listVolume = false;
var _volumeListenCount = 0;
void _onVolumeEvent(dynamic args) {
_readerControllerEvent.broadcast(_ReaderControllerEventArgs("$args"));
}
EventChannel volumeButtonChannel = const EventChannel("volume_button");
StreamSubscription? volumeS;
void addVolumeListen() {
_volumeListenCount++;
if (_volumeListenCount == 1) {
volumeS =
volumeButtonChannel.receiveBroadcastStream().listen(_onVolumeEvent);
}
}
void delVolumeListen() {
_volumeListenCount--;
if (_volumeListenCount == 0) {
volumeS?.cancel();
}
}
Widget readerKeyboardHolder(Widget widget) {
if (Platform.isWindows || Platform.isMacOS || Platform.isLinux) {
widget = RawKeyboardListener(
focusNode: FocusNode(),
child: widget,
autofocus: true,
onKey: (event) {
if (event is RawKeyDownEvent) {
if (event.isKeyPressed(LogicalKeyboardKey.arrowUp)) {
_readerControllerEvent.broadcast(_ReaderControllerEventArgs("UP"));
}
if (event.isKeyPressed(LogicalKeyboardKey.arrowDown)) {
_readerControllerEvent
.broadcast(_ReaderControllerEventArgs("DOWN"));
}
}
},
);
}
return widget;
}
////////////////////////////////
================================================
FILE: lib/screens/comic_search_screen.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/common/common.dart';
class ComicSearchStruct {
String searchContext;
late List conditions;
ComicSearchStruct({
this.searchContext = "",
List? conditions,
}) {
if (conditions != null) {
this.conditions = conditions;
} else {
this.conditions = [];
}
}
String dumpSearchString() {
var ss = searchContext.replaceAll("\"", " ").trim();
var content =
ss == "" ? "" : ss.split("\\s+").map((e) => "\"$e\"").join(" ");
for (var element in conditions) {
if (content != "") {
content += " ";
}
content += element.exclude ? "-" : "";
content += element.type;
content += ":";
content += "\"${element.content.replaceAll("\"", " ")}\"";
}
return content;
}
}
class ComicSearchCondition {
String type;
String content;
bool exclude;
ComicSearchCondition(this.type, this.content, this.exclude);
}
class ComicSearchScreen extends StatefulWidget {
late final ComicSearchStruct defaultSearchStruct;
ComicSearchScreen(ComicSearchStruct? defaultSearchStruct, {Key? key})
: super(key: key) {
if (defaultSearchStruct != null) {
this.defaultSearchStruct = defaultSearchStruct;
} else {
this.defaultSearchStruct = ComicSearchStruct();
}
}
@override
State createState() => _ComicSearchScreenState();
}
class _ComicSearchScreenState extends State {
late ComicSearchStruct _searchStruct = widget.defaultSearchStruct;
late final _searchContentFocusNode = FocusNode();
late final _textEditingController = TextEditingController();
@override
void initState() {
_textEditingController.text = _searchStruct.searchContext;
super.initState();
}
@override
void dispose() {
_searchContentFocusNode.dispose();
_textEditingController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.search),
actions: [
IconButton(
onPressed: () {
setState(() {
_searchStruct = ComicSearchStruct();
_textEditingController.text = _searchStruct.searchContext;
});
},
icon: const Icon(Icons.search_off)),
IconButton(
onPressed: () {
Navigator.of(context).pop(_searchStruct);
},
icon: const Icon(Icons.done),
),
],
),
body: ListView(
children: [
Container(height: 15),
Container(
padding: const EdgeInsets.all(15),
child: TextField(
controller: _textEditingController,
onChanged: (value) => _searchStruct.searchContext = value,
focusNode: _searchContentFocusNode,
cursorColor: Colors.red,
decoration: InputDecoration(
labelText: AppLocalizations.of(context)!.searchContent,
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15.0),
),
),
style: const TextStyle(),
),
),
Container(
margin: const EdgeInsets.all(15),
child: Wrap(
children: _searchStruct.conditions
.map(_buildCondition)
.toList()
.cast(),
),
),
Container(
margin: const EdgeInsets.all(15),
color: Colors.grey.shade500.withAlpha(50),
child: MaterialButton(
onPressed: () async {
var dia = _AddTagConditionDialog();
ComicSearchCondition? con = await showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text(AppLocalizations.of(context)!.addFilter),
content: SizedBox(
width: double.minPositive,
height: MediaQuery.of(context).size.height / 2,
child: dia,
),
actions: [
MaterialButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text(AppLocalizations.of(context)!.cancel),
),
MaterialButton(
onPressed: () {
var con = dia.condition;
con.content = con.content.trim();
if (con.content == "") {
defaultToast(context, "内容不能为空");
} else {
Navigator.of(context).pop(con);
}
},
child: Text(AppLocalizations.of(context)!.ok),
),
],
);
});
if (con != null) {
setState(() {
_searchStruct.conditions.add(con);
});
}
},
child: Text(AppLocalizations.of(context)!.addFilter),
),
),
],
),
);
}
Widget _buildCondition(ComicSearchCondition condition) {
return GestureDetector(
onTap: () {
setState(() {
_searchStruct.conditions.remove(condition);
});
},
child: Card(
child: Text.rich(TextSpan(
style: const TextStyle(fontSize: 10),
children: [
WidgetSpan(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: Container(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(condition.exclude ? "-" : "+"),
),
),
),
WidgetSpan(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: Container(
color: Colors.grey.withAlpha(20),
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(condition.type),
),
),
),
WidgetSpan(
child: ClipRRect(
borderRadius: const BorderRadius.all(Radius.circular(4.0)),
child: Container(
padding: const EdgeInsets.only(
top: 2, bottom: 2, left: 4, right: 4),
child: Text(condition.content),
),
),
),
],
)),
),
);
}
}
class _AddTagConditionDialog extends StatefulWidget {
late final ComicSearchCondition condition;
_AddTagConditionDialog({Key? key}) : super(key: key) {
condition = ComicSearchCondition("tag", "", false);
}
@override
State createState() => _AddTagConditionDialogState();
}
class _AddTagConditionDialogState extends State<_AddTagConditionDialog> {
@override
Widget build(BuildContext context) {
return ListView(
children: [
const Divider(),
SwitchListTile(
title: Text(AppLocalizations.of(context)!.exclusion),
value: widget.condition.exclude,
onChanged: (value) => setState(() {
widget.condition.exclude = value;
}),
),
const Divider(),
Text(AppLocalizations.of(context)!.type),
DropdownButton(
value: widget.condition.type,
items: [
DropdownMenuItem(
value: 'tag',
child: Text(AppLocalizations.of(context)!.tag),
),
],
onChanged: (value) => setState(() {
widget.condition.type = value ?? "";
}),
),
const Divider(),
Text(AppLocalizations.of(context)!.content),
TextFormField(
initialValue: widget.condition.content,
onChanged: (value) => widget.condition.content = value,
),
const Divider(),
],
);
}
}
================================================
FILE: lib/screens/comics_screen.dart
================================================
import 'dart:io';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/screens/comic_search_screen.dart';
import 'package:nhentai/screens/components/pager.dart';
import 'package:nhentai/screens/webview_screen.dart';
import 'comic_downloads_screen.dart';
import 'components/actions.dart';
class ComicsScreen extends StatefulWidget {
late final ComicSearchStruct searchStruct;
ComicsScreen({ComicSearchStruct? searchStruct, Key? key}) : super(key: key) {
if (searchStruct != null) {
this.searchStruct = searchStruct;
} else {
this.searchStruct = ComicSearchStruct();
}
}
@override
State createState() => _ComicsScreenState();
}
class _ComicsScreenState extends State {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
widget.searchStruct.dumpSearchString() == ""
? AppLocalizations.of(context)!.allComics
: widget.searchStruct.dumpSearchString(),
),
actions: [
...Platform.isAndroid || Platform.isIOS
? [
IconButton(
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (BuildContext context) {
return const WebViewScreen();
}));
},
icon: const Icon(Icons.wb_auto)),
]
: [],
IconButton(
onPressed: () async {
ComicSearchStruct? struct = await Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) =>
ComicSearchScreen(widget.searchStruct),
),
);
if (struct != null) {
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) =>
ComicsScreen(searchStruct: struct),
));
}
},
icon: const Icon(Icons.search),
),
IconButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) {
return const ComicDownloadsScreen();
},
));
},
icon: const Icon(Icons.archive),
),
...alwaysInActions(),
],
),
body: Pager(
onPage: (int page) {
return nHentai.comicsBySearchRaw(
widget.searchStruct.dumpSearchString(),
page,
);
},
),
);
}
}
================================================
FILE: lib/screens/components/Badged.dart
================================================
import 'package:flutter/material.dart';
class Badged extends StatelessWidget {
final String? badge;
final Widget child;
const Badged({Key? key, required this.child, this.badge}) : super(key: key);
@override
Widget build(BuildContext context) {
if (badge == null) {
return child;
}
return Stack(
children: [
child,
Positioned(
right: 0,
child: Container(
padding: const EdgeInsets.all(1),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(6),
),
constraints: const BoxConstraints(
minWidth: 12,
minHeight: 12,
),
child: Text(
badge!,
style: const TextStyle(
color: Colors.white,
fontSize: 8,
),
textAlign: TextAlign.center,
),
),
),
],
);
}
}
================================================
FILE: lib/screens/components/actions.dart
================================================
import 'package:flutter/material.dart';
import 'package:nhentai/basic/configs/version.dart';
import '../settings_screen.dart';
import 'Badged.dart';
List alwaysInActions() {
return [
_SettingsAction(),
];
}
class _SettingsAction extends StatefulWidget {
@override
State createState() => _SettingsActionState();
}
class _SettingsActionState extends State<_SettingsAction> {
@override
void initState() {
versionEvent.subscribe(_setState);
super.initState();
}
@override
void dispose() {
versionEvent.unsubscribe(_setState);
super.dispose();
}
void _setState(_) {
setState(() {});
}
@override
Widget build(BuildContext context) {
return IconButton(
onPressed: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (BuildContext context) => const SettingsScreen(),
));
},
icon: Badged(
child: const Icon(Icons.settings),
badge: latestVersion() == null ? null : "1",
),
);
}
}
================================================
FILE: lib/screens/components/content_builder.dart
================================================
import 'package:flutter/material.dart';
import 'content_error.dart';
import 'content_loading.dart';
class ContentBuilder extends StatelessWidget {
final Future future;
final Future Function() onRefresh;
final AsyncWidgetBuilder successBuilder;
final String? loadingLabel;
const ContentBuilder({
Key? key,
required this.future,
required this.onRefresh,
required this.successBuilder,
this.loadingLabel,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
return ContentError(
error: snapshot.error,
stackTrace: snapshot.stackTrace,
onRefresh: onRefresh,
);
}
if (snapshot.connectionState != ConnectionState.done) {
return ContentLoading(label: loadingLabel);
}
return successBuilder(context, snapshot);
},
);
}
}
================================================
FILE: lib/screens/components/content_error.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'dart:ui';
import 'package:nhentai/basic/common/error_types.dart';
class ContentError extends StatelessWidget {
final Object? error;
final StackTrace? stackTrace;
final Future Function() onRefresh;
const ContentError({
Key? key,
required this.error,
required this.stackTrace,
required this.onRefresh,
}) : super(key: key);
@override
Widget build(BuildContext context) {
var type = errorType("$error");
late String message;
late IconData iconData;
switch (type) {
case ERROR_TYPE_NETWORK:
iconData = Icons.wifi_off_rounded;
message = "连接不上啦, 请检查网络";
break;
case ERROR_TYPE_PERMISSION:
iconData = Icons.highlight_off;
message = "没有权限或路径不可用";
break;
case ERROR_TYPE_TIME:
iconData = Icons.timer_off;
message = "请检查设备时间";
break;
case ERROR_TYPE_UNDER_REVIEW:
iconData = Icons.highlight_off;
message = "资源未审核或不可用";
break;
default:
iconData = Icons.highlight_off;
message = "啊哦, 被玩坏了";
break;
}
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
print("$error");
print("$stackTrace");
var width = constraints.maxWidth;
var height = constraints.maxHeight;
var min = width < height ? width : height;
var iconSize = min / 2.3;
var textSize = min / 16;
var tipSize = min / 20;
var infoSize = min / 30;
return GestureDetector(
onTap: onRefresh,
child: ListView(
children: [
SizedBox(
height: height,
child: Column(
children: [
Expanded(child: Container()),
Icon(
iconData,
size: iconSize,
color: Colors.grey.shade600,
),
Container(height: min / 10),
Container(
padding: const EdgeInsets.only(
left: 30,
right: 30,
),
child: Text(
message,
style: TextStyle(fontSize: textSize),
textAlign: TextAlign.center,
),
),
Text(
AppLocalizations.of(context)!.errorAndTapRetry,
style: TextStyle(fontSize: tipSize),
),
Container(height: min / 15),
Text('$error', style: TextStyle(fontSize: infoSize)),
Expanded(child: Container()),
],
),
),
],
),
);
},
);
}
}
================================================
FILE: lib/screens/components/content_loading.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
class ContentLoading extends StatelessWidget {
final String? label;
const ContentLoading({Key? key, this.label}) : super(key: key);
@override
Widget build(BuildContext context) {
String label = this.label ?? AppLocalizations.of(context)!.loading;
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
var width = constraints.maxWidth;
var height = constraints.maxHeight;
var min = width < height ? width : height;
var theme = Theme.of(context);
return Center(
child: Column(
children: [
Expanded(child: Container()),
SizedBox(
width: min / 2,
height: min / 2,
child: CircularProgressIndicator(
color: theme.colorScheme.secondary,
backgroundColor: Colors.grey[100],
),
),
Container(height: min / 10),
Text(label, style: TextStyle(fontSize: min / 15)),
Expanded(child: Container()),
],
),
);
},
);
}
}
================================================
FILE: lib/screens/components/images.dart
================================================
import 'package:flutter/foundation.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
import 'package:nhentai/basic/common/cross.dart';
import '../file_photo_view_screen.dart';
import 'dart:ui' as ui show Codec;
String coverImageUrl(int mediaId) {
return "https://t.nhentai.net/galleries/$mediaId/cover.${"jpg"}";
}
String pageImageUrl(int mediaId, int num) {
return "https://i.nhentai.net/galleries/$mediaId/$num.${"jpg"}";
}
class NHentaiImageProvider extends ImageProvider {
final String url;
final double scale;
NHentaiImageProvider(this.url, {this.scale = 1.0});
@override
ImageStreamCompleter load(key, DecoderCallback decode) {
return MultiFrameImageStreamCompleter(
codec: _loadAsync(key),
scale: key.scale,
);
}
@override
Future obtainKey(ImageConfiguration configuration) {
return SynchronousFuture(this);
}
Future _loadAsync(NHentaiImageProvider key) async {
assert(key == this);
var path = await nHentai.cacheImageByUrlPath(url);
var data = await File(path).readAsBytes();
return PaintingBinding.instance!.instantiateImageCodec(data);
}
}
class NHentaiImage extends StatefulWidget {
final String url;
final Size size;
final BoxFit fit;
final bool disablePreview;
const NHentaiImage({
Key? key,
required this.url,
required this.size,
this.fit = BoxFit.cover,
this.disablePreview = false,
}) : super(key: key);
@override
State createState() => _NHentaiImageState();
}
class _NHentaiImageState extends State {
late final Future _future = nHentai.cacheImageByUrlPath(widget.url);
@override
Widget build(BuildContext context) {
return pathFutureImage(
_future,
widget.size.width,
widget.size.height,
fit: widget.fit,
context: context,
disablePreview: widget.disablePreview,
);
}
}
Widget pathFutureImage(Future future, double? width, double? height,
{required BuildContext context,
BoxFit fit = BoxFit.cover,
bool disablePreview = false}) {
return FutureBuilder(
future: future,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasError) {
print("${snapshot.error}");
print("${snapshot.stackTrace}");
return buildError(width, height);
}
if (snapshot.connectionState != ConnectionState.done) {
return buildLoading(width, height);
}
return buildFile(
snapshot.data!,
width,
height,
fit: fit,
context: context,
disablePreview: disablePreview,
);
});
}
Widget buildError(double? width, double? height) {
return Image(
image: const AssetImage('lib/assets/error.png'),
width: width,
height: height,
);
}
Widget buildLoading(double? width, double? height) {
double? size;
if (width != null && height != null) {
size = width < height ? width : height;
}
return SizedBox(
width: width,
height: height,
child: Center(
child: Icon(
Icons.downloading,
size: size,
color: Colors.grey.shade500.withAlpha(80),
),
),
);
}
Widget buildFile(String file, double? width, double? height,
{required BuildContext context,
BoxFit fit = BoxFit.cover,
bool disablePreview = false}) {
var image = Image(
image: FileImage(File(file)),
width: width,
height: height,
errorBuilder: (context, obj, stackTrace) {
print("$obj");
print("$stackTrace");
return buildError(width, height);
},
fit: fit,
);
if (disablePreview) return image;
return GestureDetector(
onLongPress: () async {
final previewImageText = AppLocalizations.of(context)!.previewImage;
final saveImageText = AppLocalizations.of(context)!.saveImage;
final chooseActionText = AppLocalizations.of(context)!.chooseAction;
int? choose = await chooseMapDialog(
context,
{
previewImageText: 1,
saveImageText: 2,
},
chooseActionText,
);
switch (choose) {
case 1:
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => FilePhotoViewScreen(file),
));
break;
case 2:
saveImage(file, context);
break;
}
},
child: image,
);
}
class HorizontalStretchNHentaiImage extends StatelessWidget {
final String url;
final Size originSize;
const HorizontalStretchNHentaiImage(
{required this.url, required this.originSize, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
var width = constraints.maxWidth;
var height =
constraints.maxWidth * originSize.height / originSize.width;
return NHentaiImage(url: url, size: Size(width, height));
},
);
}
}
class ScaleImageTitle extends StatelessWidget {
final String title;
final Size originSize;
const ScaleImageTitle(
{required this.title, required this.originSize, Key? key})
: super(key: key);
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
var width = constraints.maxWidth;
var height =
constraints.maxWidth * originSize.height / originSize.width;
return SizedBox(
width: width,
height: height,
child: Column(
children: [
Expanded(child: Container()),
Row(
children: [
Expanded(
child: Material(
color: const Color(0xAA000000),
child: Text(
"$title\n",
maxLines: 2,
textAlign: TextAlign.center,
style: const TextStyle(
color: Colors.white,
),
),
),
),
],
),
],
),
);
},
);
}
}
================================================
FILE: lib/screens/components/mouse_and_touch_scroll_behavior.dart
================================================
import 'dart:ui';
import 'package:flutter/material.dart';
final mouseAndTouchScrollBehavior = MouseAndTouchScrollBehavior();
class MouseAndTouchScrollBehavior extends MaterialScrollBehavior {
@override
Set get dragDevices => {
PointerDeviceKind.touch,
PointerDeviceKind.mouse,
};
}
================================================
FILE: lib/screens/components/pager.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/entities/entities.dart';
import 'package:nhentai/screens/comic_info_screen.dart';
import 'package:waterfall_flow/waterfall_flow.dart';
import 'images.dart';
class Pager extends StatefulWidget {
final FutureOr Function(int page) onPage;
const Pager({required this.onPage, Key? key}) : super(key: key);
@override
State createState() => _PageState();
}
class _PageState extends State {
late ScrollController _controller;
int _currentPage = 1;
bool _lastPage = false;
final List _data = [];
var _joining = false;
late Future _joinFuture;
Future _join() async {
try {
setState(() {
_joining = true;
});
var response = await widget.onPage(_currentPage);
_data.addAll(response.records);
_currentPage++;
if (response.pageCount <= _currentPage) {
_lastPage = true;
}
} finally {
setState(() {
_joining = false;
});
}
}
void _next() {
setState(() {
_joinFuture = _join();
});
}
void _onScroll() {
if (_joining || _lastPage) {
return;
}
if (_controller.position.pixels < _controller.position.maxScrollExtent) {
return;
}
_next();
}
@override
void initState() {
_joinFuture = _join();
_controller = ScrollController();
_controller.addListener(_onScroll);
super.initState();
}
@override
void dispose() {
_controller.removeListener(_onScroll);
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
const int crossCount = 2;
return WaterfallFlow.builder(
controller: _controller,
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.only(top: 10, bottom: 10),
itemCount: _data.length + 1,
gridDelegate: const SliverWaterfallFlowDelegateWithFixedCrossAxisCount(
crossAxisCount: crossCount,
crossAxisSpacing: 0,
mainAxisSpacing: 0,
),
itemBuilder: (BuildContext context, int index) {
if (index >= _data.length) {
return _buildLoadingCard();
}
return _buildImageCard(_data[index]);
},
);
}
Widget _buildLoadingCard() {
return FutureBuilder(
future: _joinFuture,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState != ConnectionState.done) {
return Card(
child: Column(
children: [
Container(
padding: const EdgeInsets.only(top: 10, bottom: 10),
child: const CupertinoActivityIndicator(
radius: 14,
),
),
Text(AppLocalizations.of(context)!.loading),
],
),
);
}
if (snapshot.hasError) {
print("${snapshot.error}");
print("${snapshot.stackTrace}");
return Card(
child: InkWell(
onTap: _next,
child: Column(
children: [
Container(
padding: const EdgeInsets.only(top: 10, bottom: 10),
child: const Icon(Icons.sync_problem_rounded),
),
Text(AppLocalizations.of(context)!.errorAndTapRetry),
],
),
),
);
}
return Container();
},
);
}
Widget _buildImageCard(ComicSimple item) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) {
return ComicInfoScreen(item.id, item.title);
},
));
},
child: Card(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
return HorizontalStretchNHentaiImage(
url: item.thumb,
originSize: Size(
item.thumbWidth.toDouble(),
item.thumbHeight.toDouble(),
),
);
},
),
),
);
}
}
================================================
FILE: lib/screens/file_photo_view_screen.dart
================================================
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/common/common.dart';
import 'package:nhentai/basic/common/cross.dart';
import 'package:photo_view/photo_view.dart';
// 预览图片
class FilePhotoViewScreen extends StatelessWidget {
final String filePath;
const FilePhotoViewScreen(this.filePath);
@override
Widget build(BuildContext context) => Scaffold(
body: Stack(
children: [
GestureDetector(
onLongPress: () async {
String? choose =
await chooseListDialog(context, '请选择', ['保存图片']);
switch (choose) {
case '保存图片':
saveImage(filePath, context);
break;
}
},
child: PhotoView(
imageProvider: FileImage(File(filePath)),
),
),
InkWell(
onTap: () => Navigator.of(context).pop(),
child: Container(
margin: const EdgeInsets.only(top: 30),
padding: const EdgeInsets.only(left: 4, right: 4),
decoration: BoxDecoration(
color: Colors.black.withOpacity(.75),
borderRadius: const BorderRadius.only(
topRight: Radius.circular(8),
bottomRight: Radius.circular(8),
),
),
child:
const Icon(Icons.keyboard_backspace, color: Colors.white),
),
),
],
),
);
}
================================================
FILE: lib/screens/init_screen.dart
================================================
import 'dart:io';
import 'package:app_links/app_links.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/configs/proxy.dart';
import 'package:nhentai/basic/configs/reader_direction.dart';
import 'package:nhentai/basic/configs/reader_type.dart';
import 'package:nhentai/basic/configs/themes.dart';
import 'package:nhentai/basic/configs/version.dart';
import 'comic_info_screen.dart';
import 'comics_screen.dart';
class InitScreen extends StatefulWidget {
const InitScreen({Key? key}) : super(key: key);
@override
State createState() => _InitScreenState();
}
class _InitScreenState extends State {
@override
void initState() {
_init();
super.initState();
}
Future _init() async {
await initVersion();
autoCheckNewVersion();
await initTheme();
await initProxy();
await initReaderType();
await initReaderDirection();
late Widget gotoScreen;
String? initUrl;
if (Platform.isAndroid || Platform.isIOS) {
try {
final appLinks = AppLinks();
initUrl = (await appLinks.getInitialAppLink())?.toString();
// Use the uri and warn the user, if it is not correct,
// but keep in mind it could be `null`.
} on FormatException {
// Handle exception by warning the user their action did not succeed
// return?
}
}
if (initUrl != null) {
RegExp regExp = RegExp(r"^https://nhentai\.net/g/(\d+)/$");
final matches = regExp.allMatches(initUrl!);
if (matches.isNotEmpty) {
final id = int.parse(matches.first.group(1)!);
gotoScreen = ComicInfoScreen(id, "");
} else {
gotoScreen = ComicsScreen();
}
} else {
gotoScreen = ComicsScreen();
}
Navigator.of(context).pushReplacement(MaterialPageRoute(
builder: (BuildContext context) => gotoScreen,
));
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
Container(
color: const Color(0xff313131),
),
SafeArea(
child: Column(
children: [
Expanded(child: Container()),
Material(
color: const Color(0x00000000),
child: Text(
AppLocalizations.of(context)!.initializing,
style: const TextStyle(color: Colors.white),
),
),
],
),
),
SafeArea(
child: Center(
child: LayoutBuilder(
builder: (BuildContext context, BoxConstraints constraints) {
var size = constraints.maxWidth < constraints.maxHeight
? constraints.maxWidth
: constraints.maxHeight;
size /= 2;
return SizedBox(
width: size,
height: size,
child: Image.asset(
"lib/assets/startup.png",
width: size,
height: size,
),
);
},
),
),
),
],
);
}
}
================================================
FILE: lib/screens/settings_screen.dart
================================================
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
import 'package:flutter/material.dart';
import 'package:nhentai/basic/configs/proxy.dart';
import 'package:nhentai/basic/configs/themes.dart';
import 'package:nhentai/basic/configs/version.dart';
class SettingsScreen extends StatelessWidget {
const SettingsScreen({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(AppLocalizations.of(context)!.settings),
),
body: ListView(
children: [
const Divider(),
themeSetting(context),
const Divider(),
proxySetting(),
const Divider(),
autoUpdateCheckSetting(),
const Divider(),
const VersionInfo(),
const Divider(),
],
),
);
}
}
================================================
FILE: lib/screens/webview_screen.dart
================================================
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:nhentai/basic/channels/nhentai.dart';
import 'package:nhentai/basic/common/common.dart';
class WebViewScreen extends StatefulWidget {
const WebViewScreen({Key? key}) : super(key: key);
@override
State createState() => _WebViewScreenState();
}
class _WebViewScreenState extends State {
late InAppWebViewController _webViewController;
late CookieManager _cookieManager;
@override
void initState() {
_cookieManager = CookieManager.instance();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Load web cookies"),
actions: [
IconButton(
onPressed: () {
_webViewController.loadUrl(
urlRequest:
URLRequest(url: Uri.parse('https://nhentai.net/')));
},
icon: const Icon(Icons.refresh),
),
IconButton(
onPressed: () async {
final body = await _webViewController.evaluateJavascript(
source: "navigator.userAgent");
await nHentai.setUserAgent(body);
// var cookies =
// await _webViewController.evaluateJavascript(source: "document.cookie");
//
// if (cookies.startsWith("\"")) {
// cookies = cookies.replaceAll("\"", "");
// }
final cookies = await _cookieManager.getCookies(
url: Uri.parse('https://nhentai.net/'));
print(cookies.map((e) => "${e.name}=${e.value}").join("; "));
await nHentai.setCookie(
cookies.map((e) => "${e.name}=${e.value}").join("; "));
Navigator.of(context).pop();
},
icon: const Icon(Icons.check),
),
],
),
body: InAppWebView(
initialUrlRequest: URLRequest(
url: Uri.parse('https://nhentai.net/'),
),
onLoadStart: (c, url) {
print("onLoadStart");
_webViewController = c;
},
),
);
}
}
================================================
FILE: linux/.gitignore
================================================
flutter/ephemeral
================================================
FILE: linux/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.10)
project(runner LANGUAGES CXX)
set(BINARY_NAME "nhentai")
set(APPLICATION_ID "com.example.nhentai")
cmake_policy(SET CMP0063 NEW)
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Configure build options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$>:NDEBUG>")
endfunction()
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
# Flutter library and tool build rules.
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Application build
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
apply_standard_settings(${BINARY_NAME})
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
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.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
================================================
FILE: linux/flutter/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)
================================================
FILE: linux/flutter/generated_plugin_registrant.cc
================================================
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
}
================================================
FILE: linux/flutter/generated_plugin_registrant.h
================================================
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
================================================
FILE: linux/flutter/generated_plugins.cmake
================================================
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
url_launcher_linux
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/linux plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/linux plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
================================================
FILE: linux/main.cc
================================================
#include "my_application.h"
int main(int argc, char** argv) {
g_autoptr(MyApplication) app = my_application_new();
return g_application_run(G_APPLICATION(app), argc, argv);
}
================================================
FILE: linux/my_application.cc
================================================
#include "my_application.h"
#include
#ifdef GDK_WINDOWING_X11
#include
#endif
#include "flutter/generated_plugin_registrant.h"
struct _MyApplication {
GtkApplication parent_instance;
char** dart_entrypoint_arguments;
};
G_DEFINE_TYPE(MyApplication, my_application, GTK_TYPE_APPLICATION)
// Implements GApplication::activate.
static void my_application_activate(GApplication* application) {
MyApplication* self = MY_APPLICATION(application);
GtkWindow* window =
GTK_WINDOW(gtk_application_window_new(GTK_APPLICATION(application)));
// Use a header bar when running in GNOME as this is the common style used
// by applications and is the setup most users will be using (e.g. Ubuntu
// desktop).
// If running on X and not using GNOME then just use a traditional title bar
// in case the window manager does more exotic layout, e.g. tiling.
// If running on Wayland assume the header bar will work (may need changing
// if future cases occur).
gboolean use_header_bar = TRUE;
#ifdef GDK_WINDOWING_X11
GdkScreen* screen = gtk_window_get_screen(window);
if (GDK_IS_X11_SCREEN(screen)) {
const gchar* wm_name = gdk_x11_screen_get_window_manager_name(screen);
if (g_strcmp0(wm_name, "GNOME Shell") != 0) {
use_header_bar = FALSE;
}
}
#endif
if (use_header_bar) {
GtkHeaderBar* header_bar = GTK_HEADER_BAR(gtk_header_bar_new());
gtk_widget_show(GTK_WIDGET(header_bar));
gtk_header_bar_set_title(header_bar, "nhentai");
gtk_header_bar_set_show_close_button(header_bar, TRUE);
gtk_window_set_titlebar(window, GTK_WIDGET(header_bar));
} else {
gtk_window_set_title(window, "nhentai");
}
gtk_window_set_default_size(window, 1280, 720);
gtk_widget_show(GTK_WIDGET(window));
g_autoptr(FlDartProject) project = fl_dart_project_new();
fl_dart_project_set_dart_entrypoint_arguments(project, self->dart_entrypoint_arguments);
FlView* view = fl_view_new(project);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application, gchar*** arguments, int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line = my_application_local_command_line;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID,
"flags", G_APPLICATION_NON_UNIQUE,
nullptr));
}
================================================
FILE: linux/my_application.h
================================================
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include
G_DECLARE_FINAL_TYPE(MyApplication, my_application, MY, APPLICATION,
GtkApplication)
/**
* my_application_new:
*
* Creates a new Flutter-based application.
*
* Returns: a new #MyApplication.
*/
MyApplication* my_application_new();
#endif // FLUTTER_MY_APPLICATION_H_
================================================
FILE: macos/.gitignore
================================================
# Flutter-related
**/Flutter/ephemeral/
**/Pods/
# Xcode-related
**/dgph
**/xcuserdata/
================================================
FILE: macos/Flutter/Flutter-Debug.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.debug.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
================================================
FILE: macos/Flutter/Flutter-Release.xcconfig
================================================
#include? "Pods/Target Support Files/Pods-Runner/Pods-Runner.release.xcconfig"
#include "ephemeral/Flutter-Generated.xcconfig"
================================================
FILE: macos/Flutter/GeneratedPluginRegistrant.swift
================================================
//
// Generated file. Do not edit.
//
import FlutterMacOS
import Foundation
import app_links_macos
import url_launcher_macos
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
AppLinksMacosPlugin.register(with: registry.registrar(forPlugin: "AppLinksMacosPlugin"))
UrlLauncherPlugin.register(with: registry.registrar(forPlugin: "UrlLauncherPlugin"))
}
================================================
FILE: macos/Podfile
================================================
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
================================================
FILE: macos/Runner/AppDelegate.swift
================================================
import Cocoa
import FlutterMacOS
@NSApplicationMain
class AppDelegate: FlutterAppDelegate {
override func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
}
================================================
FILE: macos/Runner/Assets.xcassets/AppIcon.appiconset/Contents.json
================================================
{
"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"
}
}
================================================
FILE: macos/Runner/Base.lproj/MainMenu.xib
================================================
================================================
FILE: macos/Runner/Configs/AppInfo.xcconfig
================================================
// 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 = nhentai
// The application's bundle identifier
PRODUCT_BUNDLE_IDENTIFIER = com.example.nhentai
// The copyright displayed in application information
PRODUCT_COPYRIGHT = Copyright © 2021 com.example. All rights reserved.
================================================
FILE: macos/Runner/Configs/Debug.xcconfig
================================================
#include "../../Flutter/Flutter-Debug.xcconfig"
#include "Warnings.xcconfig"
================================================
FILE: macos/Runner/Configs/Release.xcconfig
================================================
#include "../../Flutter/Flutter-Release.xcconfig"
#include "Warnings.xcconfig"
================================================
FILE: macos/Runner/Configs/Warnings.xcconfig
================================================
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
================================================
FILE: macos/Runner/DebugProfile.entitlements
================================================
com.apple.security.app-sandbox
com.apple.security.cs.allow-jit
com.apple.security.network.server
================================================
FILE: macos/Runner/Info.plist
================================================
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
================================================
FILE: macos/Runner/MainFlutterWindow.swift
================================================
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()
}
}
================================================
FILE: macos/Runner/Release.entitlements
================================================
com.apple.security.app-sandbox
================================================
FILE: macos/Runner.xcodeproj/project.pbxproj
================================================
// !$*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 */; };
/* 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 */
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 /* nhentai.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "nhentai.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 = ""; };
7AFA3C8E1D35360C0083082E /* Release.xcconfig */ = {isa = PBXFileReference; lastKnownFileType = text.xcconfig; path = Release.xcconfig; sourceTree = ""; };
9740EEB21CF90195004384FC /* Debug.xcconfig */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xcconfig; path = Debug.xcconfig; sourceTree = ""; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
33CC10EA2044A3C60003C045 /* Frameworks */ = {
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
);
runOnlyForDeploymentPostprocessing = 0;
};
/* End PBXFrameworksBuildPhase section */
/* Begin PBXGroup section */
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 */,
);
sourceTree = "";
};
33CC10EE2044A3C60003C045 /* Products */ = {
isa = PBXGroup;
children = (
33CC10ED2044A3C60003C045 /* nhentai.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 = (
);
name = Frameworks;
sourceTree = "";
};
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
33CC10EC2044A3C60003C045 /* Runner */ = {
isa = PBXNativeTarget;
buildConfigurationList = 33CC10FB2044A3C60003C045 /* Build configuration list for PBXNativeTarget "Runner" */;
buildPhases = (
33CC10E92044A3C60003C045 /* Sources */,
33CC10EA2044A3C60003C045 /* Frameworks */,
33CC10EB2044A3C60003C045 /* Resources */,
33CC110E2044A8840003C045 /* Bundle Framework */,
3399D490228B24CF009A79C7 /* ShellScript */,
);
buildRules = (
);
dependencies = (
33CC11202044C79F0003C045 /* PBXTargetDependency */,
);
name = Runner;
productName = Runner;
productReference = 33CC10ED2044A3C60003C045 /* nhentai.app */;
productType = "com.apple.product-type.application";
};
/* End PBXNativeTarget section */
/* Begin PBXProject section */
33CC10E52044A3C60003C045 /* Project object */ = {
isa = PBXProject;
attributes = {
LastSwiftUpdateCheck = 0920;
LastUpgradeCheck = 0930;
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 */
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";
};
/* 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.11;
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.11;
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.11;
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 */;
}
================================================
FILE: macos/Runner.xcodeproj/project.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: macos/Runner.xcodeproj/xcshareddata/xcschemes/Runner.xcscheme
================================================
================================================
FILE: macos/Runner.xcworkspace/contents.xcworkspacedata
================================================
================================================
FILE: macos/Runner.xcworkspace/xcshareddata/IDEWorkspaceChecks.plist
================================================
IDEDidComputeMac32BitWarning
================================================
FILE: pubspec.yaml
================================================
name: nhentai
description: nhentai client
publish_to: 'none'
version: 0.0.9+2
environment:
sdk: ">=2.12.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_styled_toast: 2.0.0
intl: ^0.17.0
event: ^2.0.5
waterfall_flow: ^3.0.1
photo_view: ^0.13.0
clipboard: ^0.1.3
hidden_drawer_menu: ^3.0.1
url_launcher: ^6.0.17
filesystem_picker: 2.0.0
date_format: ^2.0.4
another_xlider: 1.0.1+2
modal_bottom_sheet: ^2.0.0
app_links: ^3.2.0
flutter_inappwebview: ^5.5.0+2
permission_handler: ^10.1.0
dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^1.0.0
flutter:
uses-material-design: true
generate: true
assets:
- lib/assets/
================================================
FILE: scripts/README.md
================================================
用于记录作者构建时使用的脚本
================================================
FILE: scripts/bind-android-debug.sh
================================================
# 编译所有架构的依赖
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
gomobile bind -androidapi 19 -target=android/arm,android/arm64,android/386,android/amd64 -o lib/Mobile.aar ./
================================================
FILE: scripts/bind-ios-arm64.sh
================================================
# 编译所有架构的依赖
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
gomobile bind -androidapi 19 -target=ios -o lib/Mobile.xcframework ./
================================================
FILE: scripts/bind-ios.sh
================================================
# 编译所有架构的依赖
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
gomobile bind -iosversion 11.0 -target=ios -o lib/Mobile.xcframework ./
================================================
FILE: scripts/build-apk-arm.sh
================================================
# 仅构建arm的APK
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
go get golang.org/x/mobile/cmd/gobind
gomobile bind -androidapi 19 -target=android/arm -o lib/Mobile.aar ./
cd ../..
flutter build apk --target-platform android-arm
================================================
FILE: scripts/build-apk-arm64.sh
================================================
# 仅构建arm64的APK
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
go get golang.org/x/mobile/cmd/gobind
gomobile bind -androidapi 19 -target=android/arm64 -o lib/Mobile.aar ./
cd ../..
flutter build apk --target-platform android-arm64
================================================
FILE: scripts/build-apk-x64.sh
================================================
# 仅构建x86_64的APK
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
go get golang.org/x/mobile/cmd/gobind
gomobile bind -androidapi 19 -target=android/amd64 -o lib/Mobile.aar ./
cd ../..
flutter build apk --target-platform android-x64
================================================
FILE: scripts/build-apk-x86.sh
================================================
# 仅构建x86的APK
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
go get golang.org/x/mobile/cmd/gobind
gomobile bind -androidapi 19 -target=android/386 -o lib/Mobile.aar ./
cd ../..
flutter build apk --target-platform android-x86
================================================
FILE: scripts/build-ipa.sh
================================================
# 构建未签名的IPA
cd "$( cd "$( dirname "$0" )" && pwd )/.."
cd go/mobile
go get golang.org/x/mobile/cmd/gobind
gomobile bind -iosversion 11.0 -target=ios -o lib/Mobile.xcframework ./
cd ../..
flutter build ios --release --no-codesign
cd build
mkdir -p Payload
mv ios/iphoneos/Runner.app Payload
sh ../scripts/thin-payload.sh
zip -9 nosign.ipa -r Payload
================================================
FILE: scripts/build-macos-dmg.sh
================================================
# 构建macos
cd "$( cd "$( dirname "$0" )" && pwd )/.."
hover build darwin-dmg
================================================
FILE: scripts/sign-apk-github-actions.sh
================================================
cd "$( cd "$( dirname "$0" )" && pwd )/.."
echo $KEY_FILE_BASE64 > key.jks.base64
base64 -d key.jks.base64 > key.jks
echo $KEY_PASSWORD | $ANDROID_HOME/build-tools/30.0.2/apksigner sign --ks key.jks build/app/outputs/flutter-apk/app-release.apk
================================================
FILE: scripts/thin-payload.sh
================================================
# 精简Payload文件夹 (上传到AppStore会自动区分平台, 此代码仅用于构建非签名ipa)
foreachThin(){
for file in $1/*
do
if test -f $file
then
mime=$(file --mime-type -b $file)
if [ "$mime" == 'application/x-mach-binary' ] || [ "${file##*.}"x = "dylib"x ]
then
echo thin $file
xcrun -sdk iphoneos lipo "$file" -thin arm64 -output "$file"
xcrun -sdk iphoneos bitcode_strip "$file" -r -o "$file"
strip -S -x "$file" -o "$file"
fi
fi
if test -d $file
then
foreachThin $file
fi
done
}
foreachThin ./Payload
================================================
FILE: scripts/version.sh
================================================
# 设置版本号
cd "$( cd "$( dirname "$0" )" && pwd )/.."
if [ "$1" == "set" ] ; then
if [ "$2" != "" ] ; then
echo $2 > lib/assets/version.txt
fi
elif [ "$1" == "unset" ]; then
rm -f lib/assets/version.txt
fi
================================================
FILE: test/widget_test.dart
================================================
// This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. 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:nhentai/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
================================================
FILE: windows/.gitignore
================================================
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
================================================
FILE: windows/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.15)
project(nhentai LANGUAGES CXX)
set(BINARY_NAME "nhentai")
cmake_policy(SET CMP0063 NEW)
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Configure build options.
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()
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.
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()
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
# Flutter library and tool build rules.
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build
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)
================================================
FILE: windows/flutter/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.15)
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}
)
================================================
FILE: windows/flutter/generated_plugin_registrant.cc
================================================
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
#include
#include
#include
void RegisterPlugins(flutter::PluginRegistry* registry) {
AppLinksWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("AppLinksWindowsPlugin"));
PermissionHandlerWindowsPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("PermissionHandlerWindowsPlugin"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
}
================================================
FILE: windows/flutter/generated_plugin_registrant.h
================================================
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
================================================
FILE: windows/flutter/generated_plugins.cmake
================================================
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
app_links_windows
permission_handler_windows
url_launcher_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
)
set(PLUGIN_BUNDLED_LIBRARIES)
foreach(plugin ${FLUTTER_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${plugin}/windows plugins/${plugin})
target_link_libraries(${BINARY_NAME} PRIVATE ${plugin}_plugin)
list(APPEND PLUGIN_BUNDLED_LIBRARIES $)
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${plugin}_bundled_libraries})
endforeach(plugin)
foreach(ffi_plugin ${FLUTTER_FFI_PLUGIN_LIST})
add_subdirectory(flutter/ephemeral/.plugin_symlinks/${ffi_plugin}/windows plugins/${ffi_plugin})
list(APPEND PLUGIN_BUNDLED_LIBRARIES ${${ffi_plugin}_bundled_libraries})
endforeach(ffi_plugin)
================================================
FILE: windows/runner/CMakeLists.txt
================================================
cmake_minimum_required(VERSION 3.15)
project(runner LANGUAGES CXX)
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_standard_settings(${BINARY_NAME})
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
add_dependencies(${BINARY_NAME} flutter_assemble)
================================================
FILE: windows/runner/Runner.rc
================================================
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#ifdef FLUTTER_BUILD_NUMBER
#define VERSION_AS_NUMBER FLUTTER_BUILD_NUMBER
#else
#define VERSION_AS_NUMBER 1,0,0
#endif
#ifdef FLUTTER_BUILD_NAME
#define VERSION_AS_STRING #FLUTTER_BUILD_NAME
#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", "com.example" "\0"
VALUE "FileDescription", "A new Flutter project." "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "nhentai" "\0"
VALUE "LegalCopyright", "Copyright (C) 2021 com.example. All rights reserved." "\0"
VALUE "OriginalFilename", "nhentai.exe" "\0"
VALUE "ProductName", "nhentai" "\0"
VALUE "ProductVersion", VERSION_AS_STRING "\0"
END
END
BLOCK "VarFileInfo"
BEGIN
VALUE "Translation", 0x409, 1252
END
END
#endif // English (United States) resources
/////////////////////////////////////////////////////////////////////////////
#ifndef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 3 resource.
//
/////////////////////////////////////////////////////////////////////////////
#endif // not APSTUDIO_INVOKED
================================================
FILE: windows/runner/flutter_window.cpp
================================================
#include "flutter_window.h"
#include
#include "flutter/generated_plugin_registrant.h"
FlutterWindow::FlutterWindow(const flutter::DartProject& project)
: project_(project) {}
FlutterWindow::~FlutterWindow() {}
bool FlutterWindow::OnCreate() {
if (!Win32Window::OnCreate()) {
return false;
}
RECT frame = GetClientArea();
// The size here must match the window dimensions to avoid unnecessary surface
// creation / destruction in the startup path.
flutter_controller_ = std::make_unique(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional result =
flutter_controller_->HandleTopLevelWindowProc(hwnd, message, wparam,
lparam);
if (result) {
return *result;
}
}
switch (message) {
case WM_FONTCHANGE:
flutter_controller_->engine()->ReloadSystemFonts();
break;
}
return Win32Window::MessageHandler(hwnd, message, wparam, lparam);
}
================================================
FILE: windows/runner/flutter_window.h
================================================
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include
#include
#include
#include "win32_window.h"
// A window that does nothing but host a Flutter view.
class FlutterWindow : public Win32Window {
public:
// Creates a new FlutterWindow hosting a Flutter view running |project|.
explicit FlutterWindow(const flutter::DartProject& project);
virtual ~FlutterWindow();
protected:
// Win32Window:
bool OnCreate() override;
void OnDestroy() override;
LRESULT MessageHandler(HWND window, UINT const message, WPARAM const wparam,
LPARAM const lparam) noexcept override;
private:
// The project to run.
flutter::DartProject project_;
// The Flutter instance hosted by this window.
std::unique_ptr flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_
================================================
FILE: windows/runner/main.cpp
================================================
#include
#include
#include
#include "flutter_window.h"
#include "utils.h"
int APIENTRY wWinMain(_In_ HINSTANCE instance, _In_opt_ HINSTANCE prev,
_In_ wchar_t *command_line, _In_ int show_command) {
// Attach to console when present (e.g., 'flutter run') or create a
// new console when running with a debugger.
if (!::AttachConsole(ATTACH_PARENT_PROCESS) && ::IsDebuggerPresent()) {
CreateAndAttachConsole();
}
// Initialize COM, so that it is available for use in the library and/or
// plugins.
::CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED);
flutter::DartProject project(L"data");
std::vector command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.CreateAndShow(L"nhentai", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
================================================
FILE: windows/runner/resource.h
================================================
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
================================================
FILE: windows/runner/runner.exe.manifest
================================================
PerMonitorV2
================================================
FILE: windows/runner/utils.cpp
================================================
#include "utils.h"
#include
#include
#include
#include
#include
void CreateAndAttachConsole() {
if (::AllocConsole()) {
FILE *unused;
if (freopen_s(&unused, "CONOUT$", "w", stdout)) {
_dup2(_fileno(stdout), 1);
}
if (freopen_s(&unused, "CONOUT$", "w", stderr)) {
_dup2(_fileno(stdout), 2);
}
std::ios::sync_with_stdio();
FlutterDesktopResyncOutputStreams();
}
}
std::vector GetCommandLineArguments() {
// Convert the UTF-16 command line arguments to UTF-8 for the Engine to use.
int argc;
wchar_t** argv = ::CommandLineToArgvW(::GetCommandLineW(), &argc);
if (argv == nullptr) {
return std::vector();
}
std::vector command_line_arguments;
// Skip the first argument as it's the binary name.
for (int i = 1; i < argc; i++) {
command_line_arguments.push_back(Utf8FromUtf16(argv[i]));
}
::LocalFree(argv);
return command_line_arguments;
}
std::string Utf8FromUtf16(const wchar_t* utf16_string) {
if (utf16_string == nullptr) {
return std::string();
}
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
-1, nullptr, 0, nullptr, nullptr);
if (target_length == 0) {
return std::string();
}
std::string 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;
}
================================================
FILE: windows/runner/utils.h
================================================
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include
#include
// Creates a console for the process, and redirects stdout and stderr to
// it for both the runner and the Flutter library.
void CreateAndAttachConsole();
// Takes a null-terminated wchar_t* encoded in UTF-16 and returns a std::string
// encoded in UTF-8. Returns an empty std::string on failure.
std::string Utf8FromUtf16(const wchar_t* utf16_string);
// Gets the command line arguments passed in as a std::vector,
// encoded in UTF-8. Returns an empty std::vector on failure.
std::vector GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
================================================
FILE: windows/runner/win32_window.cpp
================================================
#include "win32_window.h"
#include
#include "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.
}
================================================
FILE: windows/runner/win32_window.h
================================================
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include
#include
#include
#include
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates 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_