Import netquality 1.1.1

Initial import of the 1.1.1 source tree. Corresponds to Origin commit f9d97e368818acfe7dd44fa9fe5088b9629d0dff.

Co-authored-by: yanjiu0721 <yanjiu0721@users.noreply.github.com>
This commit is contained in:
Cursor Agentandyanjiu0721 committed 2026-11-09 23:06:30 +00:00
1 parent 948594e7c0
commit f6ffbde518
93 files changed
+10570 -1

No files matched your search

+48
View File
@@ -0,0 +1,48 @@
# Miscellaneous
*.class
*.log
*.pyc
*.swp
.DS_Store
.atom/
.build/
.buildlog/
.history
.svn/
.swiftpm/
migrate_working_dir/
# 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-dependencies
.pub-cache/
.pub/
/build/
/coverage/
# 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
# Widget Preview related
.widget_preview/
+36
View File
@@ -0,0 +1,36 @@
# 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: "c197ca5199e9ee5661e865596c9c07294dfab51c"
channel: "stable"
project_type: app
# Tracks metadata for the flutter migrate command
migration:
platforms:
- platform: root
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: android
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: linux
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
- platform: windows
create_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
base_revision: c197ca5199e9ee5661e865596c9c07294dfab51c
# User provided section
# List of Local paths (relative to this file) that should be
# ignored by the migrate tool.
#
# Files that are not part of the templates will be ignored by default.
unmanaged_files:
- 'lib/main.dart'
- 'ios/Runner.xcodeproj/project.pbxproj'
+10
View File
@@ -0,0 +1,10 @@
# 客户端
Flutter 应用,支持 Linux、Windows 桌面和 Android。用法、节点安装和协议说明见仓库根目录的 [README.md](../README.md)。
```bash
flutter pub get
flutter run -d linux
```
默认用本机去测 `127.0.0.1` 的合作反射 TCP `19090`。先在 `../server` 里启动反射服务,再点「开始探测」。要让另一台机器代测时,把来源改成「远程节点」。
+35
View File
@@ -0,0 +1,35 @@
# 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
analyzer:
exclude:
- build/**
- android/**
- windows/**
- linux/**
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.dev/lints.
#
# 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
+14
View File
@@ -0,0 +1,14 @@
gradle-wrapper.jar
/.gradle
/captures/
/gradlew
/gradlew.bat
/local.properties
GeneratedPluginRegistrant.java
.cxx/
# Remember to never publicly share your keystore.
# See https://flutter.dev/to/reference-keystore
key.properties
**/*.keystore
**/*.jks
+49
View File
@@ -0,0 +1,49 @@
plugins {
id("com.android.application")
// The Flutter Gradle Plugin must be applied after the Android and Kotlin Gradle plugins.
id("dev.flutter.flutter-gradle-plugin")
}
android {
namespace = "dev.netquality.netquality"
compileSdk = flutter.compileSdkVersion
ndkVersion = flutter.ndkVersion
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
defaultConfig {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId = "dev.netquality.netquality"
// You can update the following values to match your application needs.
// For more information, see: https://flutter.dev/to/review-gradle-config.
minSdk = flutter.minSdkVersion
targetSdk = flutter.targetSdkVersion
// Uses the version code from pubspec.yaml. When using split APKs, 1000 * ABI_VERSION
// is added automatically by Flutter. (https://developer.android.com/studio/build/configure-apk-splits#configure-APK-versions)
// You can force using the value of versionCode by specifying the `-P force-version-code-ignoring-abi=true`
// flag during build.
versionCode = flutter.versionCode
versionName = flutter.versionName
}
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.getByName("debug")
}
}
}
kotlin {
compilerOptions {
jvmTarget = org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17
}
}
flutter {
source = "../.."
}
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
@@ -0,0 +1,46 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="网络质量探测"
android:name="${applicationName}"
android:icon="@mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:exported="true"
android:launchMode="singleTop"
android:taskAffinity=""
android:theme="@style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="@style/NormalTheme"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
<!-- Required to query activities that can process text, see:
https://developer.android.com/training/package-visibility and
https://developer.android.com/reference/android/content/Intent#ACTION_PROCESS_TEXT.
In particular, this is used by the Flutter engine in io.flutter.plugin.text.ProcessTextPlugin. -->
<queries>
<intent>
<action android:name="android.intent.action.PROCESS_TEXT"/>
<data android:mimeType="text/plain"/>
</intent>
</queries>
</manifest>
@@ -0,0 +1,5 @@
package dev.netquality.netquality
import io.flutter.embedding.android.FlutterActivity
class MainActivity : FlutterActivity()
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="?android:colorBackground" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Modify this file to customize your launch splash screen -->
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white" />
<!-- You can insert your own image assets here -->
<!-- <item>
<bitmap
android:gravity="center"
android:src="@mipmap/launch_image" />
</item> -->
</layer-list>
Binary file not shown.

After

Width:  |  Height:  |  Size: 544 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 442 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 721 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is on -->
<style name="LaunchTheme" parent="@android:style/Theme.Black.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Black.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Theme applied to the Android Window while the process is starting when the OS's Dark Mode setting is off -->
<style name="LaunchTheme" parent="@android:style/Theme.Light.NoTitleBar">
<!-- Show a splash screen on the activity. Automatically removed when
the Flutter engine draws its first frame -->
<item name="android:windowBackground">@drawable/launch_background</item>
</style>
<!-- Theme applied to the Android Window as soon as the process has started.
This theme determines the color of the Android Window while your
Flutter UI initializes, as well as behind your Flutter UI while its
running.
This Theme is only used starting with V2 of Flutter's Android embedding. -->
<style name="NormalTheme" parent="@android:style/Theme.Light.NoTitleBar">
<item name="android:windowBackground">?android:colorBackground</item>
</style>
</resources>
@@ -0,0 +1,7 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- The INTERNET permission is required for development. Specifically,
the Flutter tool needs it to communicate with the running application
to allow setting breakpoints, to provide hot reload, etc.
-->
<uses-permission android:name="android.permission.INTERNET"/>
</manifest>
+24
View File
@@ -0,0 +1,24 @@
allprojects {
repositories {
google()
mavenCentral()
}
}
val newBuildDir: Directory =
rootProject.layout.buildDirectory
.dir("../../build")
.get()
rootProject.layout.buildDirectory.value(newBuildDir)
subprojects {
val newSubprojectBuildDir: Directory = newBuildDir.dir(project.name)
project.layout.buildDirectory.value(newSubprojectBuildDir)
}
subprojects {
project.evaluationDependsOn(":app")
}
tasks.register<Delete>("clean") {
delete(rootProject.layout.buildDirectory)
}
+6
View File
@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx8G -XX:MaxMetaspaceSize=4G -XX:ReservedCodeCacheSize=512m -XX:+HeapDumpOnOutOfMemoryError
android.useAndroidX=true
# This newDsl flag was added by the Flutter template
android.newDsl=false
# This builtInKotlin flag was added by the Flutter template
android.builtInKotlin=false
@@ -0,0 +1,5 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip
+26
View File
@@ -0,0 +1,26 @@
pluginManagement {
val flutterSdkPath =
run {
val properties = java.util.Properties()
file("local.properties").inputStream().use { properties.load(it) }
val flutterSdkPath = properties.getProperty("flutter.sdk")
require(flutterSdkPath != null) { "flutter.sdk not set in local.properties" }
flutterSdkPath
}
includeBuild("$flutterSdkPath/packages/flutter_tools/gradle")
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
plugins {
id("dev.flutter.flutter-plugin-loader") version "1.0.0"
id("com.android.application") version "9.1.0" apply false
id("org.jetbrains.kotlin.android") version "2.4.0" apply false
}
include(":app")
+7
View File
@@ -0,0 +1,7 @@
WenQuanYi Micro Hei (subset)
Copyright 2008-2009 The WenQuanYi Project Board of Trustees
Copyright 2006-2008 Google Corporation
Copyright 2006-2008 Steve Matteson, Ascender Corp.
This subset is licensed under the Apache License, Version 2.0.
http://www.apache.org/licenses/LICENSE-2.0
Binary file not shown.
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'ui/home_page.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const NetQualityApp());
}
class NetQualityApp extends StatelessWidget {
const NetQualityApp({super.key});
@override
Widget build(BuildContext context) {
const paper = Color(0xFFF3F1EC);
final scheme = ColorScheme.fromSeed(
seedColor: const Color(0xFF1F4E79),
surface: paper,
);
return MaterialApp(
title: '网络质量探测',
debugShowCheckedModeBanner: false,
theme: ThemeData(
colorScheme: scheme,
scaffoldBackgroundColor: paper,
useMaterial3: true,
fontFamilyFallback: const [
'NetQualityCJK',
'Noto Sans CJK SC',
'Noto Sans SC',
'PingFang SC',
'Microsoft YaHei',
'Droid Sans Fallback',
],
inputDecorationTheme: const InputDecorationTheme(
filled: true,
fillColor: Color(0xFFFFFCF7),
isDense: true,
border: OutlineInputBorder(),
),
cardTheme: const CardThemeData(
elevation: 0,
color: Color(0xFFFFFCF7),
margin: EdgeInsets.zero,
),
),
home: const HomePage(),
);
}
}
+331
View File
@@ -0,0 +1,331 @@
class Outcome {
const Outcome({
required this.status,
required this.kind,
this.rttMs,
this.note = '',
this.detail = const {},
this.reconnect = false,
});
final String status;
final String kind;
final double? rttMs;
final String note;
final Map<String, String> detail;
final bool reconnect;
static const ok = 'ok';
static const timeout = 'timeout';
static const unknown = 'unknown';
static const refused = 'refused';
static const dns = 'dns';
static const protocol = 'protocol';
static const error = 'error';
static const connect = 'connect';
static const probe = 'probe';
static const query = 'query';
}
class ProbeSummary {
const ProbeSummary({
required this.sent,
required this.completed,
required this.ok,
required this.timeout,
required this.unknown,
required this.refused,
required this.dns,
required this.protocol,
required this.other,
required this.reconnects,
required this.consecutiveFailures,
required this.rttMs,
required this.jitterMs,
required this.probeLossPct,
required this.failurePct,
required this.unknownPct,
required this.lastNote,
required this.detail,
});
final int sent;
final int completed;
final int ok;
final int timeout;
final int unknown;
final int refused;
final int dns;
final int protocol;
final int other;
final int reconnects;
final int consecutiveFailures;
final double? rttMs;
final double? jitterMs;
final double? probeLossPct;
final double? failurePct;
final double? unknownPct;
final String lastNote;
final Map<String, String> detail;
static const empty = ProbeSummary(
sent: 0,
completed: 0,
ok: 0,
timeout: 0,
unknown: 0,
refused: 0,
dns: 0,
protocol: 0,
other: 0,
reconnects: 0,
consecutiveFailures: 0,
rttMs: null,
jitterMs: null,
probeLossPct: null,
failurePct: null,
unknownPct: null,
lastNote: '',
detail: {},
);
factory ProbeSummary.fromJson(Map<String, dynamic> json) {
return ProbeSummary(
sent: _int(json['sent']),
completed: _int(json['completed']),
ok: _int(json['ok']),
timeout: _int(json['timeout']),
unknown: _int(json['unknown']),
refused: _int(json['refused']),
dns: _int(json['dns']),
protocol: _int(json['protocol']),
other: _int(json['other']),
reconnects: _int(json['reconnects']),
consecutiveFailures: _int(json['consecutiveFailures']),
rttMs: _double(json['rttMs']),
jitterMs: _double(json['jitterMs']),
probeLossPct: _double(json['probeLossPct']),
failurePct: _double(json['failurePct']),
unknownPct: _double(json['unknownPct']),
lastNote: json['lastNote'] is String ? json['lastNote'] as String : '',
detail: _detail(json['detail']),
);
}
}
class ProbeSample {
const ProbeSample({
required this.seq,
required this.status,
required this.kind,
required this.rttMs,
required this.jitterMs,
required this.note,
required this.detail,
required this.summary,
});
final int seq;
final String status;
final String kind;
final double? rttMs;
final double? jitterMs;
final String note;
final Map<String, String> detail;
final ProbeSummary summary;
factory ProbeSample.fromJson(Map<String, dynamic> json) {
final summary = json['summary'] is Map
? ProbeSummary.fromJson(Map<String, dynamic>.from(json['summary'] as Map))
: ProbeSummary.empty;
return ProbeSample(
seq: _int(json['seq']),
status: json['status'] is String ? json['status'] as String : '',
kind: json['kind'] is String ? json['kind'] as String : '',
rttMs: _double(json['rttMs']),
jitterMs: _double(json['jitterMs']),
note: json['note'] is String ? json['note'] as String : '',
detail: _detail(json['detail']),
summary: summary,
);
}
}
class SampleBook {
SampleBook(this.profile);
final String profile;
int sent = 0;
int completed = 0;
int ok = 0;
int timeout = 0;
int unknown = 0;
int refused = 0;
int dns = 0;
int protocol = 0;
int other = 0;
int reconnects = 0;
int consecutive = 0;
double? lastRttMs;
double jitterMs = 0;
bool _hasJitter = false;
double _lastTransit = 0;
String lastNote = '';
Map<String, String> detail = {};
void add(Outcome outcome) {
sent += 1;
completed += 1;
if (outcome.reconnect) {
reconnects += 1;
}
if (outcome.note.isNotEmpty) {
lastNote = outcome.note;
}
if (outcome.detail.isNotEmpty) {
detail = {...detail, ...outcome.detail};
}
switch (outcome.status) {
case Outcome.ok:
ok += 1;
consecutive = 0;
final rtt = outcome.rttMs;
if (rtt != null) {
lastRttMs = rtt;
if (_hasJitter) {
final delta = (rtt - _lastTransit).abs();
jitterMs += (delta - jitterMs) / 16;
}
_lastTransit = rtt;
_hasJitter = true;
}
case Outcome.timeout:
if (outcome.kind == Outcome.probe) {
timeout += 1;
} else {
other += 1;
}
consecutive += 1;
case Outcome.unknown:
unknown += 1;
case Outcome.refused:
refused += 1;
consecutive += 1;
case Outcome.dns:
dns += 1;
consecutive += 1;
case Outcome.protocol:
protocol += 1;
consecutive += 1;
default:
other += 1;
consecutive += 1;
}
}
ProbeSummary summary() {
double? probeLoss;
double? failure;
double? unknownPct;
if (completed > 0) {
if (profile == 'nq-tcp' || profile == 'nq-udp') {
final denom = timeout + ok;
if (denom > 0) {
probeLoss = timeout * 100 / denom;
}
} else if (profile == 'tcp-connect' || profile == 'minecraft-java') {
final denom = ok + timeout + refused + dns + protocol + other;
if (denom > 0) {
failure = (denom - ok) * 100 / denom;
}
} else {
final denom = ok + protocol + refused + dns + other;
if (denom > 0) {
failure = (denom - ok) * 100 / denom;
}
final known = unknown + ok + protocol;
if (known > 0) {
unknownPct = unknown * 100 / completed;
}
}
}
return ProbeSummary(
sent: sent,
completed: completed,
ok: ok,
timeout: timeout,
unknown: unknown,
refused: refused,
dns: dns,
protocol: protocol,
other: other,
reconnects: reconnects,
consecutiveFailures: consecutive,
rttMs: lastRttMs,
jitterMs: _hasJitter ? jitterMs : null,
probeLossPct: probeLoss,
failurePct: failure,
unknownPct: unknownPct,
lastNote: lastNote,
detail: detail,
);
}
ProbeSample sample(int seq, Outcome outcome) {
final folded = summary();
return ProbeSample(
seq: seq,
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
jitterMs: outcome.status == Outcome.ok ? folded.jitterMs : null,
note: outcome.note,
detail: outcome.detail,
summary: folded,
);
}
}
double? chartRate(String profile, ProbeSummary summary) {
switch (profile) {
case 'nq-tcp':
case 'nq-udp':
return summary.probeLossPct;
case 'tcp-connect':
case 'minecraft-java':
return summary.failurePct;
default:
return summary.unknownPct;
}
}
int _int(Object? value) {
if (value is int) {
return value;
}
if (value is num) {
return value.toInt();
}
return 0;
}
double? _double(Object? value) {
if (value is num) {
return value.toDouble();
}
return null;
}
Map<String, String> _detail(Object? value) {
if (value is! Map) {
return const {};
}
final out = <String, String>{};
value.forEach((key, item) {
if (key is String && item is String) {
out[key] = item;
}
});
return out;
}
+103
View File
@@ -0,0 +1,103 @@
class ProbeProfile {
const ProbeProfile({
required this.id,
required this.label,
required this.port,
required this.blurb,
required this.rateLabel,
});
final String id;
final String label;
final int port;
final String blurb;
/// Name of the chart that is honest for this profile.
final String rateLabel;
static const nqTcp = ProbeProfile(
id: 'nq-tcp',
label: '合作反射 TCP',
port: 19090,
blurb: '和 NetQuality 反射器保持一条 TCP 长连接,按回显计算往返时间。超时只表示探测没有应答,不是物理丢包。',
rateLabel: '探测无应答',
);
static const nqUdp = ProbeProfile(
id: 'nq-udp',
label: '合作反射 UDP',
port: 19091,
blurb: '向 NetQuality 反射器发 UDP,收到对应序号的回显才算成功。',
rateLabel: '探测无应答',
);
static const tcpConnect = ProbeProfile(
id: 'tcp-connect',
label: '普通 TCP 连通',
port: 80,
blurb: '只测量能否连上以及连接耗时,不发送自定义探测帧。',
rateLabel: '失败率',
);
static const udpGeneric = ProbeProfile(
id: 'udp-generic',
label: '普通 UDP',
port: 9,
blurb: '发出 UDP 后如果没有协议应答,记为无应答/未知,不能当成丢包。',
rateLabel: '无应答(未知)',
);
static const dns = ProbeProfile(
id: 'dns',
label: 'DNS',
port: 53,
blurb: '发送标准 DNS 查询,序号和应答标志都对上才算成功。',
rateLabel: '无应答(未知)',
);
static const minecraftJava = ProbeProfile(
id: 'minecraft-java',
label: 'Minecraft Java',
port: 25565,
blurb: '按 Java 版状态握手读取 MOTD,再用 ping/pong 计算往返时间。',
rateLabel: '失败率',
);
static const minecraftBedrock = ProbeProfile(
id: 'minecraft-bedrock',
label: 'Minecraft 基岩版',
port: 19132,
blurb: '发送 RakNet Unconnected Ping,校验 magic 和原时间戳。',
rateLabel: '无应答(未知)',
);
static const customUdp = ProbeProfile(
id: 'custom-udp',
label: '自定义 UDP',
port: 19132,
blurb: '发送你填写的十六进制载荷。可以要求响应以前若干字节开头。',
rateLabel: '无应答(未知)',
);
static const all = <ProbeProfile>[
nqTcp,
nqUdp,
tcpConnect,
udpGeneric,
dns,
minecraftJava,
minecraftBedrock,
customUdp,
];
static ProbeProfile byId(String id) {
for (final profile in all) {
if (profile.id == id) {
return profile;
}
}
return nqTcp;
}
bool get needsPacketSize =>
id == 'nq-tcp' || id == 'nq-udp' || id == 'udp-generic';
bool get needsEchoToken => id == 'nq-tcp' || id == 'nq-udp';
bool get isNq => needsEchoToken;
}
String rateLabelFor(String profileId) => ProbeProfile.byId(profileId).rateLabel;
+291
View File
@@ -0,0 +1,291 @@
import 'dart:convert';
import '../protocol/probe_packet.dart';
import 'probe_profile.dart';
class RemoteNode {
const RemoteNode({
required this.id,
required this.name,
required this.baseUrl,
this.visibility = '',
});
final String id;
final String name;
final String baseUrl;
final String visibility;
RemoteNode copyWith({String? name, String? baseUrl, String? visibility}) {
return RemoteNode(
id: id,
name: name ?? this.name,
baseUrl: baseUrl ?? this.baseUrl,
visibility: visibility ?? this.visibility,
);
}
Map<String, Object?> toJson() => {
'id': id,
'name': name,
'baseUrl': baseUrl,
'visibility': visibility,
};
factory RemoteNode.fromJson(Map<String, dynamic> json) {
return RemoteNode(
id: json['id'] is String ? json['id'] as String : '',
name: json['name'] is String ? json['name'] as String : '未命名节点',
baseUrl: json['baseUrl'] is String ? json['baseUrl'] as String : '',
visibility: json['visibility'] is String ? json['visibility'] as String : '',
);
}
}
class SessionConfig {
const SessionConfig({
required this.remote,
required this.nodeId,
required this.nodes,
required this.host,
required this.port,
required this.profileId,
required this.intervalMs,
required this.timeoutMs,
required this.durationSec,
required this.packetSize,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
static const defaults = SessionConfig(
remote: false,
nodeId: '',
nodes: [],
host: '127.0.0.1',
port: 19090,
profileId: 'nq-tcp',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
);
final bool remote;
final String nodeId;
final List<RemoteNode> nodes;
final String host;
final int port;
final String profileId;
final int intervalMs;
final int timeoutMs;
final int durationSec;
final int packetSize;
final String dnsName;
final String payloadHex;
final String expectHex;
ProbeProfile get profile => ProbeProfile.byId(profileId);
RemoteNode? get node {
for (final item in nodes) {
if (item.id == nodeId) {
return item;
}
}
return null;
}
String? validate() {
if (host.trim().isEmpty) {
return '请填写目标地址';
}
if (port < 1 || port > 65535) {
return '端口需要在 1 到 65535 之间';
}
final minInterval = remote ? 200 : 100;
if (intervalMs < minInterval || intervalMs > 30000) {
return remote
? '远程节点的发送间隔需要在 200 到 30000 毫秒之间'
: '发送间隔需要在 100 到 30000 毫秒之间';
}
if (timeoutMs < 100 || timeoutMs > 15000) {
return '超时需要在 100 到 15000 毫秒之间';
}
if (remote && (durationSec < 1 || durationSec > 300)) {
return '远程探测时长需要在 1 到 300 秒之间,节点还会再加自己的上限';
}
if (profile.needsPacketSize &&
(packetSize < ProbePacket.headerSize || packetSize > 1400)) {
if (profileId == 'udp-generic' && (packetSize < 1 || packetSize > 1400)) {
return '报文大小需要在 1 到 1400 字节之间';
}
if (profileId != 'udp-generic') {
return '报文大小需要在 ${ProbePacket.headerSize} 到 1400 字节之间';
}
}
if (profileId == 'dns' && dnsName.trim().isEmpty) {
return '请填写要查询的域名';
}
if (profileId == 'custom-udp') {
final payload = _hexError(payloadHex, allowEmpty: false);
if (payload != null) {
return '自定义载荷$payload';
}
final expect = _hexError(expectHex, allowEmpty: true);
if (expect != null) {
return '预期响应$expect';
}
}
if (remote) {
final selected = node;
if (selected == null) {
return '请先添加并选择一个远程节点';
}
if (normalizeNodeUrl(selected.baseUrl) == null) {
return '节点地址需要是 http 或 https,且不能把口令写在地址里';
}
}
return null;
}
Map<String, Object?> toJson() => {
'remote': remote,
'nodeId': nodeId,
'nodes': nodes.map((node) => node.toJson()).toList(),
'host': host,
'port': port,
'profileId': profileId,
'intervalMs': intervalMs,
'timeoutMs': timeoutMs,
'durationSec': durationSec,
'packetSize': packetSize,
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
};
factory SessionConfig.fromJson(Map<String, dynamic> json) {
final rawNodes = json['nodes'];
final nodes = <RemoteNode>[];
if (rawNodes is List) {
for (final item in rawNodes) {
if (item is Map) {
nodes.add(RemoteNode.fromJson(Map<String, dynamic>.from(item)));
}
}
}
return SessionConfig(
remote: json['remote'] == true,
nodeId: json['nodeId'] is String ? json['nodeId'] as String : '',
nodes: nodes,
host: json['host'] is String ? json['host'] as String : defaults.host,
port: _asInt(json['port'], defaults.port),
profileId: json['profileId'] is String
? json['profileId'] as String
: defaults.profileId,
intervalMs: _asInt(json['intervalMs'], defaults.intervalMs),
timeoutMs: _asInt(json['timeoutMs'], defaults.timeoutMs),
durationSec: _asInt(json['durationSec'], defaults.durationSec),
packetSize: _asInt(json['packetSize'], defaults.packetSize),
dnsName: json['dnsName'] is String
? json['dnsName'] as String
: defaults.dnsName,
payloadHex: json['payloadHex'] is String ? json['payloadHex'] as String : '',
expectHex: json['expectHex'] is String ? json['expectHex'] as String : '',
);
}
static int _asInt(Object? value, int fallback) {
if (value is int) {
return value;
}
if (value is num) {
return value.toInt();
}
if (value is String) {
return int.tryParse(value) ?? fallback;
}
return fallback;
}
}
String? _hexError(String raw, {required bool allowEmpty}) {
final text = raw.replaceAll(RegExp(r'\s'), '');
if (text.isEmpty) {
return allowEmpty ? null : '需要是十六进制';
}
if (text.length.isOdd || !RegExp(r'^[0-9a-fA-F]+$').hasMatch(text)) {
return '需要是偶数位的十六进制';
}
if (text.length > 2800) {
return '太长了';
}
return null;
}
/// Accepts an operator control URL and refuses credentials embedded in it.
String? normalizeNodeUrl(String input) {
final trimmed = input.trim();
final uri = Uri.tryParse(trimmed);
if (uri == null || !uri.hasScheme || uri.host.isEmpty) {
return null;
}
if (uri.scheme != 'http' && uri.scheme != 'https') {
return null;
}
if (uri.userInfo.isNotEmpty) {
return null;
}
final port = uri.hasPort ? ':${uri.port}' : '';
final path = uri.path.isEmpty || uri.path == '/' ? '' : uri.path;
return '${uri.scheme}://${uri.host}$port$path';
}
bool nodeUrlLooksPublic(String url) {
final uri = Uri.tryParse(url);
if (uri == null) {
return false;
}
final host = uri.host.toLowerCase();
return host != 'localhost' &&
host != '127.0.0.1' &&
host != '::1' &&
uri.scheme == 'http';
}
/// Legacy v1 settings stored the echo token beside the host. Migrate the
/// non-secret fields and return the token so the caller can move it out.
({SessionConfig config, String echoToken}) migrateV1(String raw) {
final json = jsonDecode(raw);
if (json is! Map) {
return (config: SessionConfig.defaults, echoToken: '');
}
final map = Map<String, dynamic>.from(json);
final token = map['token'] is String ? map['token'] as String : '';
final tcp = SessionConfig._asInt(map['tcpPort'], 19090);
final udp = SessionConfig._asInt(map['udpPort'], 19091);
final enableTcp = map['enableTcp'] != false;
return (
config: SessionConfig(
remote: false,
nodeId: '',
nodes: const [],
host: map['host'] is String ? map['host'] as String : '127.0.0.1',
port: enableTcp ? tcp : udp,
profileId: enableTcp ? 'nq-tcp' : 'nq-udp',
intervalMs: SessionConfig._asInt(map['intervalMs'], 300),
timeoutMs: SessionConfig._asInt(map['timeoutMs'], 1000),
durationSec: 60,
packetSize: SessionConfig._asInt(map['packetSize'], 128),
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
),
echoToken: token,
);
}
+76
View File
@@ -0,0 +1,76 @@
import 'dart:io';
/// How many misses a working address may have before another address is tried.
const stickyMissThreshold = 3;
const clashFakeIpNote = '这是 VPN 的假地址,只有这个 VPN 开着时才能用';
/// Clash and similar VPNs hand out addresses in 198.18.0.0/15.
bool isClashFakeIp(InternetAddress address) {
final raw = address.rawAddress;
if (raw.length != 4) {
return false;
}
return raw[0] == 198 && (raw[1] == 18 || raw[1] == 19);
}
/// Picks which resolved address to send to.
///
/// Before any address has answered, one miss is enough to try the next.
/// After an address has answered, it is kept until [stickyMissThreshold]
/// misses in a row. The list is the one resolved at the start of the run;
/// nothing here looks the name up again.
class EndpointPicker {
EndpointPicker(this.candidates, {this.stickyMisses = stickyMissThreshold}) {
if (candidates.isEmpty) {
throw ArgumentError.value(candidates, 'candidates', 'empty');
}
}
final List<InternetAddress> candidates;
final int stickyMisses;
var _index = 0;
var _misses = 0;
var _locked = false;
InternetAddress get current => candidates[_index];
bool get hasAnswered => _locked;
/// Records one finished attempt. Returns true when [current] changed.
bool record(bool gotResponse) {
if (gotResponse) {
_locked = true;
_misses = 0;
return false;
}
_misses += 1;
final limit = _locked ? stickyMisses : 1;
if (candidates.length < 2 || _misses < limit) {
return false;
}
_misses = 0;
_locked = false;
_index = (_index + 1) % candidates.length;
return true;
}
}
Future<List<InternetAddress>> lookupAll(String host) async {
final parsed = InternetAddress.tryParse(host.trim());
if (parsed != null) {
return [parsed];
}
final found = await InternetAddress.lookup(host.trim());
if (found.isEmpty) {
throw const SocketException('Failed host lookup');
}
final seen = <String>{};
final unique = <InternetAddress>[];
for (final address in found) {
if (seen.add('${address.type.name} ${address.address}')) {
unique.add(address);
}
}
return unique;
}
+243
View File
@@ -0,0 +1,243 @@
import 'dart:convert';
import 'dart:typed_data';
const rakMagic = <int>[
0x00,
0xff,
0xff,
0x00,
0xfe,
0xfe,
0xfe,
0xfe,
0xfd,
0xfd,
0xfd,
0xfd,
0x12,
0x34,
0x56,
0x78,
];
Uint8List encodeVarInt(int value) {
final out = <int>[];
var u = value;
while (true) {
if ((u & ~0x7f) == 0) {
out.add(u);
return Uint8List.fromList(out);
}
out.add((u & 0x7f) | 0x80);
u >>= 7;
}
}
int? decodeVarInt(Uint8List bytes, int offset, void Function(int next) onNext) {
var n = 0;
for (var i = 0; i < 5; i++) {
if (offset + i >= bytes.length) {
return null;
}
final by = bytes[offset + i];
n |= (by & 0x7f) << (7 * i);
if ((by & 0x80) == 0) {
onNext(offset + i + 1);
return n;
}
}
throw const FormatException('varint');
}
Uint8List mcString(String value) {
final raw = utf8.encode(value);
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(raw.length));
out.add(raw);
return out.toBytes();
}
Uint8List mcPacket(List<int> payload) {
final out = BytesBuilder(copy: false);
out.add(encodeVarInt(payload.length));
out.add(payload);
return out.toBytes();
}
/// Handshake for status state. Protocol 767 is Minecraft 1.21.x.
Uint8List javaHandshake(String host, int port) {
final payload = BytesBuilder(copy: false);
payload.addByte(0x00);
payload.add(encodeVarInt(767));
payload.add(mcString(host));
final data = ByteData(2)..setUint16(0, port);
payload.add(data.buffer.asUint8List());
payload.add(encodeVarInt(1));
return mcPacket(payload.toBytes());
}
Uint8List javaStatusRequest() => mcPacket(const [0x00]);
Uint8List javaPing(int nonce) {
final data = ByteData(9);
data.setUint8(0, 0x01);
data.setUint64(1, nonce);
return mcPacket(data.buffer.asUint8List());
}
/// Returns the payload of one length-prefixed packet, and how many bytes it used.
({Uint8List payload, int used})? takeMcPacket(Uint8List bytes) {
var offset = 0;
final length = decodeVarInt(bytes, 0, (next) => offset = next);
if (length == null || length < 1 || length > 1 << 20) {
return null;
}
if (bytes.length < offset + length) {
return null;
}
return (
payload: Uint8List.sublistView(bytes, offset, offset + length),
used: offset + length,
);
}
Map<String, String> minecraftStatusDetail(String raw) {
final decoded = jsonDecode(raw);
if (decoded is! Map) {
return const {};
}
final out = <String, String>{};
final version = decoded['version'];
if (version is Map && version['name'] is String) {
out['version'] = version['name'] as String;
}
final players = decoded['players'];
if (players is Map) {
final online = players['online'];
final max = players['max'];
if (online is num && max is num) {
out['players'] = '${online.toInt()}/${max.toInt()}';
}
}
final description = decoded['description'];
final text = motdText(description);
if (text.isNotEmpty) {
out['motd'] = text;
}
return out;
}
String motdText(Object? value) {
if (value is String) {
return value;
}
if (value is Map) {
final buf = StringBuffer();
if (value['text'] is String) {
buf.write(value['text']);
}
final extra = value['extra'];
if (extra is List) {
for (final item in extra) {
buf.write(motdText(item));
}
}
return buf.toString();
}
return '';
}
String? readMcString(Uint8List payload, int offset) {
var next = offset;
final length = decodeVarInt(payload, offset, (value) => next = value);
if (length == null || length < 0 || next + length > payload.length) {
return null;
}
return utf8.decode(payload.sublist(next, next + length), allowMalformed: true);
}
Uint8List bedrockPing(int timestamp, int guid) {
final data = ByteData(1 + 8 + 16 + 8);
data.setUint8(0, 0x01);
data.setUint64(1, timestamp);
final bytes = data.buffer.asUint8List();
bytes.setRange(9, 25, rakMagic);
data.setUint64(25, guid);
return bytes;
}
Map<String, String>? parseRakPong(Uint8List packet, int timestamp) {
if (packet.length < 35 || packet[0] != 0x1c) {
return null;
}
final data = ByteData.sublistView(packet);
if (data.getUint64(1) != timestamp) {
return null;
}
for (var i = 0; i < rakMagic.length; i++) {
if (packet[17 + i] != rakMagic[i]) {
return null;
}
}
final strlen = data.getUint16(33);
if (35 + strlen > packet.length) {
return null;
}
final text = utf8.decode(packet.sublist(35, 35 + strlen), allowMalformed: true);
final parts = text.split(';');
final detail = <String, String>{};
if (parts.length > 1) {
detail['motd'] = parts[1];
}
if (parts.length > 3) {
detail['version'] = parts[3];
}
if (parts.length > 5) {
detail['players'] = '${parts[4]}/${parts[5]}';
}
return detail;
}
Uint8List dnsQuery(int id, String name) {
final body = BytesBuilder(copy: false);
for (final label in name.split('.')) {
if (label.isEmpty) {
continue;
}
final raw = utf8.encode(label);
if (raw.length > 63) {
throw const FormatException('label');
}
body.addByte(raw.length);
body.add(raw);
}
body.add(const [0, 0, 1, 0, 1]);
final question = body.toBytes();
final msg = Uint8List(12 + question.length);
final data = ByteData.sublistView(msg);
data.setUint16(0, id);
data.setUint16(2, 0x0100);
data.setUint16(4, 1);
msg.setRange(12, msg.length, question);
return msg;
}
bool dnsResponseMatches(Uint8List packet, int id) {
if (packet.length < 12) {
return false;
}
final data = ByteData.sublistView(packet);
return data.getUint16(0) == id && (packet[2] & 0x80) != 0;
}
Uint8List decodeHex(String raw) {
final text = raw.replaceAll(RegExp(r'\s'), '');
if (text.isEmpty || text.length.isOdd) {
throw const FormatException('hex');
}
final out = Uint8List(text.length ~/ 2);
for (var i = 0; i < out.length; i++) {
out[i] = int.parse(text.substring(i * 2, i * 2 + 2), radix: 16);
}
return out;
}
+288
View File
@@ -0,0 +1,288 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../metrics/sample_book.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import 'endpoint_picker.dart';
import 'probe_loop.dart';
import 'remote_client.dart';
class ChartSample {
const ChartSample({required this.sec, required this.rttMs, required this.ratePct});
final double sec;
final double? rttMs;
final double? ratePct;
}
class ProbeView {
const ProbeView({
required this.running,
required this.phase,
required this.banner,
required this.note,
required this.detail,
required this.summary,
required this.samples,
required this.rateLabel,
required this.sourceLabel,
this.targetAddress,
this.targetIsFake = false,
});
static const initial = ProbeView(
running: false,
phase: '未开始',
banner: null,
note: '',
detail: {},
summary: ProbeSummary.empty,
samples: [],
rateLabel: '探测无应答',
sourceLabel: '本机',
);
final bool running;
final String phase;
final String? banner;
final String note;
final Map<String, String> detail;
final ProbeSummary summary;
final List<ChartSample> samples;
final String rateLabel;
final String sourceLabel;
final String? targetAddress;
final bool targetIsFake;
ProbeView copyWith({
bool? running,
String? phase,
String? banner,
bool clearBanner = false,
String? note,
Map<String, String>? detail,
ProbeSummary? summary,
List<ChartSample>? samples,
String? rateLabel,
String? sourceLabel,
String? targetAddress,
bool? targetIsFake,
}) {
return ProbeView(
running: running ?? this.running,
phase: phase ?? this.phase,
banner: clearBanner ? null : banner ?? this.banner,
note: note ?? this.note,
detail: detail ?? this.detail,
summary: summary ?? this.summary,
samples: samples ?? this.samples,
rateLabel: rateLabel ?? this.rateLabel,
sourceLabel: sourceLabel ?? this.sourceLabel,
targetAddress: targetAddress ?? this.targetAddress,
targetIsFake: targetIsFake ?? this.targetIsFake,
);
}
}
class ProbeController extends ChangeNotifier {
ProbeView view = ProbeView.initial;
final Stopwatch _clock = Stopwatch();
ProbeLoop? _local;
RemoteProbe? _remote;
String _nodeToken = '';
var _token = 0;
Future<void> start(SessionConfig config, {required String nodeToken, required String echoToken}) async {
final problem = config.validate();
if (problem != null) {
view = view.copyWith(banner: problem, phase: '无法开始');
notifyListeners();
return;
}
final echoProblem = _echoProblem(config.profileId, echoToken);
if (echoProblem != null) {
view = view.copyWith(banner: echoProblem, phase: '无法开始');
notifyListeners();
return;
}
await stop();
_nodeToken = nodeToken;
final generation = ++_token;
_clock
..reset()
..start();
final source = config.remote ? (config.node?.name ?? '远程节点') : '本机';
view = ProbeView(
running: true,
phase: '探测中',
banner: null,
note: config.remote ? '正在让节点向目标发包' : '正在从本机向目标发包',
detail: const {},
summary: ProbeSummary.empty,
samples: const [],
rateLabel: rateLabelFor(config.profileId),
sourceLabel: source,
);
notifyListeners();
bool cancelled() => generation != _token;
try {
if (config.remote) {
final remote = RemoteProbe();
_remote = remote;
await remote.run(
baseUrl: config.node!.baseUrl,
nodeToken: nodeToken,
body: ProbeBody(
target: config.host.trim(),
port: config.port,
profile: config.profileId,
intervalMs: config.intervalMs,
timeoutMs: config.timeoutMs,
durationSec: config.durationSec,
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
} else {
final loop = ProbeLoop(
onEndpoint: (address) {
if (generation != _token) {
return;
}
view = view.copyWith(
targetAddress: address.address,
targetIsFake: isClashFakeIp(address),
);
notifyListeners();
},
);
_local = loop;
await loop.run(
request: ProbeRequest(
host: config.host.trim(),
port: config.port,
profileId: config.profileId,
interval: Duration(milliseconds: config.intervalMs),
timeout: Duration(milliseconds: config.timeoutMs),
packetSize: config.packetSize,
echoToken: echoToken,
dnsName: config.dnsName.trim(),
payloadHex: config.payloadHex.trim(),
expectHex: config.expectHex.trim(),
),
onSample: (sample) => _accept(generation, sample),
cancelled: cancelled,
);
}
if (generation == _token) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners();
}
} on RemoteException catch (error) {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: error.message);
notifyListeners();
}
} on Object {
if (generation == _token) {
view = view.copyWith(running: false, phase: '出错', banner: '探测中断');
notifyListeners();
}
} finally {
if (generation == _token) {
_local = null;
_remote = null;
}
}
}
Future<void> stop() async {
_token += 1;
final local = _local;
final remote = _remote;
_local = null;
_remote = null;
if (local != null) {
await local.close();
}
if (remote != null) {
await remote.stop(_nodeToken);
_nodeToken = '';
}
if (view.running) {
view = view.copyWith(running: false, phase: '已停止');
notifyListeners();
}
}
void _accept(int generation, ProbeSample sample) {
if (generation != _token) {
return;
}
final samples = [...view.samples];
if (samples.length >= 180) {
samples.removeAt(0);
}
final double? rate;
switch (view.rateLabel) {
case '探测无应答':
rate = sample.summary.probeLossPct;
case '失败率':
rate = sample.summary.failurePct;
default:
rate = sample.summary.unknownPct;
}
samples.add(
ChartSample(
sec: _clock.elapsedMilliseconds / 1000,
rttMs: sample.status == Outcome.ok ? sample.rttMs : null,
ratePct: rate,
),
);
view = view.copyWith(
phase: phaseFor(sample.status),
note: sample.note,
detail: sample.detail.isEmpty ? sample.summary.detail : sample.detail,
summary: sample.summary,
samples: samples,
clearBanner: true,
);
notifyListeners();
}
}
String? _echoProblem(String profileId, String echoToken) {
if (profileId != 'nq-tcp' && profileId != 'nq-udp') {
return null;
}
if (echoToken.length > 32) {
return '目标回显口令最长 32 字节';
}
return null;
}
String phaseFor(String status) {
switch (status) {
case Outcome.ok:
return '有应答';
case Outcome.timeout:
return '超时';
case Outcome.unknown:
return '无应答';
case Outcome.refused:
return '被拒绝';
case Outcome.dns:
return '域名失败';
case Outcome.protocol:
return '协议不符';
default:
return '出错';
}
}
+841
View File
@@ -0,0 +1,841 @@
import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import '../metrics/sample_book.dart';
import '../protocol/probe_packet.dart';
import 'endpoint_picker.dart';
import 'game_codec.dart';
class ProbeRequest {
const ProbeRequest({
required this.host,
required this.port,
required this.profileId,
required this.interval,
required this.timeout,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String host;
final int port;
final String profileId;
final Duration interval;
final Duration timeout;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
}
/// Sends one probe at a time from this device. A cancelled attempt is not
/// recorded, so stopping cannot paint a fake loss sample.
class ProbeLoop {
ProbeLoop({
this.lookup,
this.onEndpoint,
});
/// Replaces [lookupAll] in tests.
final Future<List<InternetAddress>> Function(String host)? lookup;
/// Fires when the address about to be used is chosen or changed.
final void Function(InternetAddress address)? onEndpoint;
_TcpPipe? _tcp;
_UdpPipe? _udp;
EndpointPicker? _picker;
InternetAddress? _announced;
int _seq = 0;
int _dnsId = 1;
final int _guid = DateTime.now().microsecondsSinceEpoch;
Future<void> run({
required ProbeRequest request,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final book = SampleBook(request.profileId);
try {
while (!cancelled()) {
final started = DateTime.now();
final outcome = await _once(request, cancelled);
if (cancelled() || outcome == null) {
break;
}
if (_usesDatagram(request.profileId)) {
final responded = outcome.status == Outcome.ok ||
outcome.status == Outcome.protocol ||
outcome.status == Outcome.refused;
if (_picker != null && _picker!.record(responded)) {
await _dropUdp();
_announce(_picker!.current);
}
}
book.add(outcome);
onSample(book.sample(book.sent, outcome));
final spent = DateTime.now().difference(started);
final rest = request.interval - spent;
if (!cancelled() && rest > Duration.zero) {
await Future<void>.delayed(rest);
}
}
} finally {
await close();
}
}
Future<void> close() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
Future<Outcome?> _once(ProbeRequest request, bool Function() cancelled) async {
try {
final outcome = await _dispatch(request, cancelled);
final peer = _udp?.peer;
if (peer != null && _usesDatagram(request.profileId)) {
return _stampAddress(outcome, peer);
}
return outcome;
} on SocketException catch (error) {
if (cancelled()) {
return null;
}
return classifySocket(error);
} on TimeoutException {
if (cancelled()) {
return null;
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
note: '连接超时',
);
}
}
Future<Outcome> _dispatch(ProbeRequest request, bool Function() cancelled) {
switch (request.profileId) {
case 'nq-tcp':
return _nqTcp(request, cancelled);
case 'nq-udp':
return _nqUdp(request, cancelled);
case 'tcp-connect':
return _tcpConnect(request, cancelled);
case 'udp-generic':
case 'custom-udp':
return _udpQuery(request, cancelled);
case 'dns':
return _dns(request, cancelled);
case 'minecraft-java':
return _java(request, cancelled);
case 'minecraft-bedrock':
return _bedrock(request, cancelled);
default:
return Future.value(
const Outcome(
status: Outcome.error,
kind: Outcome.query,
note: '不支持的探测类型',
),
);
}
}
Future<Outcome> _tcpConnect(
ProbeRequest request,
bool Function() cancelled,
) async {
final watch = Stopwatch()..start();
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
watch.stop();
await socket.close();
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
return Outcome(
status: Outcome.ok,
kind: Outcome.connect,
rttMs: watch.elapsedMicroseconds / 1000,
note: 'TCP 已连通',
);
}
Future<Outcome> _nqTcp(ProbeRequest request, bool Function() cancelled) async {
if (_tcp == null) {
try {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
socket.setOption(SocketOption.tcpNoDelay, true);
_tcp = _TcpPipe(socket);
} on SocketException catch (error) {
return classifySocket(error, reconnect: true);
} on TimeoutException {
return const Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: true,
note: '连接超时,将重试',
);
}
}
final pipe = _tcp!;
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
pipe.socket.add(packet.encode());
try {
await pipe.socket.flush();
} on SocketException {
await _dropTcp();
return const Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: true,
note: '发送失败,连接将重连',
);
}
final watch = Stopwatch()..start();
final matched = await pipe.waitMatch(request.timeout, (frame) {
try {
final reply = ProbePacket.decode(frame);
return reply.isReply && reply.sequence == seq;
} on ProbePacketException {
return false;
}
});
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
if (matched == null) {
await _dropTcp();
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '已发出探测,超时前没有收到回显。TCP 会重传,这不是已证实的物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<void> _dropTcp() async {
final tcp = _tcp;
_tcp = null;
if (tcp != null) {
await tcp.close();
}
}
Future<Outcome> _nqUdp(ProbeRequest request, bool Function() cancelled) async {
final pipe = await _datagram(request);
_seq += 1;
final seq = _seq;
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: seq,
clientSendUnixNano: DateTime.now().microsecondsSinceEpoch * 1000,
token: ProbePacket.encodeToken(request.echoToken),
payload: Uint8List(request.packetSize - ProbePacket.headerSize),
);
final watch = Stopwatch()..start();
pipe.send(packet.encode(), request.port);
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
try {
final parsed = ProbePacket.decode(data);
if (!parsed.isReply) {
sawInvalid = true;
return false;
}
return parsed.sequence == seq;
} on ProbePacketException {
sawInvalid = true;
return false;
}
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.probe,
note: '收到的 UDP 包不是有效回显',
);
}
return const Outcome(
status: Outcome.timeout,
kind: Outcome.probe,
note: '未收到回显。这是探测没有应答,不是网卡上的物理丢包计数',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.probe,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到回显',
);
}
Future<Outcome> _udpQuery(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
late final Uint8List payload;
Uint8List? expect;
if (request.profileId == 'udp-generic') {
payload = Uint8List(request.packetSize.clamp(1, 1400));
} else {
payload = decodeHex(request.payloadHex);
if (request.expectHex.trim().isNotEmpty) {
expect = decodeHex(request.expectHex);
}
}
final watch = Stopwatch()..start();
pipe.send(payload, request.port);
final reply = await pipe.waitMatch(request.timeout, (_) => true);
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 UDP 应答,不能据此断定物理丢包',
);
}
final wanted = expect;
if (wanted != null && (reply.length < wanted.length || !_prefix(reply, wanted))) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到了数据,但和预期的响应不一致',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 UDP 响应',
);
}
Future<Outcome> _dns(ProbeRequest request, bool Function() cancelled) async {
final pipe = await _datagram(request);
_dnsId = _dnsId == 65535 ? 1 : _dnsId + 1;
final id = _dnsId;
final name = request.dnsName.trim().isEmpty ? 'example.com' : request.dnsName.trim();
final watch = Stopwatch()..start();
pipe.send(dnsQuery(id, name), request.port);
var malformed = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
if (data.length < 12) {
malformed = true;
return false;
}
final got = ByteData.sublistView(data).getUint16(0);
if (got != id) {
return false;
}
if ((data[2] & 0x80) == 0) {
malformed = true;
return false;
}
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (malformed) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是 DNS 应答',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '没有收到 DNS 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 DNS 应答',
);
}
Future<Outcome> _bedrock(
ProbeRequest request,
bool Function() cancelled,
) async {
final pipe = await _datagram(request);
final timestamp = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
pipe.send(bedrockPing(timestamp, _guid), request.port);
Map<String, String>? detail;
var sawInvalid = false;
final reply = await pipe.waitMatch(request.timeout, (data) {
final parsed = parseRakPong(data, timestamp);
if (parsed == null) {
sawInvalid = true;
return false;
}
detail = parsed;
return true;
});
if (cancelled()) {
return const Outcome(status: Outcome.unknown, kind: Outcome.query, note: '已停止');
}
if (reply == null) {
if (sawInvalid) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '收到的包不是有效的 RakNet Pong',
);
}
return const Outcome(
status: Outcome.unknown,
kind: Outcome.query,
note: '未收到 RakNet 应答,不能据此断定物理丢包',
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Bedrock 应答',
detail: detail ?? const {},
);
}
Future<Outcome> _java(ProbeRequest request, bool Function() cancelled) async {
final socket = await Socket.connect(
request.host,
request.port,
timeout: request.timeout,
);
final reader = _BytePipe(socket);
try {
socket.add(javaHandshake(request.host, request.port));
socket.add(javaStatusRequest());
await socket.flush();
final status = await reader.nextPacket(request.timeout);
if (status == null || status.isEmpty || status[0] != 0x00) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态响应无效',
);
}
final jsonText = readMcString(status, 1);
if (jsonText == null) {
return const Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft 状态内容无法解析',
);
}
final detail = minecraftStatusDetail(jsonText);
final nonce = DateTime.now().microsecondsSinceEpoch;
final watch = Stopwatch()..start();
socket.add(javaPing(nonce));
await socket.flush();
final pong = await reader.nextPacket(request.timeout);
if (cancelled()) {
return const Outcome(status: Outcome.timeout, kind: Outcome.connect, note: '已停止');
}
if (pong == null || pong.length != 9 || pong[0] != 0x01) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: '没有收到有效的 Minecraft pong',
detail: detail,
);
}
if (ByteData.sublistView(pong).getUint64(1) != nonce) {
return Outcome(
status: Outcome.protocol,
kind: Outcome.query,
note: 'Minecraft pong 的时间戳不匹配',
detail: detail,
);
}
return Outcome(
status: Outcome.ok,
kind: Outcome.query,
rttMs: watch.elapsedMicroseconds / 1000,
note: '收到 Minecraft 状态和 ping 应答',
detail: detail,
);
} finally {
await reader.close();
await socket.close();
}
}
Future<_UdpPipe> _datagram(ProbeRequest request) async {
_picker ??= EndpointPicker(await (lookup ?? lookupAll)(request.host));
final want = _picker!.current;
final existing = _udp;
if (existing != null && existing.peer.address == want.address) {
return existing;
}
if (existing != null) {
await existing.close();
_udp = null;
}
final socket = await RawDatagramSocket.bind(
want.type == InternetAddressType.IPv6
? InternetAddress.anyIPv6
: InternetAddress.anyIPv4,
0,
);
final pipe = _UdpPipe(socket, want);
_udp = pipe;
_announce(want);
return pipe;
}
void _announce(InternetAddress address) {
if (_announced != null && _announced!.address == address.address) {
return;
}
_announced = address;
onEndpoint?.call(address);
}
Future<void> _dropUdp() async {
final udp = _udp;
_udp = null;
if (udp != null) {
await udp.close();
}
}
}
bool _usesDatagram(String profileId) {
switch (profileId) {
case 'nq-udp':
case 'udp-generic':
case 'custom-udp':
case 'dns':
case 'minecraft-bedrock':
return true;
default:
return false;
}
}
Outcome _stampAddress(Outcome outcome, InternetAddress peer) {
return Outcome(
status: outcome.status,
kind: outcome.kind,
rttMs: outcome.rttMs,
note: outcome.note,
reconnect: outcome.reconnect,
detail: {...outcome.detail, 'address': peer.address},
);
}
Outcome classifySocket(SocketException error, {bool reconnect = false}) {
final text = '${error.message} ${error.osError?.message ?? ''}'.toLowerCase();
final code = error.osError?.errorCode;
if (text.contains('timed out') || text.contains('timeout')) {
return Outcome(
status: Outcome.timeout,
kind: Outcome.connect,
reconnect: reconnect,
note: reconnect ? '连接超时,将重试' : '连接超时',
);
}
if (text.contains('failed host lookup') ||
text.contains('name or service not known') ||
text.contains('nodename nor servname') ||
text.contains('no address associated')) {
return const Outcome(
status: Outcome.dns,
kind: Outcome.connect,
note: '域名无法解析',
);
}
if (code == 111 ||
code == 61 ||
code == 10061 ||
text.contains('connection refused') ||
text.contains('actively refused')) {
return Outcome(
status: Outcome.refused,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接被拒绝',
);
}
return Outcome(
status: Outcome.error,
kind: Outcome.connect,
reconnect: reconnect,
note: '连接失败',
);
}
bool _prefix(Uint8List data, Uint8List prefix) {
for (var i = 0; i < prefix.length; i++) {
if (data[i] != prefix[i]) {
return false;
}
}
return true;
}
class _TcpPipe {
_TcpPipe(this.socket) {
_sub = socket.listen(
(data) {
try {
_frames.addAll(_buffer.add(data));
} on ProbePacketException {
_failed = true;
}
_signal();
},
onError: (Object _) {
_failed = true;
_signal();
},
onDone: () {
_failed = true;
_signal();
},
cancelOnError: true,
);
}
final Socket socket;
final FrameBuffer _buffer = FrameBuffer();
final List<Uint8List> _frames = [];
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
bool _failed = false;
var _cursor = 0;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List frame) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _frames.length) {
final frame = _frames[_cursor];
_cursor += 1;
if (match(frame)) {
return frame;
}
}
if (_failed) {
return null;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _frames.length || _failed) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
await socket.close();
_signal();
}
}
class _UdpPipe {
_UdpPipe(this.socket, this.peer) {
_sub = socket.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
while (true) {
final datagram = socket.receive();
if (datagram == null) {
return;
}
_queue.add(Uint8List.fromList(datagram.data));
_signal();
}
});
}
final RawDatagramSocket socket;
final InternetAddress peer;
final List<Uint8List> _queue = [];
late final StreamSubscription<RawSocketEvent> _sub;
Completer<void>? _pending;
var _cursor = 0;
void send(List<int> bytes, int port) {
socket.send(bytes, peer, port);
}
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> waitMatch(
Duration timeout,
bool Function(Uint8List data) match,
) async {
final deadline = DateTime.now().add(timeout);
while (true) {
while (_cursor < _queue.length) {
final data = _queue[_cursor];
_cursor += 1;
if (match(data)) {
return data;
}
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (_cursor < _queue.length) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() async {
await _sub.cancel();
socket.close();
_signal();
}
}
class _BytePipe {
_BytePipe(this.socket) {
_sub = socket.listen((data) {
_buf.add(data);
_signal();
});
}
final Socket socket;
final BytesBuilder _buf = BytesBuilder(copy: false);
late final StreamSubscription<Uint8List> _sub;
Completer<void>? _pending;
void _signal() {
final pending = _pending;
_pending = null;
if (pending != null && !pending.isCompleted) {
pending.complete();
}
}
Future<Uint8List?> nextPacket(Duration timeout) async {
final deadline = DateTime.now().add(timeout);
while (true) {
final bytes = _buf.toBytes();
final packet = takeMcPacket(bytes);
if (packet != null) {
_buf.clear();
if (packet.used < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, packet.used));
}
return packet.payload;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (takeMcPacket(_buf.toBytes()) != null) {
_signal();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
if (identical(_pending, waiter)) {
_pending = null;
}
return null;
}
}
}
Future<void> close() => _sub.cancel();
}
+281
View File
@@ -0,0 +1,281 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import '../metrics/sample_book.dart';
import '../models/session_config.dart';
class RemoteProbe {
HttpClient? _client;
String? _jobId;
Uri? _base;
Future<void> run({
required String baseUrl,
required String nodeToken,
required ProbeBody body,
required void Function(ProbeSample sample) onSample,
required bool Function() cancelled,
}) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
_base = Uri.parse(normalized);
final client = HttpClient();
_client = client;
try {
final created = await _send(
client,
'POST',
_base!.resolve('/v1/jobs'),
nodeToken,
utf8.encode(jsonEncode(body.toJson())),
);
if (created.status >= 300 && created.status < 400) {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
}
if (created.status == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (created.status == 429) {
throw RemoteException('节点同时探测的任务已达上限');
}
if (created.status == 403 || created.status == 400) {
throw RemoteException(_message(created.body) ?? '节点拒绝了这次探测');
}
if (created.status != 201) {
throw RemoteException('节点没有接受探测(${created.status})');
}
final parsed = jsonDecode(created.body);
if (parsed is! Map || parsed['jobId'] is! String) {
throw RemoteException('节点返回的任务无效');
}
_jobId = parsed['jobId'] as String;
if (cancelled()) {
return;
}
await _stream(client, nodeToken, onSample, cancelled);
} on RemoteException {
rethrow;
} on SocketException {
if (!cancelled()) {
throw RemoteException('连不上节点。请检查地址、端口和防火墙');
}
} on HandshakeException {
throw RemoteException('TLS 握手失败。请检查证书,或改用正确的 HTTPS 地址');
} on RedirectException {
throw RemoteException('节点地址发生了跳转。请填写最终地址,不要在地址里带口令');
} on HttpException {
if (!cancelled()) {
throw RemoteException('节点连接中断');
}
} on TimeoutException {
if (!cancelled()) {
throw RemoteException('节点没有及时响应');
}
} finally {
await stop(nodeToken);
}
}
Future<void> stop(String nodeToken) async {
final client = _client;
final id = _jobId;
final base = _base;
_jobId = null;
if (client != null && id != null && base != null) {
try {
await _send(client, 'DELETE', base.resolve('/v1/jobs/$id'), nodeToken, const []);
} on Object {
// The stream ending already asks the node to drop the job.
}
}
client?.close(force: true);
_client = null;
}
Future<void> _stream(
HttpClient client,
String nodeToken,
void Function(ProbeSample sample) onSample,
bool Function() cancelled,
) async {
final request = await client.getUrl(_base!.resolve('/v1/jobs/$_jobId/stream'));
request.followRedirects = false;
_auth(request, nodeToken);
final response = await request.close().timeout(const Duration(seconds: 20));
if (response.statusCode == 401) {
throw RemoteException('节点口令不正确或未提供');
}
if (response.statusCode != 200) {
throw RemoteException('无法接收节点上的探测结果');
}
var buffer = '';
await for (final chunk in response.transform(utf8.decoder)) {
if (cancelled()) {
return;
}
buffer += chunk;
while (buffer.contains('\n\n')) {
final split = buffer.indexOf('\n\n');
final block = buffer.substring(0, split);
buffer = buffer.substring(split + 2);
final sample = _sampleFromBlock(block);
if (sample != null) {
onSample(sample);
}
}
}
}
}
class ProbeBody {
const ProbeBody({
required this.target,
required this.port,
required this.profile,
required this.intervalMs,
required this.timeoutMs,
required this.durationSec,
required this.packetSize,
required this.echoToken,
required this.dnsName,
required this.payloadHex,
required this.expectHex,
});
final String target;
final int port;
final String profile;
final int intervalMs;
final int timeoutMs;
final int durationSec;
final int packetSize;
final String echoToken;
final String dnsName;
final String payloadHex;
final String expectHex;
Map<String, Object?> toJson() => {
'target': target,
'port': port,
'profile': profile,
'intervalMs': intervalMs,
'timeoutMs': timeoutMs,
'durationSec': durationSec,
'packetSize': packetSize,
'echoToken': echoToken,
'dnsName': dnsName,
'payloadHex': payloadHex,
'expectHex': expectHex,
};
}
class RemoteException implements Exception {
RemoteException(this.message);
final String message;
@override
String toString() => message;
}
class NodeInfo {
const NodeInfo({required this.visibility, required this.authRequired});
final String visibility;
final bool authRequired;
}
Future<NodeInfo> fetchNodeInfo(String baseUrl) async {
final normalized = normalizeNodeUrl(baseUrl);
if (normalized == null) {
throw RemoteException('节点地址需要是 http 或 https,且不能把口令写在地址里');
}
final client = HttpClient();
try {
final request = await client.getUrl(Uri.parse(normalized).resolve('/v1/info'));
request.followRedirects = false;
final response = await request.close().timeout(const Duration(seconds: 8));
final body = await response.transform(utf8.decoder).join();
if (response.statusCode != 200) {
throw RemoteException('读不到节点信息');
}
final json = jsonDecode(body);
if (json is! Map) {
throw RemoteException('节点信息无效');
}
return NodeInfo(
visibility: json['visibility'] is String ? json['visibility'] as String : '',
authRequired: json['authRequired'] == true,
);
} on RemoteException {
rethrow;
} on SocketException {
throw RemoteException('连不上节点');
} on HandshakeException {
throw RemoteException('TLS 握手失败');
} finally {
client.close(force: true);
}
}
Future<({int status, String body})> _send(
HttpClient client,
String method,
Uri uri,
String nodeToken,
List<int> bytes,
) async {
final request = await client.openUrl(method, uri);
request.followRedirects = false;
request.headers.contentType = ContentType.json;
_auth(request, nodeToken);
request.add(bytes);
final response = await request.close().timeout(const Duration(seconds: 15));
final body = await response.transform(utf8.decoder).join();
return (status: response.statusCode, body: body);
}
void _auth(HttpClientRequest request, String nodeToken) {
if (nodeToken.isNotEmpty) {
request.headers.set(HttpHeaders.authorizationHeader, 'Bearer $nodeToken');
}
}
String? _message(String body) {
try {
final json = jsonDecode(body);
if (json is Map && json['message'] is String) {
return json['message'] as String;
}
} on FormatException {
return null;
}
return null;
}
ProbeSample? _sampleFromBlock(String block) {
String? data;
for (final line in block.split('\n')) {
if (line.startsWith('data: ')) {
data = line.substring(6);
}
}
if (data == null || data == '{}') {
return null;
}
try {
final json = jsonDecode(data);
if (json is! Map) {
return null;
}
final sample = ProbeSample.fromJson(Map<String, dynamic>.from(json));
if (sample.status.isEmpty || sample.status == 'pending') {
return null;
}
return sample;
} on FormatException {
return null;
}
}
+165
View File
@@ -0,0 +1,165 @@
import 'dart:convert';
import 'dart:typed_data';
/// Wire format shared by TCP frames and UDP datagrams.
///
/// See docs/PROTOCOL.md. Header is 62 bytes, little-endian.
/// A TCP stream is a sequence of these frames. A UDP datagram is exactly one.
class ProbePacket {
ProbePacket({
required this.type,
required this.sequence,
required this.clientSendUnixNano,
this.serverUnixNano = 0,
Uint8List? token,
Uint8List? payload,
this.version = version1,
}) : token = token ?? Uint8List(tokenLength),
payload = payload ?? Uint8List(0);
static const version1 = 1;
static const headerSize = 62;
static const tokenLength = 32;
static const tokenOffset = 28;
static const maxPayload = 2048;
static const typeRequest = 1;
static const typeReply = 2;
static const magic0 = 0x4e; // N
static const magic1 = 0x51; // Q
static const magic2 = 0x30; // 0
static const magic3 = 0x31; // 1
final int version;
final int type;
final int sequence;
final int clientSendUnixNano;
final int serverUnixNano;
final Uint8List token;
final Uint8List payload;
bool get isReply => type == typeReply;
Uint8List encode() {
if (token.length != tokenLength) {
throw ProbePacketException('token must be $tokenLength bytes');
}
if (payload.length > maxPayload) {
throw ProbePacketException('payload too large');
}
final out = Uint8List(headerSize + payload.length);
final data = ByteData.sublistView(out);
out[0] = magic0;
out[1] = magic1;
out[2] = magic2;
out[3] = magic3;
data.setUint8(4, version);
data.setUint8(5, type);
data.setUint8(6, 0);
data.setUint8(7, 0);
data.setUint32(8, sequence, Endian.little);
data.setUint64(12, clientSendUnixNano, Endian.little);
data.setUint64(20, serverUnixNano, Endian.little);
out.setRange(tokenOffset, tokenOffset + tokenLength, token);
data.setUint16(60, payload.length, Endian.little);
out.setRange(headerSize, out.length, payload);
return out;
}
static ProbePacket decode(Uint8List bytes) {
if (bytes.length < headerSize) {
throw ProbePacketException('packet shorter than header');
}
if (bytes[0] != magic0 ||
bytes[1] != magic1 ||
bytes[2] != magic2 ||
bytes[3] != magic3) {
throw ProbePacketException('bad magic');
}
final data = ByteData.sublistView(bytes);
final version = data.getUint8(4);
if (version != version1) {
throw ProbePacketException('unsupported version $version');
}
final type = data.getUint8(5);
if (type != typeRequest && type != typeReply) {
throw ProbePacketException('unsupported type $type');
}
final payloadLen = data.getUint16(60, Endian.little);
if (payloadLen > maxPayload) {
throw ProbePacketException('payload too large');
}
final total = headerSize + payloadLen;
if (bytes.length != total) {
throw ProbePacketException(
'length mismatch: have ${bytes.length}, want $total',
);
}
return ProbePacket(
version: version,
type: type,
sequence: data.getUint32(8, Endian.little),
clientSendUnixNano: data.getUint64(12, Endian.little),
serverUnixNano: data.getUint64(20, Endian.little),
token: Uint8List.sublistView(bytes, tokenOffset, tokenOffset + tokenLength),
payload: payloadLen == 0
? Uint8List(0)
: Uint8List.sublistView(bytes, headerSize, total),
);
}
/// UTF-8 token padded with zeros. Empty string is 32 zero bytes.
static Uint8List encodeToken(String token) {
final raw = utf8.encode(token);
if (raw.length > tokenLength) {
throw ProbePacketException('口令最长 $tokenLength 字节');
}
final out = Uint8List(tokenLength);
out.setRange(0, raw.length, raw);
return out;
}
}
class ProbePacketException implements Exception {
ProbePacketException(this.message);
final String message;
@override
String toString() => message;
}
/// Reassembles TCP frames. UDP datagrams are already one frame and do not
/// need this buffer.
class FrameBuffer {
final BytesBuilder _buf = BytesBuilder(copy: false);
List<Uint8List> add(List<int> chunk) {
_buf.add(chunk);
final bytes = _buf.toBytes();
var offset = 0;
final frames = <Uint8List>[];
while (bytes.length - offset >= ProbePacket.headerSize) {
final view = ByteData.sublistView(bytes, offset);
final payloadLen = view.getUint16(60, Endian.little);
if (payloadLen > ProbePacket.maxPayload) {
_buf.clear();
throw ProbePacketException('payload too large');
}
final total = ProbePacket.headerSize + payloadLen;
if (bytes.length - offset < total) {
break;
}
frames.add(Uint8List.sublistView(bytes, offset, offset + total));
offset += total;
}
_buf.clear();
if (offset < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, offset));
}
return frames;
}
void clear() {
_buf.clear();
}
}
+59
View File
@@ -0,0 +1,59 @@
import 'dart:convert';
import 'dart:io';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../models/session_config.dart';
import 'token_vault.dart';
class AppStore {
static const _key = 'netquality.settings.v2';
static const _legacy = 'netquality.settings.v1';
Future<({SessionConfig config, String legacyEcho})> load() async {
final prefs = await SharedPreferences.getInstance();
final raw = prefs.getString(_key);
if (raw != null && raw.isNotEmpty) {
try {
final decoded = jsonDecode(raw);
if (decoded is Map) {
return (
config: SessionConfig.fromJson(Map<String, dynamic>.from(decoded)),
legacyEcho: '',
);
}
} on FormatException {
return (config: SessionConfig.defaults, legacyEcho: '');
}
}
final legacy = prefs.getString(_legacy);
if (legacy != null && legacy.isNotEmpty) {
try {
final migrated = migrateV1(legacy);
await save(migrated.config);
await prefs.remove(_legacy);
return (config: migrated.config, legacyEcho: migrated.echoToken);
} on FormatException {
return (config: SessionConfig.defaults, legacyEcho: '');
}
}
return (config: SessionConfig.defaults, legacyEcho: '');
}
Future<void> save(SessionConfig config) async {
final prefs = await SharedPreferences.getInstance();
await prefs.setString(_key, jsonEncode(config.toJson()));
}
}
Future<TokenVault> openTokenVault() async {
try {
final dir = await getApplicationSupportDirectory();
final vault = FileTokenVault(File('${dir.path}/node-tokens.json'));
await vault.load();
return vault;
} on Object {
return MemoryTokenVault();
}
}
+103
View File
@@ -0,0 +1,103 @@
import 'dart:convert';
import 'dart:io';
/// Stores node-control tokens and the target echo token outside preferences.
///
/// The file lives in the app's private support directory. On Unix it is
/// created with mode 0600. Tokens are never written into URLs or logs.
abstract class TokenVault {
Future<String?> read(String key);
Future<void> write(String key, String value);
Future<void> delete(String key);
}
class MemoryTokenVault implements TokenVault {
final Map<String, String> _values = {};
@override
Future<void> delete(String key) async {
_values.remove(key);
}
@override
Future<String?> read(String key) async => _values[key];
@override
Future<void> write(String key, String value) async {
if (value.isEmpty) {
_values.remove(key);
return;
}
_values[key] = value;
}
}
class FileTokenVault implements TokenVault {
FileTokenVault(this.file);
final File file;
final Map<String, String> _values = {};
bool _loaded = false;
Future<void> load() async {
if (_loaded) {
return;
}
_loaded = true;
if (!await file.exists()) {
return;
}
try {
final decoded = jsonDecode(await file.readAsString());
if (decoded is Map) {
decoded.forEach((key, value) {
if (key is String && value is String && value.isNotEmpty) {
_values[key] = value;
}
});
}
} on FormatException {
_values.clear();
}
}
@override
Future<void> delete(String key) async {
await load();
_values.remove(key);
await _flush();
}
@override
Future<String?> read(String key) async {
await load();
return _values[key];
}
@override
Future<void> write(String key, String value) async {
await load();
if (value.isEmpty) {
_values.remove(key);
} else {
_values[key] = value;
}
await _flush();
}
Future<void> _flush() async {
await file.parent.create(recursive: true);
await file.writeAsString(jsonEncode(_values), flush: true);
if (!Platform.isWindows) {
try {
await Process.run('chmod', ['600', file.path]);
} on ProcessException {
// The app directory is already private on Android.
}
}
}
}
const echoTokenKey = 'target-echo-token';
String nodeTokenKey(String nodeId) => 'node-token.$nodeId';
+76
View File
@@ -0,0 +1,76 @@
import '../metrics/sample_book.dart';
String formatMs(double? ms) {
if (ms == null) {
return '—';
}
if (ms < 1) {
return '${ms.toStringAsFixed(3)} ms';
}
if (ms < 10) {
return '${ms.toStringAsFixed(2)} ms';
}
if (ms < 100) {
return '${ms.toStringAsFixed(1)} ms';
}
return '${ms.toStringAsFixed(0)} ms';
}
String formatPct(double? pct) {
if (pct == null) {
return '—';
}
if (pct == 0) {
return '0%';
}
if (pct < 10) {
return '${pct.toStringAsFixed(1)}%';
}
return '${pct.toStringAsFixed(0)}%';
}
String visibilityLabel(String visibility) {
switch (visibility) {
case 'public':
return '公开';
case 'private':
return '需要口令';
default:
return '未检查';
}
}
String summaryLine(ProbeSummary summary) {
if (summary.completed == 0) {
return '还没有完成的探测';
}
final parts = <String>[
'完成 ${summary.completed}',
'成功 ${summary.ok}',
];
if (summary.timeout > 0) {
parts.add('超时 ${summary.timeout}');
}
if (summary.unknown > 0) {
parts.add('无应答 ${summary.unknown}');
}
if (summary.refused > 0) {
parts.add('拒绝 ${summary.refused}');
}
if (summary.dns > 0) {
parts.add('域名 ${summary.dns}');
}
if (summary.protocol > 0) {
parts.add('协议 ${summary.protocol}');
}
if (summary.other > 0) {
parts.add('其他失败 ${summary.other}');
}
if (summary.reconnects > 0) {
parts.add('重连 ${summary.reconnects}');
}
if (summary.consecutiveFailures > 0) {
parts.add('连续失败 ${summary.consecutiveFailures}');
}
return parts.join(' · ');
}
+631
View File
@@ -0,0 +1,631 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../models/probe_profile.dart';
import '../models/session_config.dart';
import '../probe/endpoint_picker.dart';
import '../probe/probe_controller.dart';
import '../probe/remote_client.dart';
import '../storage/app_store.dart';
import '../storage/token_vault.dart';
import 'format.dart';
import 'quality_charts.dart';
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final _controller = ProbeController();
final _store = AppStore();
TokenVault _vault = MemoryTokenVault();
final _host = TextEditingController(text: SessionConfig.defaults.host);
final _port = TextEditingController(text: '${SessionConfig.defaults.port}');
final _interval = TextEditingController(text: '300');
final _timeout = TextEditingController(text: '1000');
final _duration = TextEditingController(text: '60');
final _size = TextEditingController(text: '128');
final _echo = TextEditingController();
final _dns = TextEditingController(text: 'example.com');
final _payload = TextEditingController();
final _expect = TextEditingController();
var _remote = false;
var _profileId = ProbeProfile.nqTcp.id;
var _nodeId = '';
var _nodes = <RemoteNode>[];
var _ready = false;
@override
void initState() {
super.initState();
_controller.addListener(_rebuild);
_load();
}
Future<void> _load() async {
_vault = await openTokenVault();
final loaded = await _store.load();
final echo = await _vault.read(echoTokenKey);
if (!mounted) {
return;
}
final config = loaded.config;
setState(() {
_remote = config.remote;
_nodeId = config.nodeId;
_nodes = config.nodes;
_profileId = config.profileId;
_host.text = config.host;
_port.text = '${config.port}';
_interval.text = '${config.intervalMs}';
_timeout.text = '${config.timeoutMs}';
_duration.text = '${config.durationSec}';
_size.text = '${config.packetSize}';
_dns.text = config.dnsName;
_payload.text = config.payloadHex;
_expect.text = config.expectHex;
_echo.text = (echo == null || echo.isEmpty) ? loaded.legacyEcho : echo;
_ready = true;
});
if (loaded.legacyEcho.isNotEmpty && (echo == null || echo.isEmpty)) {
await _vault.write(echoTokenKey, loaded.legacyEcho);
}
}
void _rebuild() {
if (mounted) {
setState(() {});
}
}
@override
void dispose() {
unawaited(_controller.stop());
unawaited(_persist());
_controller.removeListener(_rebuild);
_controller.dispose();
for (final field in [
_host,
_port,
_interval,
_timeout,
_duration,
_size,
_echo,
_dns,
_payload,
_expect,
]) {
field.dispose();
}
super.dispose();
}
SessionConfig _config() {
return SessionConfig(
remote: _remote,
nodeId: _nodeId,
nodes: _nodes,
host: _host.text.trim(),
port: int.tryParse(_port.text.trim()) ?? 0,
profileId: _profileId,
intervalMs: int.tryParse(_interval.text.trim()) ?? 0,
timeoutMs: int.tryParse(_timeout.text.trim()) ?? 0,
durationSec: int.tryParse(_duration.text.trim()) ?? 0,
packetSize: int.tryParse(_size.text.trim()) ?? 0,
dnsName: _dns.text.trim(),
payloadHex: _payload.text.trim(),
expectHex: _expect.text.trim(),
);
}
Future<void> _persist() async {
await _store.save(_config());
await _vault.write(echoTokenKey, _echo.text);
}
Future<void> _start() async {
await _persist();
final config = _config();
final nodeToken = config.node == null
? ''
: (await _vault.read(nodeTokenKey(config.node!.id)) ?? '');
await _controller.start(config, nodeToken: nodeToken, echoToken: _echo.text);
}
void _changeProfile(String? id) {
if (id == null) {
return;
}
final previous = ProbeProfile.byId(_profileId);
final next = ProbeProfile.byId(id);
setState(() {
if (_port.text.trim() == '${previous.port}') {
_port.text = '${next.port}';
}
_profileId = id;
});
}
@override
Widget build(BuildContext context) {
final view = _controller.view;
final profile = ProbeProfile.byId(_profileId);
final wide = MediaQuery.sizeOf(context).width >= 720;
return Scaffold(
appBar: AppBar(
title: const Text('网络质量探测'),
backgroundColor: const Color(0xFFF3F1EC),
),
body: SafeArea(
child: Align(
alignment: Alignment.topCenter,
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 880),
child: ListView(
padding: EdgeInsets.fromLTRB(wide ? 24 : 12, 8, wide ? 24 : 12, 28),
children: [
_card(
title: '探测来源',
child: _source(view, wide),
),
_card(
title: '目标',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pair(
wide,
_field(_host, '目标地址', '域名或 IP'),
_field(_port, '端口', '1–65535'),
),
const SizedBox(height: 12),
DropdownButtonFormField<String>(
key: const Key('profile'),
initialValue: _profileId,
decoration: const InputDecoration(labelText: '探测类型'),
items: [
for (final item in ProbeProfile.all)
DropdownMenuItem(value: item.id, child: Text(item.label)),
],
onChanged: view.running ? null : _changeProfile,
),
const SizedBox(height: 8),
Text(profile.blurb, style: const TextStyle(color: muted, fontSize: 13)),
],
),
),
_card(
title: '参数',
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
_pair(
wide,
_field(_interval, '间隔(毫秒)', _remote ? '至少 200' : '至少 100'),
_field(_timeout, '超时(毫秒)', '100–15000'),
),
if (profile.needsPacketSize) ...[
const SizedBox(height: 12),
_field(_size, '报文大小(字节)', '最大 1400'),
],
if (_remote) ...[
const SizedBox(height: 12),
_field(_duration, '时长(秒)', '到点后节点会停止'),
],
if (profile.needsEchoToken) ...[
const SizedBox(height: 12),
_field(
_echo,
'目标回显口令',
'可选,只放进探测包,和节点口令不是同一个',
secret: true,
),
],
if (profile.id == 'dns') ...[
const SizedBox(height: 12),
_field(_dns, '查询域名', '例如 example.com'),
],
if (profile.id == 'custom-udp') ...[
const SizedBox(height: 12),
_field(_payload, '载荷(十六进制)', '例如 0102'),
const SizedBox(height: 12),
_field(_expect, '响应需以此开头(十六进制,可空)', '不填则任意响应都算成功'),
],
],
),
),
FilledButton(
onPressed: !_ready
? null
: view.running
? _controller.stop
: _start,
child: Text(view.running ? '停止探测' : '开始探测'),
),
if (view.banner != null) ...[
const SizedBox(height: 12),
_banner(view.banner!),
],
const SizedBox(height: 12),
_card(title: '结果', child: _result(view)),
QualityCharts(
samples: view.samples,
rateLabel: view.rateLabel,
running: view.running,
),
const Text(
'延迟用发包一侧的单调时钟计算。远程探测时,这个时间在节点上量好再传回来,不包含手机到节点的控制通道耗时。TCP 超时不是物理丢包。没有协议应答的 UDP 记为无应答/未知,不会在探测完成前显示 100%。',
style: TextStyle(color: muted, fontSize: 12, height: 1.4),
),
],
),
),
),
),
);
}
Widget _source(ProbeView view, bool wide) {
final selected = _nodes.cast<RemoteNode?>().followedBy(const [null]).firstWhere(
(node) => node?.id == _nodeId,
orElse: () => null,
);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SegmentedButton<bool>(
segments: const [
ButtonSegment(value: false, label: Text('本机'), icon: Icon(Icons.phone_android)),
ButtonSegment(value: true, label: Text('远程节点'), icon: Icon(Icons.dns_outlined)),
],
selected: {_remote},
onSelectionChanged: view.running
? null
: (value) => setState(() => _remote = value.first),
),
const SizedBox(height: 8),
Text(
_remote
? '由选中的节点向目标发包,这台设备只负责控制和显示。'
: '由这台设备直接向目标发包。可以探测本机上的反射器。',
style: const TextStyle(color: muted, fontSize: 13),
),
if (_remote) ...[
const SizedBox(height: 12),
_pair(
wide,
DropdownButtonFormField<String>(
key: const Key('node-selector'),
initialValue: selected == null ? '' : selected.id,
decoration: const InputDecoration(labelText: '节点'),
items: [
const DropdownMenuItem(value: '', child: Text('未选择')),
for (final node in _nodes)
DropdownMenuItem(
value: node.id,
child: Text(_nodeLabel(node)),
),
],
onChanged: view.running
? null
: (value) => setState(() => _nodeId = value ?? ''),
),
OutlinedButton(
onPressed: view.running ? null : _manageNodes,
child: const Text('管理节点'),
),
),
if (selected != null && nodeUrlLooksPublic(selected.baseUrl))
const Padding(
padding: EdgeInsets.only(top: 8),
child: Text(
'这个控制地址没有使用 HTTPS。口令会暴露在链路上,请改用 TLS 或 HTTPS 反向代理。',
style: TextStyle(color: Color(0xFF9A3412), fontSize: 12),
),
),
],
],
);
}
String _nodeLabel(RemoteNode node) {
final vis = visibilityLabel(node.visibility);
return '${node.name} · $vis';
}
Widget _result(ProbeView view) {
final summary = view.summary;
final rate = view.rateLabel == '探测无应答'
? summary.probeLossPct
: view.rateLabel == '失败率'
? summary.failurePct
: summary.unknownPct;
final motd = view.detail['motd'];
final version = view.detail['version'];
final players = view.detail['players'];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
spacing: 8,
runSpacing: 8,
children: [
_chip(view.phase),
_chip('来源 ${view.sourceLabel}'),
if (view.targetAddress != null) _chip('发往 ${view.targetAddress}'),
_chip('延迟 ${formatMs(summary.rttMs)}'),
_chip('抖动 ${formatMs(summary.jitterMs)}'),
_chip('${view.rateLabel} ${formatPct(rate)}'),
],
),
if (view.targetIsFake) ...[
const SizedBox(height: 8),
const Text(
clashFakeIpNote,
style: TextStyle(color: Color(0xFF9A3412), fontSize: 13),
),
],
if (view.note.isNotEmpty) ...[
const SizedBox(height: 8),
Text(view.note, style: const TextStyle(color: ink)),
],
if (motd != null || version != null || players != null) ...[
const SizedBox(height: 8),
Text(
[
if (motd != null) 'MOTD $motd',
if (version != null) '版本 $version',
if (players != null) '人数 $players',
].join(' · '),
style: const TextStyle(color: ink),
),
],
const SizedBox(height: 8),
Text(summaryLine(summary), style: const TextStyle(color: muted, fontSize: 13)),
],
);
}
Future<void> _manageNodes() async {
await showDialog<void>(
context: context,
builder: (context) => _NodeDialog(
nodes: _nodes,
vault: _vault,
onChanged: (nodes, selected) {
setState(() {
_nodes = nodes;
if (selected != null) {
_nodeId = selected;
_remote = true;
} else if (_nodes.every((node) => node.id != _nodeId)) {
_nodeId = '';
}
});
unawaited(_persist());
},
),
);
}
}
class _NodeDialog extends StatefulWidget {
const _NodeDialog({
required this.nodes,
required this.vault,
required this.onChanged,
});
final List<RemoteNode> nodes;
final TokenVault vault;
final void Function(List<RemoteNode> nodes, String? selected) onChanged;
@override
State<_NodeDialog> createState() => _NodeDialogState();
}
class _NodeDialogState extends State<_NodeDialog> {
late List<RemoteNode> _nodes = [...widget.nodes];
final _name = TextEditingController();
final _url = TextEditingController();
final _token = TextEditingController();
String? _hint;
@override
void dispose() {
_name.dispose();
_url.dispose();
_token.dispose();
super.dispose();
}
Future<void> _save() async {
final url = normalizeNodeUrl(_url.text);
if (_name.text.trim().isEmpty || url == null) {
setState(() => _hint = '请填写名称,以及不带口令的 http 或 https 地址');
return;
}
final id = DateTime.now().microsecondsSinceEpoch.toString();
final node = RemoteNode(id: id, name: _name.text.trim(), baseUrl: url);
await widget.vault.write(nodeTokenKey(id), _token.text.trim());
setState(() {
_nodes = [..._nodes, node];
_hint = '已保存。口令只留在本机。';
_name.clear();
_url.clear();
_token.clear();
});
widget.onChanged(_nodes, id);
}
Future<void> _check(RemoteNode node) async {
try {
final info = await fetchNodeInfo(node.baseUrl);
final next = [
for (final item in _nodes)
if (item.id == node.id)
item.copyWith(visibility: info.visibility)
else
item,
];
setState(() {
_nodes = next;
_hint = info.authRequired
? '这个节点是私有的,请求必须带正确的节点口令,否则不会向目标发包。'
: '这个节点是公开的,不需要口令。它仍然有并发、时长和带宽上限。';
});
widget.onChanged(next, node.id);
} on RemoteException catch (error) {
setState(() => _hint = error.message);
}
}
Future<void> _delete(RemoteNode node) async {
await widget.vault.delete(nodeTokenKey(node.id));
final next = [for (final item in _nodes) if (item.id != node.id) item];
setState(() => _nodes = next);
widget.onChanged(next, null);
}
@override
Widget build(BuildContext context) {
return AlertDialog(
title: const Text('远程节点'),
content: SizedBox(
width: 460,
child: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'节点口令和目标回显口令是两回事。服务器没配置节点口令时,它是公开节点;配置了就必须校验,错误口令不会发出任何探测。',
style: TextStyle(fontSize: 13, color: muted),
),
const SizedBox(height: 12),
for (final node in _nodes)
ListTile(
contentPadding: EdgeInsets.zero,
title: Text(_nodes.isEmpty ? '' : '${node.name} · ${visibilityLabel(node.visibility)}'),
subtitle: Text(node.baseUrl, maxLines: 1, overflow: TextOverflow.ellipsis),
trailing: Wrap(
spacing: 4,
children: [
TextButton(onPressed: () => _check(node), child: const Text('检查')),
TextButton(onPressed: () => _delete(node), child: const Text('删除')),
],
),
),
TextField(
controller: _name,
decoration: const InputDecoration(labelText: '名称'),
),
const SizedBox(height: 8),
TextField(
controller: _url,
decoration: const InputDecoration(
labelText: '节点地址',
hintText: 'https://probe.example:8443',
),
),
const SizedBox(height: 8),
TextField(
controller: _token,
obscureText: true,
decoration: const InputDecoration(
labelText: '节点口令(公开节点留空)',
),
),
if (_hint != null) ...[
const SizedBox(height: 8),
Text(_hint!, style: const TextStyle(fontSize: 13)),
],
],
),
),
),
actions: [
TextButton(onPressed: _save, child: const Text('添加节点')),
TextButton(onPressed: () => Navigator.pop(context), child: const Text('完成')),
],
);
}
}
Widget _card({required String title, required Widget child}) {
return Card(
margin: const EdgeInsets.only(bottom: 12),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
child: Padding(
padding: const EdgeInsets.all(14),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(title, style: const TextStyle(fontWeight: FontWeight.w700, color: ink)),
const SizedBox(height: 10),
child,
],
),
),
);
}
Widget _field(
TextEditingController controller,
String label,
String hint, {
bool secret = false,
}) {
return TextField(
controller: controller,
obscureText: secret,
decoration: InputDecoration(labelText: label, hintText: hint),
);
}
Widget _pair(bool wide, Widget left, Widget right) {
if (!wide) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [left, const SizedBox(height: 12), right],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: left),
const SizedBox(width: 12),
Expanded(child: right),
],
);
}
Widget _chip(String text) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: const Color(0xFFE7EEF5),
borderRadius: BorderRadius.circular(99),
),
child: Text(text, style: const TextStyle(fontSize: 12, color: ink)),
);
}
Widget _banner(String text) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFFFF1E8),
borderRadius: BorderRadius.circular(10),
border: Border.all(color: const Color(0xFFF0C9B0)),
),
child: Text(text, style: const TextStyle(color: Color(0xFF9A3412))),
);
}
+284
View File
@@ -0,0 +1,284 @@
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/material.dart';
import '../probe/probe_controller.dart';
const rttColor = Color(0xFF1F4E79);
const rateColor = Color(0xFF9A3412);
const ink = Color(0xFF1C2430);
const muted = Color(0xFF5E6872);
const line = Color(0xFFE4DFD4);
class QualityCharts extends StatelessWidget {
const QualityCharts({
super.key,
required this.samples,
required this.rateLabel,
required this.running,
});
final List<ChartSample> samples;
final String rateLabel;
final bool running;
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Row(
children: [
_Swatch(color: rttColor, label: '往返时间'),
SizedBox(width: 16),
_Swatch(color: rateColor, label: '比率'),
],
),
const SizedBox(height: 8),
_ChartCard(
title: '延迟',
unit: 'ms',
samples: samples,
read: (sample) => sample.rttMs,
color: rttColor,
floor: 1,
running: running,
),
_ChartCard(
title: rateLabel,
unit: '%',
samples: samples,
read: (sample) => sample.ratePct,
color: rateColor,
floor: 10,
running: running,
),
],
);
}
}
class _Swatch extends StatelessWidget {
const _Swatch({required this.color, required this.label});
final Color color;
final String label;
@override
Widget build(BuildContext context) {
return Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 14,
height: 3,
decoration: BoxDecoration(
color: color,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(width: 6),
Text(label, style: const TextStyle(color: muted, fontSize: 12)),
],
);
}
}
class _ChartCard extends StatelessWidget {
const _ChartCard({
required this.title,
required this.unit,
required this.samples,
required this.read,
required this.color,
required this.floor,
required this.running,
});
final String title;
final String unit;
final List<ChartSample> samples;
final double? Function(ChartSample sample) read;
final Color color;
final double floor;
final bool running;
@override
Widget build(BuildContext context) {
final spots = _spots();
final hasData = spots.any((spot) => !spot.isNull());
return Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: const BorderSide(color: line),
),
margin: const EdgeInsets.only(bottom: 12),
child: Padding(
padding: const EdgeInsets.fromLTRB(12, 12, 12, 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'$title($unit)',
style: const TextStyle(
color: ink,
fontWeight: FontWeight.w600,
fontSize: 14,
),
),
const SizedBox(height: 8),
SizedBox(
height: 168,
child: hasData
? _lineChart(spots)
: Center(
child: Text(
running
? '正在等待第一次完成的探测。未完成的不会画成 100%。'
: '暂无已完成的探测',
style: const TextStyle(color: muted),
textAlign: TextAlign.center,
),
),
),
],
),
),
);
}
List<FlSpot> _spots() {
final spots = <FlSpot>[];
for (final sample in samples) {
final value = read(sample);
if (value == null) {
if (spots.isNotEmpty && !spots.last.isNull()) {
spots.add(FlSpot.nullSpot);
}
} else {
spots.add(FlSpot(sample.sec, value));
}
}
if (spots.isNotEmpty && spots.last.isNull()) {
spots.removeLast();
}
return spots;
}
Widget _lineChart(List<FlSpot> spots) {
final minX = samples.first.sec;
var maxX = samples.last.sec;
if (maxX - minX < 1) {
maxX = minX + 1;
}
var maxY = floor;
for (final spot in spots) {
if (!spot.isNull() && spot.y > maxY) {
maxY = spot.y;
}
}
maxY = maxY * 1.2;
final yInterval = _yInterval(maxY);
final xInterval = _xInterval(maxX - minX);
return LineChart(
LineChartData(
minX: minX,
maxX: maxX,
minY: 0,
maxY: maxY,
clipData: const FlClipData.all(),
gridData: FlGridData(
show: true,
drawVerticalLine: false,
horizontalInterval: yInterval,
getDrawingHorizontalLine: (_) => const FlLine(color: line, strokeWidth: 1),
),
borderData: FlBorderData(
show: true,
border: const Border(
left: BorderSide(color: line),
bottom: BorderSide(color: line),
),
),
titlesData: FlTitlesData(
topTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
rightTitles: const AxisTitles(sideTitles: SideTitles(showTitles: false)),
leftTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 40,
interval: yInterval,
getTitlesWidget: (value, meta) => _axisLabel(_formatTick(value, maxY)),
),
),
bottomTitles: AxisTitles(
sideTitles: SideTitles(
showTitles: true,
reservedSize: 26,
interval: xInterval,
getTitlesWidget: (value, meta) =>
_axisLabel('${value.toStringAsFixed(0)}s'),
),
),
),
lineTouchData: const LineTouchData(handleBuiltInTouches: true),
lineBarsData: [
LineChartBarData(
spots: spots,
isCurved: false,
color: color,
barWidth: 2,
dotData: const FlDotData(show: false),
belowBarData: BarAreaData(show: true, color: color.withValues(alpha: 0.10)),
),
],
),
duration: Duration.zero,
);
}
}
Widget _axisLabel(String text) {
return Padding(
padding: const EdgeInsets.only(right: 4),
child: Text(text, style: const TextStyle(color: muted, fontSize: 10)),
);
}
double _yInterval(double maxY) {
if (maxY <= 1) {
return 0.25;
}
if (maxY <= 5) {
return 1;
}
if (maxY <= 20) {
return 5;
}
if (maxY <= 50) {
return 10;
}
if (maxY <= 120) {
return 20;
}
if (maxY <= 300) {
return 50;
}
return 100;
}
double _xInterval(double span) {
if (span <= 15) {
return 5;
}
if (span <= 40) {
return 10;
}
return 15;
}
String _formatTick(double value, double maxY) {
if (maxY < 5) {
return value.toStringAsFixed(value < 1 ? 2 : 1);
}
return value.toStringAsFixed(0);
}
+1
View File
@@ -0,0 +1 @@
flutter/ephemeral
+128
View File
@@ -0,0 +1,128 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "netquality")
# The unique GTK application identifier for this application. See:
# https://wiki.gnome.org/HowDoI/ChooseApplicationID
set(APPLICATION_ID "dev.netquality.netquality")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(SET CMP0063 NEW)
# Load bundled libraries from the lib/ directory relative to the binary.
set(CMAKE_INSTALL_RPATH "$ORIGIN/lib")
# Root filesystem for cross-building.
if(FLUTTER_TARGET_PLATFORM_SYSROOT)
set(CMAKE_SYSROOT ${FLUTTER_TARGET_PLATFORM_SYSROOT})
set(CMAKE_FIND_ROOT_PATH ${CMAKE_SYSROOT})
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_PACKAGE ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
endif()
# Define build configuration options.
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_14)
target_compile_options(${TARGET} PRIVATE -Wall -Werror)
target_compile_options(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:-O3>")
target_compile_definitions(${TARGET} PRIVATE "$<$<NOT:$<CONFIG:Debug>>:NDEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
# Only the install-generated bundle's copy of the executable will launch
# correctly, since the resources must in the right relative locations. To avoid
# people trying to run the unbundled copy, put it in a subdirectory instead of
# the default top-level location.
set_target_properties(${BINARY_NAME}
PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/intermediates_do_not_run"
)
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# By default, "installing" just makes a relocatable bundle in the build
# directory.
set(BUILD_BUNDLE_DIR "${PROJECT_BINARY_DIR}/bundle")
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
# Start with a clean build bundle directory every time.
install(CODE "
file(REMOVE_RECURSE \"${BUILD_BUNDLE_DIR}/\")
" COMPONENT Runtime)
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}/lib")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
foreach(bundled_library ${PLUGIN_BUNDLED_LIBRARIES})
install(FILES "${bundled_library}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endforeach(bundled_library)
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/linux/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
if(NOT CMAKE_BUILD_TYPE MATCHES "Debug")
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
+88
View File
@@ -0,0 +1,88 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.10)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
# Serves the same purpose as list(TRANSFORM ... PREPEND ...),
# which isn't available in 3.10.
function(list_prepend LIST_NAME PREFIX)
set(NEW_LIST "")
foreach(element ${${LIST_NAME}})
list(APPEND NEW_LIST "${PREFIX}${element}")
endforeach(element)
set(${LIST_NAME} "${NEW_LIST}" PARENT_SCOPE)
endfunction()
# === Flutter Library ===
# System-level dependencies.
find_package(PkgConfig REQUIRED)
pkg_check_modules(GTK REQUIRED IMPORTED_TARGET gtk+-3.0)
pkg_check_modules(GLIB REQUIRED IMPORTED_TARGET glib-2.0)
pkg_check_modules(GIO REQUIRED IMPORTED_TARGET gio-2.0)
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/libflutter_linux_gtk.so")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/lib/libapp.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"fl_basic_message_channel.h"
"fl_binary_codec.h"
"fl_binary_messenger.h"
"fl_dart_project.h"
"fl_engine.h"
"fl_json_message_codec.h"
"fl_json_method_codec.h"
"fl_message_codec.h"
"fl_method_call.h"
"fl_method_channel.h"
"fl_method_codec.h"
"fl_method_response.h"
"fl_plugin_registrar.h"
"fl_plugin_registry.h"
"fl_standard_message_codec.h"
"fl_standard_method_codec.h"
"fl_string_codec.h"
"fl_value.h"
"fl_view.h"
"flutter_linux.h"
)
list_prepend(FLUTTER_LIBRARY_HEADERS "${EPHEMERAL_DIR}/flutter_linux/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}")
target_link_libraries(flutter INTERFACE
PkgConfig::GTK
PkgConfig::GLIB
PkgConfig::GIO
)
add_dependencies(flutter flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CMAKE_CURRENT_BINARY_DIR}/_phony_
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.sh"
${FLUTTER_TARGET_PLATFORM} ${CMAKE_BUILD_TYPE}
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
)
@@ -0,0 +1,11 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
void fl_register_plugins(FlPluginRegistry* registry) {
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter_linux/flutter_linux.h>
// Registers Flutter plugins.
void fl_register_plugins(FlPluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
@@ -0,0 +1,24 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
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 $<TARGET_FILE:${plugin}_plugin>)
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)
+26
View File
@@ -0,0 +1,26 @@
cmake_minimum_required(VERSION 3.13)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME}
"main.cc"
"my_application.cc"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the application ID.
add_definitions(-DAPPLICATION_ID="${APPLICATION_ID}")
# Add dependency libraries. Add any application-specific dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter)
target_link_libraries(${BINARY_NAME} PRIVATE PkgConfig::GTK)
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
+6
View File
@@ -0,0 +1,6 @@
#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);
}
+148
View File
@@ -0,0 +1,148 @@
#include "my_application.h"
#include <flutter_linux/flutter_linux.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#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)
// Called when first Flutter frame received.
static void first_frame_cb(MyApplication* self, FlView* view) {
gtk_widget_show(gtk_widget_get_toplevel(GTK_WIDGET(view)));
}
// 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, "网络质量探测");
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, "网络质量探测");
}
gtk_window_set_default_size(window, 1180, 800);
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);
GdkRGBA background_color;
// Background defaults to black, override it here if necessary, e.g. #00000000
// for transparent.
gdk_rgba_parse(&background_color, "#F3F1EC");
fl_view_set_background_color(view, &background_color);
gtk_widget_show(GTK_WIDGET(view));
gtk_container_add(GTK_CONTAINER(window), GTK_WIDGET(view));
// Show the window when Flutter renders.
// Requires the view to be realized so we can start rendering.
g_signal_connect_swapped(view, "first-frame", G_CALLBACK(first_frame_cb),
self);
gtk_widget_realize(GTK_WIDGET(view));
fl_register_plugins(FL_PLUGIN_REGISTRY(view));
gtk_widget_grab_focus(GTK_WIDGET(view));
}
// Implements GApplication::local_command_line.
static gboolean my_application_local_command_line(GApplication* application,
gchar*** arguments,
int* exit_status) {
MyApplication* self = MY_APPLICATION(application);
// Strip out the first argument as it is the binary name.
self->dart_entrypoint_arguments = g_strdupv(*arguments + 1);
g_autoptr(GError) error = nullptr;
if (!g_application_register(application, nullptr, &error)) {
g_warning("Failed to register: %s", error->message);
*exit_status = 1;
return TRUE;
}
g_application_activate(application);
*exit_status = 0;
return TRUE;
}
// Implements GApplication::startup.
static void my_application_startup(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application startup.
G_APPLICATION_CLASS(my_application_parent_class)->startup(application);
}
// Implements GApplication::shutdown.
static void my_application_shutdown(GApplication* application) {
// MyApplication* self = MY_APPLICATION(object);
// Perform any actions required at application shutdown.
G_APPLICATION_CLASS(my_application_parent_class)->shutdown(application);
}
// Implements GObject::dispose.
static void my_application_dispose(GObject* object) {
MyApplication* self = MY_APPLICATION(object);
g_clear_pointer(&self->dart_entrypoint_arguments, g_strfreev);
G_OBJECT_CLASS(my_application_parent_class)->dispose(object);
}
static void my_application_class_init(MyApplicationClass* klass) {
G_APPLICATION_CLASS(klass)->activate = my_application_activate;
G_APPLICATION_CLASS(klass)->local_command_line =
my_application_local_command_line;
G_APPLICATION_CLASS(klass)->startup = my_application_startup;
G_APPLICATION_CLASS(klass)->shutdown = my_application_shutdown;
G_OBJECT_CLASS(klass)->dispose = my_application_dispose;
}
static void my_application_init(MyApplication* self) {}
MyApplication* my_application_new() {
// Set the program name to the application ID, which helps various systems
// like GTK and desktop environments map this running application to its
// corresponding .desktop file. This ensures better integration by allowing
// the application to be recognized beyond its binary name.
g_set_prgname(APPLICATION_ID);
return MY_APPLICATION(g_object_new(my_application_get_type(),
"application-id", APPLICATION_ID, "flags",
G_APPLICATION_NON_UNIQUE, nullptr));
}
+21
View File
@@ -0,0 +1,21 @@
#ifndef FLUTTER_MY_APPLICATION_H_
#define FLUTTER_MY_APPLICATION_H_
#include <gtk/gtk.h>
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_
+490
View File
@@ -0,0 +1,490 @@
# Generated by pub
# See https://dart.dev/tools/pub/glossary#lockfile
packages:
args:
dependency: transitive
description:
name: args
sha256: d0481093c50b1da8910eb0bb301626d4d8eb7284aa739614d2b394ee09e3ea04
url: "https://pub.dev"
source: hosted
version: "2.7.0"
async:
dependency: transitive
description:
name: async
sha256: e2eb0491ba5ddb6177742d2da23904574082139b07c1e33b8503b9f46f3e1a37
url: "https://pub.dev"
source: hosted
version: "2.13.1"
boolean_selector:
dependency: transitive
description:
name: boolean_selector
sha256: "8aab1771e1243a5063b8b0ff68042d67334e3feab9e95b9490f9a6ebf73b42ea"
url: "https://pub.dev"
source: hosted
version: "2.1.2"
characters:
dependency: transitive
description:
name: characters
sha256: faf38497bda5ead2a8c7615f4f7939df04333478bf32e4173fcb06d428b5716b
url: "https://pub.dev"
source: hosted
version: "1.4.1"
clock:
dependency: transitive
description:
name: clock
sha256: e51d50bca3217c9a9fa2b41a30e4a38971133f5f9ec7a3d57bae095007f1d28e
url: "https://pub.dev"
source: hosted
version: "1.1.3"
code_assets:
dependency: transitive
description:
name: code_assets
sha256: bf394f466ba9205f1812a0433b392d6af280f155f56651eda7c18cc32ed493b8
url: "https://pub.dev"
source: hosted
version: "1.2.1"
collection:
dependency: transitive
description:
name: collection
sha256: "2f5709ae4d3d59dd8f7cd309b4e023046b57d8a6c82130785d2b0e5868084e76"
url: "https://pub.dev"
source: hosted
version: "1.19.1"
crypto:
dependency: transitive
description:
name: crypto
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
url: "https://pub.dev"
source: hosted
version: "3.0.8"
cupertino_icons:
dependency: "direct main"
description:
name: cupertino_icons
sha256: "41e005c33bd814be4d3096aff55b1908d419fde52ca656c8c47719ec745873cd"
url: "https://pub.dev"
source: hosted
version: "1.0.9"
equatable:
dependency: transitive
description:
name: equatable
sha256: ea36e500cbf0ec18361deabca755434f73e42fe53c5130021c7e2d6b5ebe1702
url: "https://pub.dev"
source: hosted
version: "3.0.0"
fake_async:
dependency: transitive
description:
name: fake_async
sha256: "5368f224a74523e8d2e7399ea1638b37aecfca824a3cc4dfdf77bf1fa905ac44"
url: "https://pub.dev"
source: hosted
version: "1.3.3"
ffi:
dependency: transitive
description:
name: ffi
sha256: "6d7fd89431262d8f3125e81b50d3847a091d846eafcd4fdb88dd06f36d705a45"
url: "https://pub.dev"
source: hosted
version: "2.2.0"
file:
dependency: transitive
description:
name: file
sha256: a3b4f84adafef897088c160faf7dfffb7696046cb13ae90b508c2cbc95d3b8d4
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fl_chart:
dependency: "direct main"
description:
name: fl_chart
sha256: "5ed69b8be550c6276c8f0bc25c09704fb061018ed1b1681867ad18fcf477e7b7"
url: "https://pub.dev"
source: hosted
version: "1.3.0"
flutter:
dependency: "direct main"
description: flutter
source: sdk
version: "0.0.0"
flutter_lints:
dependency: "direct dev"
description:
name: flutter_lints
sha256: "3105dc8492f6183fb076ccf1f351ac3d60564bff92e20bfc4af9cc1651f4e7e1"
url: "https://pub.dev"
source: hosted
version: "6.0.0"
flutter_test:
dependency: "direct dev"
description: flutter
source: sdk
version: "0.0.0"
flutter_web_plugins:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
hooks:
dependency: transitive
description:
name: hooks
sha256: "9a62a50b50b769a737bc0a8ff381f333529df3ab746b2f6b02e83760231455ba"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
jni:
dependency: transitive
description:
name: jni
sha256: "2e91e6087291affd10b31b6c872f3e3ac7dc5d93b51b5ba485d930c8f08bde6c"
url: "https://pub.dev"
source: hosted
version: "1.1.2"
jni_flutter:
dependency: transitive
description:
name: jni_flutter
sha256: "0dd33d67797560f66e961a6053882d4df54bd345bf063b8fe7ea133f7ad8b191"
url: "https://pub.dev"
source: hosted
version: "1.0.4+1"
jni_util:
dependency: transitive
description:
name: jni_util
sha256: "1ba86da04a5f2bf18fde2edb235587e70c5b0fc5bd4ba955f46b00942c3fc35f"
url: "https://pub.dev"
source: hosted
version: "1.0.0"
leak_tracker:
dependency: transitive
description:
name: leak_tracker
sha256: "33e2e26bdd85a0112ec15400c8cbffea70d0f9c3407491f672a2fad47915e2de"
url: "https://pub.dev"
source: hosted
version: "11.0.2"
leak_tracker_flutter_testing:
dependency: transitive
description:
name: leak_tracker_flutter_testing
sha256: "1dbc140bb5a23c75ea9c4811222756104fbcd1a27173f0c34ca01e16bea473c1"
url: "https://pub.dev"
source: hosted
version: "3.0.10"
leak_tracker_testing:
dependency: transitive
description:
name: leak_tracker_testing
sha256: "8d5a2d49f4a66b49744b23b018848400d23e54caf9463f4eb20df3eb8acb2eb1"
url: "https://pub.dev"
source: hosted
version: "3.0.2"
lints:
dependency: transitive
description:
name: lints
sha256: "12f842a479589fea194fe5c5a3095abc7be0c1f2ddfa9a0e76aed1dbd26a87df"
url: "https://pub.dev"
source: hosted
version: "6.1.0"
logging:
dependency: transitive
description:
name: logging
sha256: c8245ada5f1717ed44271ed1c26b8ce85ca3228fd2ffdb75468ab01979309d61
url: "https://pub.dev"
source: hosted
version: "1.3.0"
matcher:
dependency: transitive
description:
name: matcher
sha256: "31bd099b47c10cd1aeb55146a2d46ce0277630ecef3f7dae54ad7873f36696cd"
url: "https://pub.dev"
source: hosted
version: "0.12.20"
material_color_utilities:
dependency: transitive
description:
name: material_color_utilities
sha256: "9c337007e82b1889149c82ed242ed1cb24a66044e30979c44912381e9be4c48b"
url: "https://pub.dev"
source: hosted
version: "0.13.0"
meta:
dependency: transitive
description:
name: meta
sha256: c82594181e3312f3d0695fc95aaaf7758d75b8d4ae2bbecf223b9fd5109a059d
url: "https://pub.dev"
source: hosted
version: "1.18.3"
objective_c:
dependency: transitive
description:
name: objective_c
sha256: b7fb95a6d9a4f009edd63dc5ac69f07420b23a16161c6dd8660290b59c602e8e
url: "https://pub.dev"
source: hosted
version: "9.5.0"
package_config:
dependency: transitive
description:
name: package_config
sha256: ffcf4cf3d6c0b74ac43708d9f56625506e8a68aa935abe9d267a7330f320eb5d
url: "https://pub.dev"
source: hosted
version: "3.0.0"
path:
dependency: transitive
description:
name: path
sha256: "75cca69d1490965be98c73ceaea117e8a04dd21217b37b292c9ddbec0d955bc5"
url: "https://pub.dev"
source: hosted
version: "1.9.1"
path_provider:
dependency: "direct main"
description:
name: path_provider
sha256: a7f4874f987173da295a61c181b8ee71dab59b332a486b391babf26a1b884825
url: "https://pub.dev"
source: hosted
version: "2.1.6"
path_provider_android:
dependency: transitive
description:
name: path_provider_android
sha256: "69cbd515a62b94d32a7944f086b2f82b4ac40a1d45bebfc00813a430ab2dabcd"
url: "https://pub.dev"
source: hosted
version: "2.3.1"
path_provider_foundation:
dependency: transitive
description:
name: path_provider_foundation
sha256: "2a376b7d6392d80cd3705782d2caa734ca4727776db0b6ec36ef3f1855197699"
url: "https://pub.dev"
source: hosted
version: "2.6.0"
path_provider_linux:
dependency: transitive
description:
name: path_provider_linux
sha256: "58c2005f147315b11e9b4a7bc889cd5203e250cba8e3f012dae259b4972b5c16"
url: "https://pub.dev"
source: hosted
version: "2.2.2"
path_provider_platform_interface:
dependency: transitive
description:
name: path_provider_platform_interface
sha256: "484838772624c3a4b94f1e44a3e19897fee738f2d5c4ce448443b0417f7c9dda"
url: "https://pub.dev"
source: hosted
version: "2.1.3"
path_provider_windows:
dependency: transitive
description:
name: path_provider_windows
sha256: bd6f00dbd873bfb70d0761682da2b3a2c2fccc2b9e84c495821639601d81afe7
url: "https://pub.dev"
source: hosted
version: "2.3.0"
platform:
dependency: transitive
description:
name: platform
sha256: a36d119c13416516a7b5913fbe8af8531e11633d784c550b2125f76c758524ec
url: "https://pub.dev"
source: hosted
version: "3.2.0"
plugin_platform_interface:
dependency: transitive
description:
name: plugin_platform_interface
sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02"
url: "https://pub.dev"
source: hosted
version: "2.1.8"
pub_semver:
dependency: transitive
description:
name: pub_semver
sha256: "261236774e8b1d69cfc6b9eabbc96c40f25e7a2d6b171f3385d4f65d5734fb24"
url: "https://pub.dev"
source: hosted
version: "2.2.1"
record_use:
dependency: transitive
description:
name: record_use
sha256: "2551bd8eecfe95d14ae75f6021ad0248be5c27f138c2ec12fcb52b500b3ba1ed"
url: "https://pub.dev"
source: hosted
version: "0.6.0"
shared_preferences:
dependency: "direct main"
description:
name: shared_preferences
sha256: "1e85e0dccf5b4a016077fea7dfbb4a7cb39c759ac1596fcf60c06deadb7da91f"
url: "https://pub.dev"
source: hosted
version: "2.5.6"
shared_preferences_android:
dependency: transitive
description:
name: shared_preferences_android
sha256: "33b38b07d9ac7d16aff0426c61418752fd3e7a8c7dc8be786c875d6ce673b002"
url: "https://pub.dev"
source: hosted
version: "2.5.4"
shared_preferences_foundation:
dependency: transitive
description:
name: shared_preferences_foundation
sha256: "2ec3934efa51e46117f23031cc141b8fc878e8525b94ec1ea4f7f586cf1b47ea"
url: "https://pub.dev"
source: hosted
version: "2.5.7"
shared_preferences_linux:
dependency: transitive
description:
name: shared_preferences_linux
sha256: "580abfd40f415611503cae30adf626e6656dfb2f0cee8f465ece7b6defb40f2f"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
shared_preferences_platform_interface:
dependency: transitive
description:
name: shared_preferences_platform_interface
sha256: "649dc798a33931919ea356c4305c2d1f81619ea6e92244070b520187b5140ef9"
url: "https://pub.dev"
source: hosted
version: "2.4.2"
shared_preferences_web:
dependency: transitive
description:
name: shared_preferences_web
sha256: c49bd060261c9a3f0ff445892695d6212ff603ef3115edbb448509d407600019
url: "https://pub.dev"
source: hosted
version: "2.4.3"
shared_preferences_windows:
dependency: transitive
description:
name: shared_preferences_windows
sha256: "94ef0f72b2d71bc3e700e025db3710911bd51a71cefb65cc609dd0d9a982e3c1"
url: "https://pub.dev"
source: hosted
version: "2.4.1"
sky_engine:
dependency: transitive
description: flutter
source: sdk
version: "0.0.0"
source_span:
dependency: transitive
description:
name: source_span
sha256: "56a02f1f4cd1a2d96303c0144c93bd6d909eea6bee6bf5a0e0b685edbd4c47ab"
url: "https://pub.dev"
source: hosted
version: "1.10.2"
stack_trace:
dependency: transitive
description:
name: stack_trace
sha256: "277654b3034d17ac6f9f1cb5595db011b1d5d41e8806866db28e0abaa101c490"
url: "https://pub.dev"
source: hosted
version: "1.12.2"
stream_channel:
dependency: transitive
description:
name: stream_channel
sha256: "969e04c80b8bcdf826f8f16579c7b14d780458bd97f56d107d3950fdbeef059d"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
string_scanner:
dependency: transitive
description:
name: string_scanner
sha256: "921cd31725b72fe181906c6a94d987c78e3b98c2e205b397ea399d4054872b43"
url: "https://pub.dev"
source: hosted
version: "1.4.1"
term_glyph:
dependency: transitive
description:
name: term_glyph
sha256: "7f554798625ea768a7518313e58f83891c7f5024f88e46e7182a4558850a4b8e"
url: "https://pub.dev"
source: hosted
version: "1.2.2"
test_api:
dependency: transitive
description:
name: test_api
sha256: "2a122cbe059f8b610d3a5415f42e255b6c17b1f21eee1d960f31080237fb4f11"
url: "https://pub.dev"
source: hosted
version: "0.7.12"
vector_math:
dependency: transitive
description:
name: vector_math
sha256: "1d774bbdf6b72a0b12122fc1560c9c2d2a67db5a4a4cc2bd8a5c990ab20e3188"
url: "https://pub.dev"
source: hosted
version: "2.4.0"
vm_service:
dependency: transitive
description:
name: vm_service
sha256: "89b11d62e1040ee681af3b4f1c97a803ecbf010c6e8b9c5896ee5b08c3bf7b78"
url: "https://pub.dev"
source: hosted
version: "15.4.0"
web:
dependency: transitive
description:
name: web
sha256: e119e82ac4795c7925103b7cf3768191f33941b99e7ccffbd6c645201d9f606b
url: "https://pub.dev"
source: hosted
version: "1.1.2"
xdg_directories:
dependency: transitive
description:
name: xdg_directories
sha256: "7a3f37b05d989967cdddcbb571f1ea834867ae2faa29725fd085180e0883aa15"
url: "https://pub.dev"
source: hosted
version: "1.1.0"
yaml:
dependency: transitive
description:
name: yaml
sha256: f67cdd8e07d3c6329146aaef1ba043542b3134c12489f553ca9a7435d1068aea
url: "https://pub.dev"
source: hosted
version: "3.1.4"
sdks:
dart: ">=3.13.7 <4.0.0"
flutter: ">=3.44.0"
+97
View File
@@ -0,0 +1,97 @@
name: netquality
description: "UDP/TCP connection quality probe"
# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.1.1+4
environment:
sdk: ^3.13.7
# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
flutter:
sdk: flutter
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.8
fl_chart: ^1.3.0
path_provider: ^2.1.5
shared_preferences: ^2.5.6
dev_dependencies:
flutter_test:
sdk: flutter
# The "flutter_lints" package below contains a set of recommended lints to
# encourage good coding practices. The lint set provided by the package is
# activated in the `analysis_options.yaml` file located at the root of your
# package. See that file for information about deactivating specific lint
# rules and activating additional ones.
flutter_lints: ^6.0.0
# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec
# The following section is specific to Flutter packages.
flutter:
# The following line ensures that the Material Icons font is
# included with your application, so that you can use the icons in
# the material Icons class.
uses-material-design: true
fonts:
- family: NetQualityCJK
fonts:
- asset: assets/fonts/wqy-subset.ttf
# To add assets to your application, add an assets section, like this:
# assets:
# - images/a_dot_burr.jpeg
# - images/a_dot_ham.jpeg
# An image asset can refer to one or more resolution-specific "variants", see
# https://flutter.dev/to/resolution-aware-images
# For details regarding adding assets from package dependencies, see
# https://flutter.dev/to/asset-from-package
# To add custom fonts to your application, add a fonts section here,
# in this "flutter" section. Each entry in this list should have a
# "family" key with the font family name, and a "fonts" key with a
# list giving the asset and other descriptors for the font. For
# example:
# fonts:
# - family: Schyler
# fonts:
# - asset: fonts/Schyler-Regular.ttf
# - asset: fonts/Schyler-Italic.ttf
# style: italic
# - family: Trajan Pro
# fonts:
# - asset: fonts/TrajanPro.ttf
# - asset: fonts/TrajanPro_Bold.ttf
# weight: 700
#
# For details regarding fonts from package dependencies,
# see https://flutter.dev/to/font-from-package
+50
View File
@@ -0,0 +1,50 @@
import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/probe/endpoint_picker.dart';
void main() {
test('a miss before any answer tries the next address', () {
final v6 = InternetAddress('2001:db8::1');
final v4 = InternetAddress('203.0.113.5');
final picker = EndpointPicker([v6, v4]);
expect(picker.current, v6);
expect(picker.record(false), isTrue);
expect(picker.current, v4);
expect(picker.record(true), isFalse);
expect(picker.current, v4);
expect(picker.hasAnswered, isTrue);
});
test('a working address survives two misses and leaves on the third', () {
final v4 = InternetAddress('203.0.113.5');
final v6 = InternetAddress('2001:db8::1');
final picker = EndpointPicker([v4, v6]);
expect(picker.record(true), isFalse);
expect(picker.record(false), isFalse);
expect(picker.record(false), isFalse);
expect(picker.current, v4);
expect(picker.record(false), isTrue);
expect(picker.current, v6);
expect(picker.hasAnswered, isFalse);
expect(picker.record(false), isTrue);
expect(picker.current, v4);
});
test('one address is never abandoned', () {
final only = InternetAddress('203.0.113.9');
final picker = EndpointPicker([only]);
expect(picker.record(false), isFalse);
expect(picker.record(false), isFalse);
expect(picker.current, only);
});
test('198.18.0.0/15 is treated as a VPN fake address', () {
expect(isClashFakeIp(InternetAddress('198.18.0.1')), isTrue);
expect(isClashFakeIp(InternetAddress('198.19.255.254')), isTrue);
expect(isClashFakeIp(InternetAddress('198.17.255.255')), isFalse);
expect(isClashFakeIp(InternetAddress('198.20.0.1')), isFalse);
expect(isClashFakeIp(InternetAddress('180.172.93.226')), isFalse);
expect(isClashFakeIp(InternetAddress('2001:db8::1')), isFalse);
});
}
+498
View File
@@ -0,0 +1,498 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/probe_loop.dart';
import 'package:netquality/probe/remote_client.dart';
late String binary;
void main() {
setUpAll(() async {
final dir = await Directory.systemTemp.createTemp('nq-node');
binary = '${dir.path}/netquality-reflector';
final serverDir = Directory('server').existsSync() ? 'server' : '../server';
final build = await Process.run('go', [
'build',
'-o',
binary,
'.',
], workingDirectory: serverDir);
expect(build.exitCode, 0, reason: '${build.stdout}\n${build.stderr}');
});
test('local nq tcp and udp get real rtt and do not call connect failure loss', () async {
final reflector = await _reflector();
addTearDown(() => reflector.process.kill());
final tcp = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: reflector.tcp,
profileId: 'nq-tcp',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 2,
);
expect(tcp.last.status, Outcome.ok);
expect(tcp.last.rttMs, greaterThan(0));
expect(tcp.last.summary.probeLossPct, 0);
final udp = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: reflector.udp,
profileId: 'nq-udp',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(udp.single.status, Outcome.ok);
expect(udp.single.summary.probeLossPct, 0);
final refused = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: 1,
profileId: 'tcp-connect',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 400),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(refused.single.status, Outcome.refused);
expect(refused.single.summary.failurePct, 100);
expect(refused.single.summary.probeLossPct, isNull);
});
test('silence is unknown, games answer, and a remote node measures rtt', () async {
final hole = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(hole.close);
hole.listen((event) {
if (event == RawSocketEvent.read) {
hole.receive();
}
});
final unknown = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: hole.port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 200),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(unknown.single.status, Outcome.unknown);
expect(unknown.single.summary.probeLossPct, isNull);
expect(unknown.single.summary.unknownPct, 100);
expect(unknown.single.detail['address'], '127.0.0.1');
final java = await _javaServer();
addTearDown(java.close);
final javaSample = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: java.port,
profileId: 'minecraft-java',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(javaSample.single.status, Outcome.ok);
expect(javaSample.single.detail['motd'], 'Hello');
expect(javaSample.single.rttMs, greaterThan(0));
expect(javaSample.single.summary.failurePct, 0);
final bedrock = await _bedrockServer();
addTearDown(bedrock.close);
final bedrockSample = await _collect(
ProbeRequest(
host: '127.0.0.1',
port: bedrock.port,
profileId: 'minecraft-bedrock',
interval: const Duration(milliseconds: 200),
timeout: const Duration(milliseconds: 800),
packetSize: 64,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 1,
);
expect(bedrockSample.single.status, Outcome.ok);
expect(bedrockSample.single.detail['motd'], 'Bed');
final node = await _node();
addTearDown(node.kill);
final samples = <ProbeSample>[];
final remote = RemoteProbe();
final done = Completer<void>();
unawaited(() async {
try {
await remote.run(
baseUrl: 'http://127.0.0.1:${node.control}',
nodeToken: '',
body: ProbeBody(
target: '127.0.0.1',
port: node.udp,
profile: 'nq-udp',
intervalMs: 200,
timeoutMs: 800,
durationSec: 3,
packetSize: 80,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
onSample: (sample) {
samples.add(sample);
if (samples.length == 1 && !done.isCompleted) {
done.complete();
}
},
cancelled: () => done.isCompleted,
);
} finally {
if (!done.isCompleted) {
done.complete();
}
}
}());
await done.future.timeout(const Duration(seconds: 5));
await remote.stop('');
expect(samples, isNotEmpty);
expect(samples.first.status, Outcome.ok);
expect(samples.first.rttMs, greaterThan(0));
expect(samples.first.summary.probeLossPct, 0);
});
test('plain udp leaves a silent address and keeps one that answers', () async {
final drop = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(drop.close);
final port = drop.port;
drop.listen((event) {
if (event == RawSocketEvent.read) {
drop.receive();
}
});
final RawDatagramSocket echo;
try {
echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv6, port);
} on SocketException {
markTestSkipped('IPv6 loopback is not available');
return;
}
addTearDown(echo.close);
echo.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
final datagram = echo.receive();
if (datagram == null) {
return;
}
echo.send(datagram.data, datagram.address, datagram.port);
});
final seen = <String>[];
final samples = await _collect(
ProbeRequest(
host: 'example.test',
port: port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 40),
timeout: const Duration(milliseconds: 250),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 2,
loop: ProbeLoop(
lookup: (host) async {
expect(host, 'example.test');
return [InternetAddress('127.0.0.1'), InternetAddress('::1')];
},
onEndpoint: (address) => seen.add(address.address),
),
);
expect(samples.first.status, Outcome.unknown);
expect(samples.first.detail['address'], '127.0.0.1');
expect(samples.last.status, Outcome.ok);
expect(samples.last.detail['address'], '::1');
expect(seen, ['127.0.0.1', '::1']);
});
test('a responding address is not replaced while it still answers', () async {
final echo = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
addTearDown(echo.close);
echo.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
final datagram = echo.receive();
if (datagram == null) {
return;
}
echo.send(datagram.data, datagram.address, datagram.port);
});
final samples = await _collect(
ProbeRequest(
host: 'example.test',
port: echo.port,
profileId: 'udp-generic',
interval: const Duration(milliseconds: 40),
timeout: const Duration(milliseconds: 300),
packetSize: 16,
echoToken: '',
dnsName: '',
payloadHex: '',
expectHex: '',
),
count: 3,
loop: ProbeLoop(
lookup: (_) async => [
InternetAddress('127.0.0.1'),
InternetAddress('2001:db8::1'),
],
),
);
expect(samples.map((sample) => sample.status), everyElement(Outcome.ok));
expect(samples.map((sample) => sample.detail['address']), everyElement('127.0.0.1'));
});
}
Future<List<ProbeSample>> _collect(
ProbeRequest request, {
required int count,
ProbeLoop? loop,
}) async {
final probe = loop ?? ProbeLoop();
final samples = <ProbeSample>[];
var stop = false;
await probe
.run(
request: request,
onSample: (sample) {
samples.add(sample);
if (samples.length >= count) {
stop = true;
}
},
cancelled: () => stop,
)
.timeout(const Duration(seconds: 6));
return samples;
}
Future<({Process process, int tcp, int udp})> _reflector() async {
final tcp = await _freeTcp();
final udp = await _freeUdp();
final process = await Process.start(binary, [
'-bind',
'127.0.0.1',
'-tcp-port',
'$tcp',
'-udp-port',
'$udp',
'-mode',
'reflector',
]);
await _waitListen(process);
return (process: process, tcp: tcp, udp: udp);
}
Future<({Process process, int control, int udp, void Function() kill})> _node() async {
final udp = await _freeUdp();
final control = await _freeTcp();
final process = await Process.start(binary, [
'-bind',
'127.0.0.1',
'-tcp-port',
'0',
'-udp-port',
'$udp',
'-mode',
'both',
'-control-addr',
'127.0.0.1:$control',
'-allow-private',
]);
final ready = Completer<void>();
process.stderr.transform(utf8.decoder).listen((text) {
if (text.contains('node control listening') && !ready.isCompleted) {
ready.complete();
}
});
process.stdout.transform(utf8.decoder).listen((_) {});
await ready.future.timeout(const Duration(seconds: 3));
return (
process: process,
control: control,
udp: udp,
kill: () {
process.kill();
},
);
}
Future<void> _waitListen(Process process) async {
final ready = Completer<void>();
process.stderr.transform(utf8.decoder).listen((text) {
if (text.contains('listening') && !ready.isCompleted) {
ready.complete();
}
});
process.stdout.transform(utf8.decoder).listen((_) {});
await ready.future.timeout(const Duration(seconds: 3));
}
Future<int> _freeTcp() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = server.port;
await server.close();
return port;
}
Future<int> _freeUdp() async {
final socket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
final port = socket.port;
socket.close();
return port;
}
Future<({int port, Future<void> Function() close})> _javaServer() async {
final server = await ServerSocket.bind(InternetAddress.loopbackIPv4, 0);
final sub = server.listen((socket) async {
final reader = _Reader(socket);
await reader.next();
await reader.next();
const status =
'{"version":{"name":"1.21.1","protocol":767},"players":{"online":3,"max":20},"description":{"text":"Hello"}}';
final payload = BytesBuilder(copy: false)
..addByte(0x00)
..add(mcString(status));
socket.add(mcPacket(payload.toBytes()));
final ping = await reader.next();
if (ping != null) {
socket.add(mcPacket(ping));
}
await socket.close();
});
return (
port: server.port,
close: () async {
await sub.cancel();
await server.close();
},
);
}
Future<({int port, void Function() close})> _bedrockServer() async {
final socket = await RawDatagramSocket.bind(InternetAddress.loopbackIPv4, 0);
final sub = socket.listen((event) {
if (event != RawSocketEvent.read) {
return;
}
final datagram = socket.receive();
if (datagram == null || datagram.data.length < 9) {
return;
}
final ts = datagram.data.sublist(1, 9);
const motd = 'MCPE;Bed;844;1.21.50;1;10;0;world;Survival;1;19132;0;';
final body = BytesBuilder(copy: false)
..addByte(0x1c)
..add(ts)
..add(const [0, 0, 0, 0, 0, 0, 0, 99])
..add(rakMagic)
..addByte(0)
..addByte(motd.length)
..add(motd.codeUnits);
socket.send(body.toBytes(), datagram.address, datagram.port);
});
return (
port: socket.port,
close: () {
sub.cancel();
socket.close();
},
);
}
class _Reader {
_Reader(this.socket) {
socket.listen((data) {
_buf.add(data);
_pending?.complete();
_pending = null;
});
}
final Socket socket;
final BytesBuilder _buf = BytesBuilder(copy: false);
Completer<void>? _pending;
Future<Uint8List?> next() async {
final deadline = DateTime.now().add(const Duration(seconds: 2));
while (true) {
final bytes = _buf.toBytes();
final packet = takeMcPacket(bytes);
if (packet != null) {
_buf.clear();
if (packet.used < bytes.length) {
_buf.add(Uint8List.sublistView(bytes, packet.used));
}
return packet.payload;
}
final left = deadline.difference(DateTime.now());
if (left <= Duration.zero) {
return null;
}
final waiter = Completer<void>();
_pending = waiter;
if (takeMcPacket(_buf.toBytes()) != null) {
waiter.complete();
}
try {
await waiter.future.timeout(left);
} on TimeoutException {
return null;
}
}
}
}
+75
View File
@@ -0,0 +1,75 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/protocol/probe_packet.dart';
void main() {
test('golden request matches the server fixture', () {
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: 1,
clientSendUnixNano: 1000,
payload: Uint8List.fromList([1, 2, 3, 4]),
);
final hex = packet
.encode()
.map((byte) => byte.toRadixString(16).padLeft(2, '0'))
.join();
expect(
hex,
'4e5130310101000001000000e803000000000000'
'0000000000000000000000000000000000000000'
'0000000000000000000000000000000000000000'
'040001020304',
);
final back = ProbePacket.decode(packet.encode());
expect(back.sequence, 1);
expect(back.clientSendUnixNano, 1000);
expect(back.type, ProbePacket.typeRequest);
expect(back.payload, [1, 2, 3, 4]);
});
test('token is zero padded in the header', () {
final token = ProbePacket.encodeToken('demo');
expect(token, hasLength(32));
expect(token.sublist(0, 4), [0x64, 0x65, 0x6d, 0x6f]);
expect(token.sublist(4), everyElement(0));
expect(() => ProbePacket.encodeToken('x' * 33), throwsA(isA<ProbePacketException>()));
});
test('frame buffer splits partial and concatenated TCP frames', () {
final packet = ProbePacket(
type: ProbePacket.typeReply,
sequence: 9,
clientSendUnixNano: 50,
serverUnixNano: 80,
payload: Uint8List.fromList([9, 8, 7]),
).encode();
final buffer = FrameBuffer();
expect(buffer.add(packet.sublist(0, 20)), isEmpty);
expect(buffer.add(packet.sublist(20, 40)), isEmpty);
final one = buffer.add(packet.sublist(40));
expect(one, hasLength(1));
expect(ProbePacket.decode(one.single).sequence, 9);
expect(ProbePacket.decode(one.single).serverUnixNano, 80);
final both = Uint8List.fromList([...packet, ...packet]);
final two = FrameBuffer().add(both);
expect(two, hasLength(2));
expect(ProbePacket.decode(two[1]).payload, [9, 8, 7]);
});
test('rejects a short or trailing datagram', () {
final packet = ProbePacket(
type: ProbePacket.typeRequest,
sequence: 1,
clientSendUnixNano: 1,
).encode();
expect(
() => ProbePacket.decode(Uint8List.sublistView(packet, 0, 10)),
throwsA(isA<ProbePacketException>()),
);
final extra = Uint8List(packet.length + 1)..setRange(0, packet.length, packet);
expect(() => ProbePacket.decode(extra), throwsA(isA<ProbePacketException>()));
});
}
+96
View File
@@ -0,0 +1,96 @@
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/metrics/sample_book.dart';
import 'package:netquality/models/session_config.dart';
import 'package:netquality/probe/game_codec.dart';
import 'package:netquality/probe/remote_client.dart';
void main() {
test('pending work is not a rate, and connect failure is not probe loss', () {
final book = SampleBook('nq-tcp');
expect(book.summary().probeLossPct, isNull);
expect(book.summary().completed, 0);
book.add(
const Outcome(status: Outcome.refused, kind: Outcome.connect, reconnect: true),
);
expect(book.summary().probeLossPct, isNull);
expect(book.summary().reconnects, 1);
book.add(const Outcome(status: Outcome.timeout, kind: Outcome.probe));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 2));
book.add(const Outcome(status: Outcome.ok, kind: Outcome.probe, rttMs: 1.5));
expect(book.summary().probeLossPct, 25);
expect(book.summary().jitterMs, closeTo(0.08984375, 0.000001));
});
test('generic udp silence is unknown, not loss', () {
final book = SampleBook('udp-generic');
book.add(const Outcome(status: Outcome.unknown, kind: Outcome.query));
final summary = book.summary();
expect(summary.probeLossPct, isNull);
expect(summary.unknownPct, 100);
});
test('node url rejects embedded secrets and job body keeps tokens apart', () {
expect(normalizeNodeUrl('https://user:secret@probe.example/node'), isNull);
expect(
normalizeNodeUrl('https://probe.example:8443/nq?token=secret'),
'https://probe.example:8443/nq',
);
expect(normalizeNodeUrl('http://127.0.0.1:8443'), 'http://127.0.0.1:8443');
const body = ProbeBody(
target: '203.0.113.10',
port: 19090,
profile: 'nq-tcp',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 30,
packetSize: 128,
echoToken: 'echo-secret',
dnsName: '',
payloadHex: '',
expectHex: '',
);
final json = body.toJson();
expect(json.containsKey('nodeToken'), isFalse);
expect(json['echoToken'], 'echo-secret');
expect(jsonEncodeContainsToken(json), isFalse);
});
test('minecraft and raknet builders match the protocol', () {
final handshake = javaHandshake('127.0.0.1', 25565);
expect(handshake.sublist(2, 4), [0xff, 0x05]);
final status = minecraftStatusDetail(
'{"version":{"name":"1.21.1"},"players":{"online":3,"max":20},"description":{"text":"Hello","extra":[{"text":"!"}]}}',
);
expect(status['motd'], 'Hello!');
expect(status['version'], '1.21.1');
expect(status['players'], '3/20');
const motd = 'MCPE;Bed;844;1.21.50;1;10;0;';
final pong = Uint8List.fromList([
0x1c,
0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88,
0, 0, 0, 0, 0, 0, 0, 99,
...rakMagic,
0, motd.length,
...motd.codeUnits,
]);
final detail = parseRakPong(pong, 0x1122334455667788);
expect(detail?['motd'], 'Bed');
expect(detail?['version'], '1.21.50');
expect(detail?['players'], '1/10');
final bad = Uint8List.fromList(pong);
bad[17] = 0x11;
expect(parseRakPong(bad, 0x1122334455667788), isNull);
final query = dnsQuery(7, 'example.com');
expect(query[0], 0);
expect(query[1], 7);
expect((query[2] & 0x80), 0);
});
}
bool jsonEncodeContainsToken(Map<String, Object?> json) {
return json.keys.contains('nodeToken') || json.values.contains('node-control-secret');
}
+50
View File
@@ -0,0 +1,50 @@
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:netquality/main.dart';
import 'package:netquality/models/session_config.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
testWidgets('opens on local source with an empty chart', (tester) async {
SharedPreferences.setMockInitialValues({});
tester.view.physicalSize = const Size(1280, 1400);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
await tester.pumpWidget(const NetQualityApp());
await tester.pumpAndSettle();
expect(find.text('网络质量探测'), findsOneWidget);
expect(find.text('探测来源'), findsOneWidget);
expect(find.text('本机'), findsWidgets);
expect(find.text('远程节点'), findsWidgets);
expect(find.text('开始探测'), findsOneWidget);
expect(find.text('暂无已完成的探测'), findsNWidgets(2));
expect(find.textContaining('127.0.0.1'), findsWidgets);
});
test('settings round trip keeps the node and drops nothing secret into json keys', () {
const config = SessionConfig(
remote: true,
nodeId: 'n1',
nodes: [RemoteNode(id: 'n1', name: '机房', baseUrl: 'https://probe.example:8443')],
host: '203.0.113.8',
port: 25565,
profileId: 'minecraft-java',
intervalMs: 300,
timeoutMs: 1000,
durationSec: 60,
packetSize: 128,
dnsName: 'example.com',
payloadHex: '',
expectHex: '',
);
final again = SessionConfig.fromJson(config.toJson());
expect(again.host, '203.0.113.8');
expect(again.profileId, 'minecraft-java');
expect(again.node?.name, '机房');
expect(again.toJson().containsKey('token'), isFalse);
expect(again.toJson().containsKey('nodeToken'), isFalse);
expect(SessionConfig.defaults.validate(), isNull);
});
}
+17
View File
@@ -0,0 +1,17 @@
flutter/ephemeral/
# Visual Studio user-specific files.
*.suo
*.user
*.userosscache
*.sln.docstates
# Visual Studio build-related files.
x64/
x86/
# Visual Studio cache files
# files ending in .cache can be ignored
*.[Cc]ache
# but keep track of directories ending in .cache
!*.[Cc]ache/
+108
View File
@@ -0,0 +1,108 @@
# Project-level configuration.
cmake_minimum_required(VERSION 3.14)
project(netquality LANGUAGES CXX)
# The name of the executable created for the application. Change this to change
# the on-disk name of your application.
set(BINARY_NAME "netquality")
# Explicitly opt in to modern CMake behaviors to avoid warnings with recent
# versions of CMake.
cmake_policy(VERSION 3.14...3.25)
# Define build configuration option.
get_property(IS_MULTICONFIG GLOBAL PROPERTY GENERATOR_IS_MULTI_CONFIG)
if(IS_MULTICONFIG)
set(CMAKE_CONFIGURATION_TYPES "Debug;Profile;Release"
CACHE STRING "" FORCE)
else()
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
set(CMAKE_BUILD_TYPE "Debug" CACHE
STRING "Flutter build mode" FORCE)
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS
"Debug" "Profile" "Release")
endif()
endif()
# Define settings for the Profile build mode.
set(CMAKE_EXE_LINKER_FLAGS_PROFILE "${CMAKE_EXE_LINKER_FLAGS_RELEASE}")
set(CMAKE_SHARED_LINKER_FLAGS_PROFILE "${CMAKE_SHARED_LINKER_FLAGS_RELEASE}")
set(CMAKE_C_FLAGS_PROFILE "${CMAKE_C_FLAGS_RELEASE}")
set(CMAKE_CXX_FLAGS_PROFILE "${CMAKE_CXX_FLAGS_RELEASE}")
# Use Unicode for all projects.
add_definitions(-DUNICODE -D_UNICODE)
# Compilation settings that should be applied to most targets.
#
# Be cautious about adding new options here, as plugins use this function by
# default. In most cases, you should add new options to specific targets instead
# of modifying this function.
function(APPLY_STANDARD_SETTINGS TARGET)
target_compile_features(${TARGET} PUBLIC cxx_std_17)
target_compile_options(${TARGET} PRIVATE /W4 /WX /wd"4100")
target_compile_options(${TARGET} PRIVATE /EHsc)
target_compile_definitions(${TARGET} PRIVATE "_HAS_EXCEPTIONS=0")
target_compile_definitions(${TARGET} PRIVATE "$<$<CONFIG:Debug>:_DEBUG>")
endfunction()
# Flutter library and tool build rules.
set(FLUTTER_MANAGED_DIR "${CMAKE_CURRENT_SOURCE_DIR}/flutter")
add_subdirectory(${FLUTTER_MANAGED_DIR})
# Application build; see runner/CMakeLists.txt.
add_subdirectory("runner")
# Generated plugin build rules, which manage building the plugins and adding
# them to the application.
include(flutter/generated_plugins.cmake)
# === Installation ===
# Support files are copied into place next to the executable, so that it can
# run in place. This is done instead of making a separate bundle (as on Linux)
# so that building and running from within Visual Studio will work.
set(BUILD_BUNDLE_DIR "$<TARGET_FILE_DIR:${BINARY_NAME}>")
# Make the "install" step default, as it's required to run.
set(CMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD 1)
if(CMAKE_INSTALL_PREFIX_INITIALIZED_TO_DEFAULT)
set(CMAKE_INSTALL_PREFIX "${BUILD_BUNDLE_DIR}" CACHE PATH "..." FORCE)
endif()
set(INSTALL_BUNDLE_DATA_DIR "${CMAKE_INSTALL_PREFIX}/data")
set(INSTALL_BUNDLE_LIB_DIR "${CMAKE_INSTALL_PREFIX}")
install(TARGETS ${BINARY_NAME} RUNTIME DESTINATION "${CMAKE_INSTALL_PREFIX}"
COMPONENT Runtime)
install(FILES "${FLUTTER_ICU_DATA_FILE}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
COMPONENT Runtime)
install(FILES "${FLUTTER_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
if(PLUGIN_BUNDLED_LIBRARIES)
install(FILES "${PLUGIN_BUNDLED_LIBRARIES}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
endif()
# Copy the native assets provided by the build.dart from all packages.
set(NATIVE_ASSETS_DIR "${PROJECT_BUILD_DIR}native_assets/windows/")
install(DIRECTORY "${NATIVE_ASSETS_DIR}"
DESTINATION "${INSTALL_BUNDLE_LIB_DIR}"
COMPONENT Runtime)
# Fully re-copy the assets directory on each build to avoid having stale files
# from a previous install.
set(FLUTTER_ASSET_DIR_NAME "flutter_assets")
install(CODE "
file(REMOVE_RECURSE \"${INSTALL_BUNDLE_DATA_DIR}/${FLUTTER_ASSET_DIR_NAME}\")
" COMPONENT Runtime)
install(DIRECTORY "${PROJECT_BUILD_DIR}/${FLUTTER_ASSET_DIR_NAME}"
DESTINATION "${INSTALL_BUNDLE_DATA_DIR}" COMPONENT Runtime)
# Install the AOT library on non-Debug builds only.
install(FILES "${AOT_LIBRARY}" DESTINATION "${INSTALL_BUNDLE_DATA_DIR}"
CONFIGURATIONS Profile;Release
COMPONENT Runtime)
+109
View File
@@ -0,0 +1,109 @@
# This file controls Flutter-level build steps. It should not be edited.
cmake_minimum_required(VERSION 3.14)
set(EPHEMERAL_DIR "${CMAKE_CURRENT_SOURCE_DIR}/ephemeral")
# Configuration provided via flutter tool.
include(${EPHEMERAL_DIR}/generated_config.cmake)
# TODO: Move the rest of this into files in ephemeral. See
# https://github.com/flutter/flutter/issues/57146.
set(WRAPPER_ROOT "${EPHEMERAL_DIR}/cpp_client_wrapper")
# Set fallback configurations for older versions of the flutter tool.
if (NOT DEFINED FLUTTER_TARGET_PLATFORM)
set(FLUTTER_TARGET_PLATFORM "windows-x64")
endif()
# === Flutter Library ===
set(FLUTTER_LIBRARY "${EPHEMERAL_DIR}/flutter_windows.dll")
# Published to parent scope for install step.
set(FLUTTER_LIBRARY ${FLUTTER_LIBRARY} PARENT_SCOPE)
set(FLUTTER_ICU_DATA_FILE "${EPHEMERAL_DIR}/icudtl.dat" PARENT_SCOPE)
set(PROJECT_BUILD_DIR "${PROJECT_DIR}/build/" PARENT_SCOPE)
set(AOT_LIBRARY "${PROJECT_DIR}/build/windows/app.so" PARENT_SCOPE)
list(APPEND FLUTTER_LIBRARY_HEADERS
"flutter_export.h"
"flutter_windows.h"
"flutter_messenger.h"
"flutter_plugin_registrar.h"
"flutter_texture_registrar.h"
)
list(TRANSFORM FLUTTER_LIBRARY_HEADERS PREPEND "${EPHEMERAL_DIR}/")
add_library(flutter INTERFACE)
target_include_directories(flutter INTERFACE
"${EPHEMERAL_DIR}"
)
target_link_libraries(flutter INTERFACE "${FLUTTER_LIBRARY}.lib")
add_dependencies(flutter flutter_assemble)
# === Wrapper ===
list(APPEND CPP_WRAPPER_SOURCES_CORE
"core_implementations.cc"
"standard_codec.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_CORE PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_PLUGIN
"plugin_registrar.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_PLUGIN PREPEND "${WRAPPER_ROOT}/")
list(APPEND CPP_WRAPPER_SOURCES_APP
"flutter_engine.cc"
"flutter_view_controller.cc"
)
list(TRANSFORM CPP_WRAPPER_SOURCES_APP PREPEND "${WRAPPER_ROOT}/")
# Wrapper sources needed for a plugin.
add_library(flutter_wrapper_plugin STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
)
apply_standard_settings(flutter_wrapper_plugin)
set_target_properties(flutter_wrapper_plugin PROPERTIES
POSITION_INDEPENDENT_CODE ON)
set_target_properties(flutter_wrapper_plugin PROPERTIES
CXX_VISIBILITY_PRESET hidden)
target_link_libraries(flutter_wrapper_plugin PUBLIC flutter)
target_include_directories(flutter_wrapper_plugin PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_plugin flutter_assemble)
# Wrapper sources needed for the runner.
add_library(flutter_wrapper_app STATIC
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_APP}
)
apply_standard_settings(flutter_wrapper_app)
target_link_libraries(flutter_wrapper_app PUBLIC flutter)
target_include_directories(flutter_wrapper_app PUBLIC
"${WRAPPER_ROOT}/include"
)
add_dependencies(flutter_wrapper_app flutter_assemble)
# === Flutter tool backend ===
# _phony_ is a non-existent file to force this command to run every time,
# since currently there's no way to get a full input/output list from the
# flutter tool.
set(PHONY_OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/_phony_")
set_source_files_properties("${PHONY_OUTPUT}" PROPERTIES SYMBOLIC TRUE)
add_custom_command(
OUTPUT ${FLUTTER_LIBRARY} ${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE} ${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
${PHONY_OUTPUT}
COMMAND ${CMAKE_COMMAND} -E env
${FLUTTER_TOOL_ENVIRONMENT}
"${FLUTTER_ROOT}/packages/flutter_tools/bin/tool_backend.bat"
${FLUTTER_TARGET_PLATFORM} $<CONFIG>
VERBATIM
)
add_custom_target(flutter_assemble DEPENDS
"${FLUTTER_LIBRARY}"
${FLUTTER_LIBRARY_HEADERS}
${CPP_WRAPPER_SOURCES_CORE}
${CPP_WRAPPER_SOURCES_PLUGIN}
${CPP_WRAPPER_SOURCES_APP}
)
@@ -0,0 +1,11 @@
//
// Generated file. Do not edit.
//
// clang-format off
#include "generated_plugin_registrant.h"
void RegisterPlugins(flutter::PluginRegistry* registry) {
}
@@ -0,0 +1,15 @@
//
// Generated file. Do not edit.
//
// clang-format off
#ifndef GENERATED_PLUGIN_REGISTRANT_
#define GENERATED_PLUGIN_REGISTRANT_
#include <flutter/plugin_registry.h>
// Registers Flutter plugins.
void RegisterPlugins(flutter::PluginRegistry* registry);
#endif // GENERATED_PLUGIN_REGISTRANT_
@@ -0,0 +1,24 @@
#
# Generated file, do not edit.
#
list(APPEND FLUTTER_PLUGIN_LIST
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST
jni
)
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 $<TARGET_FILE:${plugin}_plugin>)
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)
+40
View File
@@ -0,0 +1,40 @@
cmake_minimum_required(VERSION 3.14)
project(runner LANGUAGES CXX)
# Define the application target. To change its name, change BINARY_NAME in the
# top-level CMakeLists.txt, not the value here, or `flutter run` will no longer
# work.
#
# Any new source files that you add to the application should be added here.
add_executable(${BINARY_NAME} WIN32
"flutter_window.cpp"
"main.cpp"
"utils.cpp"
"win32_window.cpp"
"${FLUTTER_MANAGED_DIR}/generated_plugin_registrant.cc"
"Runner.rc"
"runner.exe.manifest"
)
# Apply the standard set of build settings. This can be removed for applications
# that need different build settings.
apply_standard_settings(${BINARY_NAME})
# Add preprocessor definitions for the build version.
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION=\"${FLUTTER_VERSION}\"")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MAJOR=${FLUTTER_VERSION_MAJOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_MINOR=${FLUTTER_VERSION_MINOR}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_PATCH=${FLUTTER_VERSION_PATCH}")
target_compile_definitions(${BINARY_NAME} PRIVATE "FLUTTER_VERSION_BUILD=${FLUTTER_VERSION_BUILD}")
# Disable Windows macros that collide with C++ standard library functions.
target_compile_definitions(${BINARY_NAME} PRIVATE "NOMINMAX")
# Add dependency libraries and include directories. Add any application-specific
# dependencies here.
target_link_libraries(${BINARY_NAME} PRIVATE flutter flutter_wrapper_app)
target_link_libraries(${BINARY_NAME} PRIVATE "dwmapi.lib")
target_include_directories(${BINARY_NAME} PRIVATE "${CMAKE_SOURCE_DIR}")
# Run the Flutter tool portions of the build. This must not be removed.
add_dependencies(${BINARY_NAME} flutter_assemble)
+121
View File
@@ -0,0 +1,121 @@
// Microsoft Visual C++ generated resource script.
//
#pragma code_page(65001)
#include "resource.h"
#define APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
//
// Generated from the TEXTINCLUDE 2 resource.
//
#include "winres.h"
/////////////////////////////////////////////////////////////////////////////
#undef APSTUDIO_READONLY_SYMBOLS
/////////////////////////////////////////////////////////////////////////////
// English (United States) resources
#if !defined(AFX_RESOURCE_DLL) || defined(AFX_TARG_ENU)
LANGUAGE LANG_ENGLISH, SUBLANG_ENGLISH_US
#ifdef APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// TEXTINCLUDE
//
1 TEXTINCLUDE
BEGIN
"resource.h\0"
END
2 TEXTINCLUDE
BEGIN
"#include ""winres.h""\r\n"
"\0"
END
3 TEXTINCLUDE
BEGIN
"\r\n"
"\0"
END
#endif // APSTUDIO_INVOKED
/////////////////////////////////////////////////////////////////////////////
//
// Icon
//
// Icon with lowest ID value placed first to ensure application icon
// remains consistent on all systems.
IDI_APP_ICON ICON "resources\\app_icon.ico"
/////////////////////////////////////////////////////////////////////////////
//
// Version
//
#if defined(FLUTTER_VERSION_MAJOR) && defined(FLUTTER_VERSION_MINOR) && defined(FLUTTER_VERSION_PATCH) && defined(FLUTTER_VERSION_BUILD)
#define VERSION_AS_NUMBER FLUTTER_VERSION_MAJOR,FLUTTER_VERSION_MINOR,FLUTTER_VERSION_PATCH,FLUTTER_VERSION_BUILD
#else
#define VERSION_AS_NUMBER 1,0,0,0
#endif
#if defined(FLUTTER_VERSION)
#define VERSION_AS_STRING FLUTTER_VERSION
#else
#define VERSION_AS_STRING "1.0.0"
#endif
VS_VERSION_INFO VERSIONINFO
FILEVERSION VERSION_AS_NUMBER
PRODUCTVERSION VERSION_AS_NUMBER
FILEFLAGSMASK VS_FFI_FILEFLAGSMASK
#ifdef _DEBUG
FILEFLAGS VS_FF_DEBUG
#else
FILEFLAGS 0x0L
#endif
FILEOS VOS__WINDOWS32
FILETYPE VFT_APP
FILESUBTYPE 0x0L
BEGIN
BLOCK "StringFileInfo"
BEGIN
BLOCK "040904e4"
BEGIN
VALUE "CompanyName", "dev.netquality" "\0"
VALUE "FileDescription", "netquality" "\0"
VALUE "FileVersion", VERSION_AS_STRING "\0"
VALUE "InternalName", "netquality" "\0"
VALUE "LegalCopyright", "Copyright (C) 2026 dev.netquality. All rights reserved." "\0"
VALUE "OriginalFilename", "netquality.exe" "\0"
VALUE "ProductName", "netquality" "\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
+71
View File
@@ -0,0 +1,71 @@
#include "flutter_window.h"
#include <optional>
#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<flutter::FlutterViewController>(
frame.right - frame.left, frame.bottom - frame.top, project_);
// Ensure that basic setup of the controller was successful.
if (!flutter_controller_->engine() || !flutter_controller_->view()) {
return false;
}
RegisterPlugins(flutter_controller_->engine());
SetChildContent(flutter_controller_->view()->GetNativeWindow());
flutter_controller_->engine()->SetNextFrameCallback([&]() {
this->Show();
});
// Flutter can complete the first frame before the "show window" callback is
// registered. The following call ensures a frame is pending to ensure the
// window is shown. It is a no-op if the first frame hasn't completed yet.
flutter_controller_->ForceRedraw();
return true;
}
void FlutterWindow::OnDestroy() {
if (flutter_controller_) {
flutter_controller_ = nullptr;
}
Win32Window::OnDestroy();
}
LRESULT
FlutterWindow::MessageHandler(HWND hwnd, UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
// Give Flutter, including plugins, an opportunity to handle window messages.
if (flutter_controller_) {
std::optional<LRESULT> 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);
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef RUNNER_FLUTTER_WINDOW_H_
#define RUNNER_FLUTTER_WINDOW_H_
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <memory>
#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::FlutterViewController> flutter_controller_;
};
#endif // RUNNER_FLUTTER_WINDOW_H_
+43
View File
@@ -0,0 +1,43 @@
#include <flutter/dart_project.h>
#include <flutter/flutter_view_controller.h>
#include <windows.h>
#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<std::string> command_line_arguments =
GetCommandLineArguments();
project.set_dart_entrypoint_arguments(std::move(command_line_arguments));
FlutterWindow window(project);
Win32Window::Point origin(10, 10);
Win32Window::Size size(1280, 720);
if (!window.Create(L"\x7f51\x7edc\x8d28\x91cf\x63a2\x6d4b", origin, size)) {
return EXIT_FAILURE;
}
window.SetQuitOnClose(true);
::MSG msg;
while (::GetMessage(&msg, nullptr, 0, 0)) {
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
::CoUninitialize();
return EXIT_SUCCESS;
}
+16
View File
@@ -0,0 +1,16 @@
//{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by Runner.rc
//
#define IDI_APP_ICON 101
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 102
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1001
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
Binary file not shown.

After

Width:  |  Height:  |  Size: 33 KiB

+14
View File
@@ -0,0 +1,14 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
</windowsSettings>
</application>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- Windows 10 and Windows 11 -->
<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/>
</application>
</compatibility>
</assembly>
+69
View File
@@ -0,0 +1,69 @@
#include "utils.h"
#include <flutter_windows.h>
#include <io.h>
#include <stdio.h>
#include <windows.h>
#include <iostream>
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<std::string> 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::string>();
}
std::vector<std::string> 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();
}
// First, find the length of the string with a safe upper bound (CWE-126).
// UNICODE_STRING_MAX_CHARS (32767) is the maximum length of a UNICODE_STRING.
int input_length = static_cast<int>(wcsnlen(utf16_string, UNICODE_STRING_MAX_CHARS));
// Now use that bounded length to determine the required buffer size.
// When an explicit length is passed, WideCharToMultiByte does not include
// the null terminator in its returned size.
int target_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, nullptr, 0, nullptr, nullptr);
std::string utf8_string;
if (target_length == 0 || static_cast<size_t>(target_length) > utf8_string.max_size()) {
return utf8_string;
}
utf8_string.resize(target_length);
int converted_length = ::WideCharToMultiByte(
CP_UTF8, WC_ERR_INVALID_CHARS, utf16_string,
input_length, utf8_string.data(), target_length, nullptr, nullptr);
if (converted_length == 0) {
return std::string();
}
return utf8_string;
}
+19
View File
@@ -0,0 +1,19 @@
#ifndef RUNNER_UTILS_H_
#define RUNNER_UTILS_H_
#include <string>
#include <vector>
// 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<std::string>,
// encoded in UTF-8. Returns an empty std::vector<std::string> on failure.
std::vector<std::string> GetCommandLineArguments();
#endif // RUNNER_UTILS_H_
+288
View File
@@ -0,0 +1,288 @@
#include "win32_window.h"
#include <dwmapi.h>
#include <flutter_windows.h>
#include "resource.h"
namespace {
/// Window attribute that enables dark mode window decorations.
///
/// Redefined in case the developer's machine has a Windows SDK older than
/// version 10.0.22000.0.
/// See: https://docs.microsoft.com/windows/win32/api/dwmapi/ne-dwmapi-dwmwindowattribute
#ifndef DWMWA_USE_IMMERSIVE_DARK_MODE
#define DWMWA_USE_IMMERSIVE_DARK_MODE 20
#endif
constexpr const wchar_t kWindowClassName[] = L"FLUTTER_RUNNER_WIN32_WINDOW";
/// Registry key for app theme preference.
///
/// A value of 0 indicates apps should use dark mode. A non-zero or missing
/// value indicates apps should use light mode.
constexpr const wchar_t kGetPreferredBrightnessRegKey[] =
L"Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize";
constexpr const wchar_t kGetPreferredBrightnessRegValue[] = L"AppsUseLightTheme";
// The number of Win32Window objects that currently exist.
static int g_active_window_count = 0;
using EnableNonClientDpiScaling = BOOL __stdcall(HWND hwnd);
// Scale helper to convert logical scaler values to physical using passed in
// scale factor
int Scale(int source, double scale_factor) {
return static_cast<int>(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<EnableNonClientDpiScaling*>(
GetProcAddress(user32_module, "EnableNonClientDpiScaling"));
if (enable_non_client_dpi_scaling != nullptr) {
enable_non_client_dpi_scaling(hwnd);
}
FreeLibrary(user32_module);
}
} // namespace
// Manages the Win32Window's window class registration.
class WindowClassRegistrar {
public:
~WindowClassRegistrar() = default;
// Returns the singleton registrar instance.
static WindowClassRegistrar* GetInstance() {
if (!instance_) {
instance_ = new WindowClassRegistrar();
}
return instance_;
}
// Returns the name of the window class, registering the class if it hasn't
// previously been registered.
const wchar_t* GetWindowClass();
// Unregisters the window class. Should only be called if there are no
// instances of the window.
void UnregisterWindowClass();
private:
WindowClassRegistrar() = default;
static WindowClassRegistrar* instance_;
bool class_registered_ = false;
};
WindowClassRegistrar* WindowClassRegistrar::instance_ = nullptr;
const wchar_t* WindowClassRegistrar::GetWindowClass() {
if (!class_registered_) {
WNDCLASS window_class{};
window_class.hCursor = LoadCursor(nullptr, IDC_ARROW);
window_class.lpszClassName = kWindowClassName;
window_class.style = CS_HREDRAW | CS_VREDRAW;
window_class.cbClsExtra = 0;
window_class.cbWndExtra = 0;
window_class.hInstance = GetModuleHandle(nullptr);
window_class.hIcon =
LoadIcon(window_class.hInstance, MAKEINTRESOURCE(IDI_APP_ICON));
window_class.hbrBackground = 0;
window_class.lpszMenuName = nullptr;
window_class.lpfnWndProc = Win32Window::WndProc;
RegisterClass(&window_class);
class_registered_ = true;
}
return kWindowClassName;
}
void WindowClassRegistrar::UnregisterWindowClass() {
UnregisterClass(kWindowClassName, nullptr);
class_registered_ = false;
}
Win32Window::Win32Window() {
++g_active_window_count;
}
Win32Window::~Win32Window() {
--g_active_window_count;
Destroy();
}
bool Win32Window::Create(const std::wstring& title,
const Point& origin,
const Size& size) {
Destroy();
const wchar_t* window_class =
WindowClassRegistrar::GetInstance()->GetWindowClass();
const POINT target_point = {static_cast<LONG>(origin.x),
static_cast<LONG>(origin.y)};
HMONITOR monitor = MonitorFromPoint(target_point, MONITOR_DEFAULTTONEAREST);
UINT dpi = FlutterDesktopGetDpiForMonitor(monitor);
double scale_factor = dpi / 96.0;
HWND window = CreateWindow(
window_class, title.c_str(), WS_OVERLAPPEDWINDOW,
Scale(origin.x, scale_factor), Scale(origin.y, scale_factor),
Scale(size.width, scale_factor), Scale(size.height, scale_factor),
nullptr, nullptr, GetModuleHandle(nullptr), this);
if (!window) {
return false;
}
UpdateTheme(window);
return OnCreate();
}
bool Win32Window::Show() {
return ShowWindow(window_handle_, SW_SHOWNORMAL);
}
// static
LRESULT CALLBACK Win32Window::WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept {
if (message == WM_NCCREATE) {
auto window_struct = reinterpret_cast<CREATESTRUCT*>(lparam);
SetWindowLongPtr(window, GWLP_USERDATA,
reinterpret_cast<LONG_PTR>(window_struct->lpCreateParams));
auto that = static_cast<Win32Window*>(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<RECT*>(lparam);
LONG newWidth = newRectSize->right - newRectSize->left;
LONG newHeight = newRectSize->bottom - newRectSize->top;
SetWindowPos(hwnd, nullptr, newRectSize->left, newRectSize->top, newWidth,
newHeight, SWP_NOZORDER | SWP_NOACTIVATE);
return 0;
}
case WM_SIZE: {
RECT rect = GetClientArea();
if (child_content_ != nullptr) {
// Size and position the child window.
MoveWindow(child_content_, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, TRUE);
}
return 0;
}
case WM_ACTIVATE:
if (child_content_ != nullptr) {
SetFocus(child_content_);
}
return 0;
case WM_DWMCOLORIZATIONCOLORCHANGED:
UpdateTheme(hwnd);
return 0;
}
return DefWindowProc(window_handle_, message, wparam, lparam);
}
void Win32Window::Destroy() {
OnDestroy();
if (window_handle_) {
DestroyWindow(window_handle_);
window_handle_ = nullptr;
}
if (g_active_window_count == 0) {
WindowClassRegistrar::GetInstance()->UnregisterWindowClass();
}
}
Win32Window* Win32Window::GetThisFromHandle(HWND const window) noexcept {
return reinterpret_cast<Win32Window*>(
GetWindowLongPtr(window, GWLP_USERDATA));
}
void Win32Window::SetChildContent(HWND content) {
child_content_ = content;
SetParent(content, window_handle_);
RECT frame = GetClientArea();
MoveWindow(content, frame.left, frame.top, frame.right - frame.left,
frame.bottom - frame.top, true);
SetFocus(child_content_);
}
RECT Win32Window::GetClientArea() {
RECT frame;
GetClientRect(window_handle_, &frame);
return frame;
}
HWND Win32Window::GetHandle() {
return window_handle_;
}
void Win32Window::SetQuitOnClose(bool quit_on_close) {
quit_on_close_ = quit_on_close;
}
bool Win32Window::OnCreate() {
// No-op; provided for subclasses.
return true;
}
void Win32Window::OnDestroy() {
// No-op; provided for subclasses.
}
void Win32Window::UpdateTheme(HWND const window) {
DWORD light_mode;
DWORD light_mode_size = sizeof(light_mode);
LSTATUS result = RegGetValue(HKEY_CURRENT_USER, kGetPreferredBrightnessRegKey,
kGetPreferredBrightnessRegValue,
RRF_RT_REG_DWORD, nullptr, &light_mode,
&light_mode_size);
if (result == ERROR_SUCCESS) {
BOOL enable_dark_mode = light_mode == 0;
DwmSetWindowAttribute(window, DWMWA_USE_IMMERSIVE_DARK_MODE,
&enable_dark_mode, sizeof(enable_dark_mode));
}
}
+102
View File
@@ -0,0 +1,102 @@
#ifndef RUNNER_WIN32_WINDOW_H_
#define RUNNER_WIN32_WINDOW_H_
#include <windows.h>
#include <functional>
#include <memory>
#include <string>
// A class abstraction for a high DPI-aware Win32 Window. Intended to be
// inherited from by classes that wish to specialize with custom
// rendering and input handling
class Win32Window {
public:
struct Point {
unsigned int x;
unsigned int y;
Point(unsigned int x, unsigned int y) : x(x), y(y) {}
};
struct Size {
unsigned int width;
unsigned int height;
Size(unsigned int width, unsigned int height)
: width(width), height(height) {}
};
Win32Window();
virtual ~Win32Window();
// Creates a win32 window with |title| that is positioned and sized using
// |origin| and |size|. New windows are created on the default monitor. Window
// sizes are specified to the OS in physical pixels, hence to ensure a
// consistent size this function will scale the inputted width and height as
// as appropriate for the default monitor. The window is invisible until
// |Show| is called. Returns true if the window was created successfully.
bool Create(const std::wstring& title, const Point& origin, const Size& size);
// Show the current window. Returns true if the window was successfully shown.
bool Show();
// Release OS resources associated with window.
void Destroy();
// Inserts |content| into the window tree.
void SetChildContent(HWND content);
// Returns the backing Window handle to enable clients to set icon and other
// window properties. Returns nullptr if the window has been destroyed.
HWND GetHandle();
// If true, closing this window will quit the application.
void SetQuitOnClose(bool quit_on_close);
// Return a RECT representing the bounds of the current client area.
RECT GetClientArea();
protected:
// Processes and route salient window messages for mouse handling,
// size change and DPI. Delegates handling of these to member overloads that
// inheriting classes can handle.
virtual LRESULT MessageHandler(HWND window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Called when CreateAndShow is called, allowing subclass window-related
// setup. Subclasses should return false if setup fails.
virtual bool OnCreate();
// Called when Destroy is called.
virtual void OnDestroy();
private:
friend class WindowClassRegistrar;
// OS callback called by message pump. Handles the WM_NCCREATE message which
// is passed when the non-client area is being created and enables automatic
// non-client DPI scaling so that the non-client area automatically
// responds to changes in DPI. All other messages are handled by
// MessageHandler.
static LRESULT CALLBACK WndProc(HWND const window,
UINT const message,
WPARAM const wparam,
LPARAM const lparam) noexcept;
// Retrieves a class instance pointer for |window|
static Win32Window* GetThisFromHandle(HWND const window) noexcept;
// Update the window frame's theme to match the system theme.
static void UpdateTheme(HWND const window);
bool quit_on_close_ = false;
// window handle for top level window.
HWND window_handle_ = nullptr;
// window handle for hosted content.
HWND child_content_ = nullptr;
};
#endif // RUNNER_WIN32_WINDOW_H_