Compare commits

..

1 Commits

Author SHA1 Message Date
chen08209
f10a8a189d Add rule override
Optimize more details
2025-04-05 20:47:43 +08:00
72 changed files with 1003 additions and 1811 deletions

View File

@@ -76,7 +76,7 @@ jobs:
run: flutter pub get
- name: Setup
run: dart setup.dart ${{ matrix.platform }} ${{ matrix.arch && format('--arch {0}', matrix.arch) }} ${{ env.IS_STABLE == 'true' && '--env stable' || '' }}
run: dart setup.dart ${{ matrix.platform }} ${{ matrix.arch && format('--arch {0}', matrix.arch) }} ${{ env.IS_STABLE == 'true' && format('--env stable') }}
- name: Upload
uses: actions/upload-artifact@v4
@@ -91,12 +91,12 @@ jobs:
steps:
- name: Checkout
uses: actions/checkout@v4
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
with:
fetch-depth: 0
ref: refs/heads/main
- name: Generate
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
run: |
tags=($(git tag --merged $(git rev-parse HEAD) --sort=-creatordate))
preTag=$(grep -oP '^## \K.*' CHANGELOG.md | head -n 1)
@@ -128,7 +128,7 @@ jobs:
cat NEW_CHANGELOG.md > CHANGELOG.md
- name: Commit
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
run: |
git add CHANGELOG.md
if ! git diff --cached --quiet; then
@@ -215,21 +215,21 @@ jobs:
sed "s|VERSION|$version|g" ./.github/release_template.md >> release.md
- name: Release
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
uses: softprops/action-gh-release@v2
with:
files: ./dist/*
body_path: './release.md'
- name: Create Fdroid Source Dir
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
run: |
mkdir -p ./tmp
cp ./dist/*android-arm64-v8a* ./tmp/ || true
echo "Files copied successfully"
- name: Push to fdroid repo
if: ${{ env.IS_STABLE == 'true' }}
if: ${{ env.IS_STABLE }}
uses: cpina/github-action-push-to-another-repository@v1.7.2
env:
SSH_DEPLOY_KEY: ${{ secrets.SSH_DEPLOY_KEY }}

2
.gitmodules vendored
View File

@@ -1,7 +1,7 @@
[submodule "core/Clash.Meta"]
path = core/Clash.Meta
url = git@github.com:chen08209/Clash.Meta.git
branch = FlClash
branch = FlClash-Alpha
[submodule "plugins/flutter_distributor"]
path = plugins/flutter_distributor
url = git@github.com:chen08209/flutter_distributor.git

View File

@@ -1,25 +1,3 @@
## v0.8.81
- Add rule override
- Update core
- Optimize more details
- Update changelog
## v0.8.80
- Optimize dashboard performance
- Fix some issues
- Fix unselected proxy group delay issues
- Fix asn url issues
- Update changelog
## v0.8.79
- Fix tab delay view issues

View File

@@ -1,8 +0,0 @@
android_arm64:
dart ./setup.dart android --arch arm64
macos_arm64:
dart ./setup.dart macos --arch arm64
android_arm64_core:
dart ./setup.dart android --arch arm64 --out core
macos_arm64_core:
dart ./setup.dart macos --arch arm64 --out core

View File

@@ -1,3 +1,5 @@
import com.android.build.gradle.tasks.MergeSourceSetFolders
plugins {
id "com.android.application"
id "kotlin-android"
@@ -32,6 +34,7 @@ def isRelease = defStoreFile.exists() && defStorePassword != null && defKeyAlias
android {
namespace "com.follow.clash"
compileSdkVersion 35
ndkVersion "27.1.12297006"
compileOptions {
sourceCompatibility JavaVersion.VERSION_17
@@ -45,7 +48,6 @@ android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
signingConfigs {
if (isRelease) {
release {
@@ -82,15 +84,31 @@ android {
}
}
tasks.register('copyNativeLibs', Copy) {
delete('src/main/jniLibs')
from('../../libclash/android')
into('src/main/jniLibs')
}
tasks.withType(MergeSourceSetFolders).configureEach {
dependsOn copyNativeLibs
}
flutter {
source '../..'
}
dependencies {
implementation project(":core")
implementation 'androidx.core:core-splashscreen:1.0.1'
implementation 'com.google.code.gson:gson:2.10.1'
implementation("com.android.tools.smali:smali-dexlib2:3.0.9") {
implementation 'com.google.code.gson:gson:2.10'
implementation("com.android.tools.smali:smali-dexlib2:3.0.7") {
exclude group: "com.google.guava", module: "guava"
}
}
}
afterEvaluate {
assembleDebug.dependsOn copyNativeLibs
assembleRelease.dependsOn copyNativeLibs
}

View File

@@ -1,17 +1,13 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools">
<!-- 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.
-->
<application
android:icon="@mipmap/ic_launcher"
android:label="FlClash Debug"
tools:replace="android:label">
<application android:label="FlClash Debug" tools:replace="android:label">
<service
android:name=".services.FlClashTileService"
android:label="FlClash Debug"
tools:replace="android:label"
tools:targetApi="24" />
android:name=".services.FlClashTileService"
android:label="FlClash Debug"
tools:replace="android:label">
</service>
</application>
</manifest>

View File

@@ -1,6 +1,5 @@
package com.follow.clash
import com.follow.clash.core.Core
import com.follow.clash.plugins.AppPlugin
import com.follow.clash.plugins.ServicePlugin
import com.follow.clash.plugins.TilePlugin

View File

@@ -52,6 +52,7 @@ data object ServicePlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
private fun handleDestroy() {
GlobalState.getCurrentVPNPlugin()?.handleStop()
GlobalState.destroyServiceEngine()
}
}

View File

@@ -14,9 +14,10 @@ import androidx.core.content.getSystemService
import com.follow.clash.FlClashApplication
import com.follow.clash.GlobalState
import com.follow.clash.RunState
import com.follow.clash.core.Core
import com.follow.clash.extensions.awaitResult
import com.follow.clash.extensions.getProtocol
import com.follow.clash.extensions.resolveDns
import com.follow.clash.models.Process
import com.follow.clash.models.StartForegroundParams
import com.follow.clash.models.VpnOptions
import com.follow.clash.services.BaseServiceInterface
@@ -39,12 +40,10 @@ import kotlin.concurrent.withLock
data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private lateinit var flutterMethodChannel: MethodChannel
private var flClashService: BaseServiceInterface? = null
private var options: VpnOptions? = null
private var isBind: Boolean = false
private lateinit var options: VpnOptions
private lateinit var scope: CoroutineScope
private var lastStartForegroundParams: StartForegroundParams? = null
private var timerJob: Job? = null
private val uidPageNameMap = mutableMapOf<Int, String>()
private val connectivity by lazy {
FlClashApplication.getAppContext().getSystemService<ConnectivityManager>()
@@ -52,7 +51,6 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
private val connection = object : ServiceConnection {
override fun onServiceConnected(className: ComponentName, service: IBinder) {
isBind = true
flClashService = when (service) {
is FlClashVpnService.LocalBinder -> service.getService()
is FlClashService.LocalBinder -> service.getService()
@@ -62,7 +60,6 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
override fun onServiceDisconnected(arg: ComponentName) {
isBind = false
flClashService = null
}
}
@@ -93,6 +90,62 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
result.success(true)
}
"setProtect" -> {
val fd = call.argument<Int>("fd")
if (fd != null && flClashService is FlClashVpnService) {
try {
(flClashService as FlClashVpnService).protect(fd)
result.success(true)
} catch (e: RuntimeException) {
result.success(false)
}
} else {
result.success(false)
}
}
"resolverProcess" -> {
val data = call.argument<String>("data")
val process = if (data != null) Gson().fromJson(
data, Process::class.java
) else null
val metadata = process?.metadata
if (metadata == null) {
result.success(null)
return
}
val protocol = metadata.getProtocol()
if (protocol == null) {
result.success(null)
return
}
scope.launch {
withContext(Dispatchers.Default) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
result.success(null)
return@withContext
}
val src = InetSocketAddress(metadata.sourceIP, metadata.sourcePort)
val dst = InetSocketAddress(
metadata.destinationIP.ifEmpty { metadata.host },
metadata.destinationPort
)
val uid = try {
connectivity?.getConnectionOwnerUid(protocol, src, dst)
} catch (_: Exception) {
null
}
if (uid == null || uid == -1) {
result.success(null)
return@withContext
}
val packages =
FlClashApplication.getAppContext().packageManager?.getPackagesForUid(uid)
result.success(packages?.first())
}
}
}
else -> {
result.notImplemented()
}
@@ -100,9 +153,6 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
fun handleStart(options: VpnOptions): Boolean {
if (options.enable != this.options?.enable) {
this.flClashService = null
}
this.options = options
when (options.enable) {
true -> handleStartVpn()
@@ -112,9 +162,10 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
private fun handleStartVpn() {
GlobalState.getCurrentAppPlugin()?.requestVpnPermission {
handleStartService()
}
GlobalState.getCurrentAppPlugin()
?.requestVpnPermission {
handleStartService()
}
}
fun requestGc() {
@@ -184,7 +235,6 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
}
private fun startForegroundJob() {
stopForegroundJob()
timerJob = CoroutineScope(Dispatchers.Main).launch {
while (isActive) {
startForeground()
@@ -206,58 +256,26 @@ data object VpnPlugin : FlutterPlugin, MethodChannel.MethodCallHandler {
GlobalState.runLock.withLock {
if (GlobalState.runState.value == RunState.START) return
GlobalState.runState.value = RunState.START
val fd = flClashService?.start(options!!)
Core.startTun(
fd = fd ?: 0,
protect = this::protect,
resolverProcess = this::resolverProcess,
val fd = flClashService?.start(options)
flutterMethodChannel.invokeMethod(
"started", fd
)
startForegroundJob()
startForegroundJob();
}
}
private fun protect(fd: Int): Boolean {
return (flClashService as? FlClashVpnService)?.protect(fd) == true
}
private fun resolverProcess(
protocol: Int,
source: InetSocketAddress,
target: InetSocketAddress,
uid: Int,
): String {
val nextUid = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
connectivity?.getConnectionOwnerUid(protocol, source, target) ?: -1
} else {
uid
}
if (nextUid == -1) {
return ""
}
if (!uidPageNameMap.containsKey(nextUid)) {
uidPageNameMap[nextUid] =
FlClashApplication.getAppContext().packageManager?.getPackagesForUid(nextUid)
?.first() ?: ""
}
return uidPageNameMap[nextUid] ?: ""
}
fun handleStop() {
GlobalState.runLock.withLock {
if (GlobalState.runState.value == RunState.STOP) return
GlobalState.runState.value = RunState.STOP
stopForegroundJob()
Core.stopTun()
flClashService?.stop()
GlobalState.handleTryDestroy()
}
}
private fun bindService() {
if (isBind) {
FlClashApplication.getAppContext().unbindService(connection)
}
val intent = when (options?.enable == true) {
val intent = when (options.enable) {
true -> Intent(FlClashApplication.getAppContext(), FlClashVpnService::class.java)
false -> Intent(FlClashApplication.getAppContext(), FlClashService::class.java)
}

View File

@@ -45,16 +45,9 @@ class FlClashVpnService : VpnService(), BaseServiceInterface {
addAddress(cidr.address, cidr.prefixLength)
val routeAddress = options.getIpv4RouteAddress()
if (routeAddress.isNotEmpty()) {
try {
routeAddress.forEach { i ->
Log.d(
"addRoute4",
"address: ${i.address} prefixLength:${i.prefixLength}"
)
addRoute(i.address, i.prefixLength)
}
} catch (_: Exception) {
addRoute("0.0.0.0", 0)
routeAddress.forEach { i ->
Log.d("addRoute4", "address: ${i.address} prefixLength:${i.prefixLength}")
addRoute(i.address, i.prefixLength)
}
} else {
addRoute("0.0.0.0", 0)
@@ -65,16 +58,9 @@ class FlClashVpnService : VpnService(), BaseServiceInterface {
addAddress(cidr.address, cidr.prefixLength)
val routeAddress = options.getIpv6RouteAddress()
if (routeAddress.isNotEmpty()) {
try {
routeAddress.forEach { i ->
Log.d(
"addRoute6",
"address: ${i.address} prefixLength:${i.prefixLength}"
)
addRoute(i.address, i.prefixLength)
}
} catch (_: Exception) {
addRoute("::", 0)
routeAddress.forEach { i ->
Log.d("addRoute6", "address: ${i.address} prefixLength:${i.prefixLength}")
addRoute(i.address, i.prefixLength)
}
} else {
addRoute("::", 0)

View File

@@ -24,7 +24,6 @@ subprojects {
}
subprojects {
project.evaluationDependsOn(':app')
project.evaluationDependsOn(':core')
}
tasks.register("clean", Delete) {

View File

@@ -1 +0,0 @@
/build

View File

@@ -1,72 +0,0 @@
import com.android.build.gradle.tasks.MergeSourceSetFolders
plugins {
id("com.android.library")
id("org.jetbrains.kotlin.android")
}
android {
namespace = "com.follow.clash.core"
compileSdk = 35
ndkVersion = "27.1.12297006"
defaultConfig {
minSdk = 21
consumerProguardFiles("consumer-rules.pro")
}
buildTypes {
release {
proguardFiles(
getDefaultProguardFile("proguard-android-optimize.txt"),
"proguard-rules.pro"
)
}
}
sourceSets {
getByName("main") {
jniLibs.srcDirs("src/main/jniLibs")
}
}
externalNativeBuild {
cmake {
path("src/main/cpp/CMakeLists.txt")
version = "3.22.1"
}
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_11
targetCompatibility = JavaVersion.VERSION_11
}
kotlinOptions {
jvmTarget = "11"
}
}
tasks.register<Copy>("copyNativeLibs") {
doFirst {
delete("src/main/jniLibs")
}
from("../../libclash/android")
into("src/main/jniLibs")
}
tasks.withType<MergeSourceSetFolders>().configureEach {
dependsOn("copyNativeLibs")
}
afterEvaluate {
tasks.named("assembleDebug").configure {
dependsOn("copyNativeLibs")
}
tasks.named("assembleRelease").configure {
dependsOn("copyNativeLibs")
}
}
dependencies {
implementation("androidx.core:core-ktx:1.16.0")
}

View File

@@ -1,21 +0,0 @@
# Add project specific ProGuard rules here.
# You can control the set of applied configuration files using the
# proguardFiles setting in build.gradle.
#
# For more details, see
# http://developer.android.com/guide/developing/tools/proguard.html
# If your project uses WebView with JS, uncomment the following
# and specify the fully qualified class name to the JavaScript interface
# class:
#-keepclassmembers class fqcn.of.javascript.interface.for.webview {
# public *;
#}
# Uncomment this to preserve the line number information for
# debugging stack traces.
#-keepattributes SourceFile,LineNumberTable
# If you keep the line number information, uncomment this to
# hide the original source file name.
#-renamesourcefileattribute SourceFile

View File

@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
</manifest>

View File

@@ -1,41 +0,0 @@
cmake_minimum_required(VERSION 3.22.1)
project("core")
if (NOT "${CMAKE_BUILD_TYPE}" STREQUAL "Debug")
add_compile_options(-O3)
add_compile_options(-flto)
add_compile_options(-g0)
add_compile_options(-ffunction-sections -fdata-sections)
add_compile_options(-fno-exceptions -fno-rtti)
add_link_options(
-flto
-Wl,--gc-sections
-Wl,--strip-all
-Wl,--exclude-libs=ALL
)
endif ()
set(LIB_CLASH_PATH "${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI}/libclash.so")
if (EXISTS ${LIB_CLASH_PATH})
message(STATUS "Found libclash.so for ABI ${ANDROID_ABI}")
add_definitions(-D_LIBCLASH)
include_directories(${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI})
link_directories(${CMAKE_SOURCE_DIR}/../jniLibs/${ANDROID_ABI})
add_library(${CMAKE_PROJECT_NAME} SHARED
jni_helper.cpp
core.cpp)
target_link_libraries(${CMAKE_PROJECT_NAME}
clash)
else ()
add_library(${CMAKE_PROJECT_NAME} SHARED
jni_helper.cpp
core.cpp)
target_link_libraries(${CMAKE_PROJECT_NAME})
endif ()

View File

@@ -1,88 +0,0 @@
#include <jni.h>
#ifdef _LIBCLASH
#include <jni.h>
#include <string>
#include "jni_helper.h"
#include "libclash.h"
extern "C"
JNIEXPORT void JNICALL
Java_com_follow_clash_core_Core_startTun(JNIEnv *env, jobject thiz, jint fd, jobject cb) {
auto interface = new_global(cb);
startTUN(fd, interface);
}
extern "C"
JNIEXPORT void JNICALL
Java_com_follow_clash_core_Core_stopTun(JNIEnv *env, jobject thiz) {
stopTun();
}
static jmethodID m_tun_interface_protect;
static jmethodID m_tun_interface_resolve_process;
static void release_jni_object_impl(void *obj) {
ATTACH_JNI();
del_global((jobject) obj);
}
static void call_tun_interface_protect_impl(void *tun_interface, int fd) {
ATTACH_JNI();
env->CallVoidMethod((jobject) tun_interface,
(jmethodID) m_tun_interface_protect,
(jint) fd);
}
static const char*
call_tun_interface_resolve_process_impl(void *tun_interface, int protocol,
const char *source,
const char *target,
int uid) {
ATTACH_JNI();
jstring packageName = (jstring)env->CallObjectMethod((jobject) tun_interface,
(jmethodID) m_tun_interface_resolve_process,
(jint) protocol,
(jstring) new_string(source),
(jstring) new_string(target),
(jint) uid);
return get_string(packageName);
}
extern "C"
JNIEXPORT jint JNICALL
JNI_OnLoad(JavaVM *vm, void *reserved) {
JNIEnv *env = nullptr;
if (vm->GetEnv((void **) &env, JNI_VERSION_1_6) != JNI_OK) {
return JNI_ERR;
}
initialize_jni(vm, env);
jclass c_tun_interface = find_class("com/follow/clash/core/TunInterface");
m_tun_interface_protect = find_method(c_tun_interface, "protect", "(I)V");
m_tun_interface_resolve_process = find_method(c_tun_interface, "resolverProcess",
"(ILjava/lang/String;Ljava/lang/String;I)Ljava/lang/String;");
registerCallbacks(&call_tun_interface_protect_impl,
&call_tun_interface_resolve_process_impl,
&release_jni_object_impl);
return JNI_VERSION_1_6;
}
#else
extern "C"
JNIEXPORT void JNICALL
Java_com_follow_clash_core_Core_stopTun(JNIEnv *env, jobject thiz) {
}
extern "C"
JNIEXPORT void JNICALL
Java_com_follow_clash_core_Core_startTun(JNIEnv *env, jobject thiz, jint fd, jobject cb) {
}
#endif

View File

@@ -1,70 +0,0 @@
#include "jni_helper.h"
#include <malloc.h>
#include <cstring>
static JavaVM *global_vm;
static jclass c_string;
static jmethodID m_new_string;
static jmethodID m_get_bytes;
void initialize_jni(JavaVM *vm, JNIEnv *env) {
global_vm = vm;
c_string = (jclass) new_global(find_class("java/lang/String"));
m_new_string = find_method(c_string, "<init>", "([B)V");
m_get_bytes = find_method(c_string, "getBytes", "()[B");
}
JavaVM *global_java_vm() {
return global_vm;
}
char *jni_get_string(JNIEnv *env, jstring str) {
auto array = (jbyteArray) env->CallObjectMethod(str, m_get_bytes);
int length = env->GetArrayLength(array);
char *content = (char *) malloc(length + 1);
env->GetByteArrayRegion(array, 0, length, (jbyte *) content);
content[length] = 0;
return content;
}
jstring jni_new_string(JNIEnv *env, const char *str) {
auto length = (int) strlen(str);
jbyteArray array = env->NewByteArray(length);
env->SetByteArrayRegion(array, 0, length, (const jbyte *) str);
return (jstring) env->NewObject(c_string, m_new_string, array);
}
int jni_catch_exception(JNIEnv *env) {
int result = env->ExceptionCheck();
if (result) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return result;
}
void jni_attach_thread(struct scoped_jni *jni) {
JavaVM *vm = global_java_vm();
if (vm->GetEnv((void **) &jni->env, JNI_VERSION_1_6) == JNI_OK) {
jni->require_release = 0;
return;
}
if (vm->AttachCurrentThread(&jni->env, nullptr) != JNI_OK) {
abort();
}
jni->require_release = 1;
}
void jni_detach_thread(struct scoped_jni *jni) {
JavaVM *vm = global_java_vm();
if (jni->require_release) {
vm->DetachCurrentThread();
}
}
void release_string(char **str) {
free(*str);
}

View File

@@ -1,39 +0,0 @@
#pragma once
#include <jni.h>
#include <cstdint>
#include <cstdlib>
#include <malloc.h>
struct scoped_jni {
JNIEnv *env;
int require_release;
};
extern void initialize_jni(JavaVM *vm, JNIEnv *env);
extern jstring jni_new_string(JNIEnv *env, const char *str);
extern char *jni_get_string(JNIEnv *env, jstring str);
extern int jni_catch_exception(JNIEnv *env);
extern void jni_attach_thread(struct scoped_jni *jni);
extern void jni_detach_thread(struct scoped_jni *env);
extern void release_string(char **str);
#define ATTACH_JNI() __attribute__((unused, cleanup(jni_detach_thread))) \
struct scoped_jni _jni; \
jni_attach_thread(&_jni); \
JNIEnv *env = _jni.env
#define scoped_string __attribute__((cleanup(release_string))) char*
#define find_class(name) env->FindClass(name)
#define find_method(cls, name, signature) env->GetMethodID(cls, name, signature)
#define new_global(obj) env->NewGlobalRef(obj)
#define del_global(obj) env->DeleteGlobalRef(obj)
#define get_string(jstr) jni_get_string(env, jstr)
#define new_string(cstr) jni_new_string(env, cstr)

View File

@@ -1,50 +0,0 @@
package com.follow.clash.core
import java.net.InetAddress
import java.net.InetSocketAddress
import java.net.URL
data object Core {
private external fun startTun(
fd: Int,
cb: TunInterface
)
private fun parseInetSocketAddress(address: String): InetSocketAddress {
val url = URL("https://$address")
return InetSocketAddress(InetAddress.getByName(url.host), url.port)
}
fun startTun(
fd: Int,
protect: (Int) -> Boolean,
resolverProcess: (protocol: Int, source: InetSocketAddress, target: InetSocketAddress, uid: Int) -> String
) {
startTun(fd, object : TunInterface {
override fun protect(fd: Int) {
protect(fd)
}
override fun resolverProcess(
protocol: Int,
source: String,
target: String,
uid: Int
): String {
return resolverProcess(
protocol,
parseInetSocketAddress(source),
parseInetSocketAddress(target),
uid,
)
}
});
}
external fun stopTun()
init {
System.loadLibrary("core")
}
}

View File

@@ -1,9 +0,0 @@
package com.follow.clash.core
import androidx.annotation.Keep
@Keep
interface TunInterface {
fun protect(fd: Int)
fun resolverProcess(protocol: Int, source: String, target: String, uid: Int): String
}

View File

@@ -24,4 +24,3 @@ plugins {
}
include ":app"
include ':core'

View File

@@ -35,8 +35,8 @@ func (action Action) getResult(data interface{}) []byte {
func handleAction(action *Action, result func(data interface{})) {
switch action.Method {
case initClashMethod:
paramsString := action.Data.(string)
result(handleInitClash(paramsString))
data := action.Data.(string)
result(handleInitClash(data))
return
case getIsInitMethod:
result(handleGetIsInit())

View File

@@ -1,77 +0,0 @@
//go:build android && cgo
package main
/*
#include <stdlib.h>
typedef void (*release_object_func)(void *obj);
typedef void (*protect_func)(void *tun_interface, int fd);
typedef const char* (*resolve_process_func)(void *tun_interface, int protocol, const char *source, const char *target, int uid);
static void protect(protect_func fn, void *tun_interface, int fd) {
if (fn) {
fn(tun_interface, fd);
}
}
static const char* resolve_process(resolve_process_func fn, void *tun_interface, int protocol, const char *source, const char *target, int uid) {
if (fn) {
return fn(tun_interface, protocol, source, target, uid);
}
return "";
}
static void release_object(release_object_func fn, void *obj) {
if (fn) {
return fn(obj);
}
}
*/
import "C"
import (
"unsafe"
)
var (
globalCallbacks struct {
releaseObjectFunc C.release_object_func
protectFunc C.protect_func
resolveProcessFunc C.resolve_process_func
}
)
func protect(callback unsafe.Pointer, fd int) {
if globalCallbacks.protectFunc != nil {
C.protect(globalCallbacks.protectFunc, callback, C.int(fd))
}
}
func resolveProcess(callback unsafe.Pointer, protocol int, source, target string, uid int) string {
if globalCallbacks.resolveProcessFunc == nil {
return ""
}
s := C.CString(source)
defer C.free(unsafe.Pointer(s))
t := C.CString(target)
defer C.free(unsafe.Pointer(t))
res := C.resolve_process(globalCallbacks.resolveProcessFunc, callback, C.int(protocol), s, t, C.int(uid))
defer C.free(unsafe.Pointer(res))
return C.GoString(res)
}
func releaseObject(callback unsafe.Pointer) {
if globalCallbacks.releaseObjectFunc == nil {
return
}
C.release_object(globalCallbacks.releaseObjectFunc, callback)
}
//export registerCallbacks
func registerCallbacks(markSocketFunc C.protect_func, resolveProcessFunc C.resolve_process_func, releaseObjectFunc C.release_object_func) {
globalCallbacks.protectFunc = markSocketFunc
globalCallbacks.resolveProcessFunc = resolveProcessFunc
globalCallbacks.releaseObjectFunc = releaseObjectFunc
}

View File

@@ -41,7 +41,6 @@ func splitByMultipleSeparators(s string) interface{} {
}
var (
version = 0
isRunning = false
runLock sync.Mutex
ips = []string{"ipwho.is", "api.ip.sb", "ipapi.co", "ipinfo.io"}
@@ -275,6 +274,7 @@ func patchConfig() {
dialer.DefaultInterface.Store(general.Interface)
adapter.UnifiedDelay.Store(general.UnifiedDelay)
tunnel.SetMode(general.Mode)
tunnel.UpdateRules(currentConfig.Rules, currentConfig.SubRules, currentConfig.RuleProviders)
log.SetLevel(general.LogLevel)
resolver.DisableIPv6 = !general.IPv6

View File

@@ -7,11 +7,6 @@ import (
"time"
)
type InitParams struct {
HomeDir string `json:"home-dir"`
Version int `json:"version"`
}
type ConfigExtendedParams struct {
IsPatch bool `json:"is-patch"`
IsCompatible bool `json:"is-compatible"`
@@ -76,7 +71,11 @@ const (
stopLogMethod Method = "stopLog"
startListenerMethod Method = "startListener"
stopListenerMethod Method = "stopListener"
startTunMethod Method = "startTun"
stopTunMethod Method = "stopTun"
updateDnsMethod Method = "updateDns"
setProcessMapMethod Method = "setProcessMap"
setFdMapMethod Method = "setFdMap"
setStateMethod Method = "setState"
getAndroidVpnOptionsMethod Method = "getAndroidVpnOptions"
getRunTimeMethod Method = "getRunTime"
@@ -110,3 +109,20 @@ func (message *Message) Json() (string, error) {
data, err := json.Marshal(message)
return string(data), err
}
type InvokeMessage struct {
Type InvokeType `json:"type"`
Data interface{} `json:"data"`
}
type InvokeType string
const (
ProtectInvoke InvokeType = "protect"
ProcessInvoke InvokeType = "process"
)
func (message *InvokeMessage) Json() string {
data, _ := json.Marshal(message)
return string(data)
}

View File

@@ -34,15 +34,9 @@ var (
currentConfig *config.Config
)
func handleInitClash(paramsString string) bool {
var params = InitParams{}
err := json.Unmarshal([]byte(paramsString), &params)
if err != nil {
return false
}
version = params.Version
func handleInitClash(homeDirStr string) bool {
if !isInit {
constant.SetHomeDir(params.HomeDir)
constant.SetHomeDir(homeDirStr)
isInit = true
}
return isInit

View File

@@ -4,7 +4,6 @@ package main
import "C"
import (
"context"
bridge "core/dart-bridge"
"core/platform"
"core/state"
@@ -12,116 +11,121 @@ import (
"encoding/json"
"errors"
"fmt"
"github.com/metacubex/mihomo/common/utils"
"github.com/metacubex/mihomo/component/dialer"
"github.com/metacubex/mihomo/component/process"
"github.com/metacubex/mihomo/constant"
"github.com/metacubex/mihomo/dns"
"github.com/metacubex/mihomo/listener/sing_tun"
"github.com/metacubex/mihomo/log"
"golang.org/x/sync/semaphore"
"net"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
)
type TunHandler struct {
listener *sing_tun.Listener
callback unsafe.Pointer
limit *semaphore.Weighted
type Fd struct {
Id string `json:"id"`
Value int64 `json:"value"`
}
func (t *TunHandler) close() {
_ = t.limit.Acquire(context.TODO(), 4)
defer t.limit.Release(4)
removeTunHook()
if t.listener != nil {
_ = t.listener.Close()
}
if t.callback != nil {
releaseObject(t.callback)
}
t.callback = nil
t.listener = nil
type Process struct {
Id string `json:"id"`
Metadata *constant.Metadata `json:"metadata"`
}
func (t *TunHandler) handleProtect(fd int) {
_ = t.limit.Acquire(context.Background(), 1)
defer t.limit.Release(1)
if t.listener == nil {
return
}
protect(t.callback, fd)
type ProcessMapItem struct {
Id string `json:"id"`
Value string `json:"value"`
}
func (t *TunHandler) handleResolveProcess(source, target net.Addr) string {
_ = t.limit.Acquire(context.Background(), 1)
defer t.limit.Release(1)
type InvokeManager struct {
invokeMap sync.Map
chanMap map[string]chan struct{}
chanLock sync.Mutex
}
if t.listener == nil {
func NewInvokeManager() *InvokeManager {
return &InvokeManager{
chanMap: make(map[string]chan struct{}),
}
}
func (m *InvokeManager) completer(id string, value string) {
m.invokeMap.Store(id, value)
m.chanLock.Lock()
if ch, ok := m.chanMap[id]; ok {
close(ch)
delete(m.chanMap, id)
}
m.chanLock.Unlock()
}
func (m *InvokeManager) await(id string) string {
m.chanLock.Lock()
if _, ok := m.chanMap[id]; !ok {
m.chanMap[id] = make(chan struct{})
}
ch := m.chanMap[id]
m.chanLock.Unlock()
timeout := time.After(500 * time.Millisecond)
select {
case <-ch:
res, ok := m.invokeMap.Load(id)
m.invokeMap.Delete(id)
if ok {
return res.(string)
} else {
return ""
}
case <-timeout:
m.completer(id, "")
return ""
}
var protocol int
uid := -1
switch source.Network() {
case "udp", "udp4", "udp6":
protocol = syscall.IPPROTO_UDP
case "tcp", "tcp4", "tcp6":
protocol = syscall.IPPROTO_TCP
}
if version < 29 {
uid = platform.QuerySocketUidFromProcFs(source, target)
}
return resolveProcess(t.callback, protocol, source.String(), target.String(), uid)
}
var (
tunLock sync.Mutex
runTime *time.Time
errBlocked = errors.New("blocked")
tunHandler *TunHandler
invokePort int64 = -1
tunListener *sing_tun.Listener
fdInvokeMap = NewInvokeManager()
processInvokeMap = NewInvokeManager()
tunLock sync.Mutex
runTime *time.Time
errBlocked = errors.New("blocked")
)
func handleStartTun(fd int) string {
handleStopTun()
tunLock.Lock()
defer tunLock.Unlock()
if fd == 0 {
now := time.Now()
runTime = &now
} else {
initSocketHook()
tunListener, _ = t.Start(fd, currentConfig.General.Tun.Device, currentConfig.General.Tun.Stack)
if tunListener != nil {
log.Infoln("TUN address: %v", tunListener.Address())
}
now := time.Now()
runTime = &now
}
return handleGetRunTime()
}
func handleStopTun() {
tunLock.Lock()
defer tunLock.Unlock()
removeSocketHook()
runTime = nil
if tunHandler != nil {
tunHandler.close()
if tunListener != nil {
log.Infoln("TUN close")
_ = tunListener.Close()
}
}
func handleStartTun(fd int, callback unsafe.Pointer) bool {
handleStopTun()
now := time.Now()
runTime = &now
if fd != 0 {
tunLock.Lock()
defer tunLock.Unlock()
tunHandler = &TunHandler{
callback: callback,
limit: semaphore.NewWeighted(4),
}
initTunHook()
tunListener, _ := t.Start(fd, currentConfig.General.Tun.Device, currentConfig.General.Tun.Stack)
if tunListener != nil {
log.Infoln("TUN address: %v", tunListener.Address())
} else {
removeTunHook()
return false
}
tunHandler.listener = tunListener
}
return true
}
func handleGetRunTime() string {
if runTime == nil {
return ""
@@ -129,27 +133,81 @@ func handleGetRunTime() string {
return strconv.FormatInt(runTime.UnixMilli(), 10)
}
func initTunHook() {
func handleSetProcessMap(params string) {
var processMapItem = &ProcessMapItem{}
err := json.Unmarshal([]byte(params), processMapItem)
if err == nil {
processInvokeMap.completer(processMapItem.Id, processMapItem.Value)
}
}
//export attachInvokePort
func attachInvokePort(mPort C.longlong) {
invokePort = int64(mPort)
}
func sendInvokeMessage(message InvokeMessage) {
if invokePort == -1 {
return
}
bridge.SendToPort(invokePort, message.Json())
}
func handleMarkSocket(fd Fd) {
sendInvokeMessage(InvokeMessage{
Type: ProtectInvoke,
Data: fd,
})
}
func handleParseProcess(process Process) {
sendInvokeMessage(InvokeMessage{
Type: ProcessInvoke,
Data: process,
})
}
func handleSetFdMap(id string) {
go func() {
fdInvokeMap.completer(id, "")
}()
}
func initSocketHook() {
dialer.DefaultSocketHook = func(network, address string, conn syscall.RawConn) error {
if platform.ShouldBlockConnection() {
return errBlocked
}
return conn.Control(func(fd uintptr) {
tunHandler.handleProtect(int(fd))
fdInt := int64(fd)
id := utils.NewUUIDV1().String()
handleMarkSocket(Fd{
Id: id,
Value: fdInt,
})
fdInvokeMap.await(id)
})
}
process.DefaultPackageNameResolver = func(metadata *constant.Metadata) (string, error) {
src, dst := metadata.RawSrcAddr, metadata.RawDstAddr
if src == nil || dst == nil {
return "", process.ErrInvalidNetwork
}
return tunHandler.handleResolveProcess(src, dst), nil
}
}
func removeTunHook() {
func removeSocketHook() {
dialer.DefaultSocketHook = nil
process.DefaultPackageNameResolver = nil
}
func init() {
process.DefaultPackageNameResolver = func(metadata *constant.Metadata) (string, error) {
if metadata == nil {
return "", process.ErrInvalidNetwork
}
id := utils.NewUUIDV1().String()
handleParseProcess(Process{
Id: id,
Metadata: metadata,
})
return processInvokeMap.await(id), nil
}
}
func handleGetAndroidVpnOptions() string {
@@ -192,6 +250,16 @@ func handleGetCurrentProfileName() string {
func nextHandle(action *Action, result func(data interface{})) bool {
switch action.Method {
case startTunMethod:
data := action.Data.(string)
var fd int
_ = json.Unmarshal([]byte(data), &fd)
result(handleStartTun(fd))
return true
case stopTunMethod:
handleStopTun()
result(true)
return true
case getAndroidVpnOptionsMethod:
result(handleGetAndroidVpnOptions())
return true
@@ -200,6 +268,16 @@ func nextHandle(action *Action, result func(data interface{})) bool {
handleUpdateDns(data)
result(true)
return true
case setFdMapMethod:
fdId := action.Data.(string)
handleSetFdMap(fdId)
result(true)
return true
case setProcessMapMethod:
data := action.Data.(string)
handleSetProcessMap(data)
result(true)
return true
case getRunTimeMethod:
result(handleGetRunTime())
return true
@@ -211,13 +289,13 @@ func nextHandle(action *Action, result func(data interface{})) bool {
}
//export quickStart
func quickStart(initParamsChar *C.char, paramsChar *C.char, stateParamsChar *C.char, port C.longlong) {
func quickStart(dirChar *C.char, paramsChar *C.char, stateParamsChar *C.char, port C.longlong) {
i := int64(port)
paramsString := C.GoString(initParamsChar)
dir := C.GoString(dirChar)
bytes := []byte(C.GoString(paramsChar))
stateParams := C.GoString(stateParamsChar)
go func() {
res := handleInitClash(paramsString)
res := handleInitClash(dir)
if res == false {
bridge.SendToPort(i, "init error")
}
@@ -227,8 +305,9 @@ func quickStart(initParamsChar *C.char, paramsChar *C.char, stateParamsChar *C.c
}
//export startTUN
func startTUN(fd C.int, callback unsafe.Pointer) bool {
return handleStartTun(int(fd), callback)
func startTUN(fd C.int) *C.char {
f := int(fd)
return C.CString(handleStartTun(f))
}
//export getRunTime
@@ -241,6 +320,12 @@ func stopTun() {
handleStopTun()
}
//export setFdMap
func setFdMap(fdIdChar *C.char) {
fdId := C.GoString(fdIdChar)
handleSetFdMap(fdId)
}
//export getCurrentProfileName
func getCurrentProfileName() *C.char {
return C.CString(handleGetCurrentProfileName())
@@ -262,3 +347,12 @@ func updateDns(s *C.char) {
dnsList := C.GoString(s)
handleUpdateDns(dnsList)
}
//export setProcessMap
func setProcessMap(s *C.char) {
if s == nil {
return
}
paramsString := C.GoString(s)
handleSetProcessMap(paramsString)
}

View File

@@ -1,176 +0,0 @@
//go:build linux
// +build linux
package platform
import (
"bufio"
"encoding/binary"
"encoding/hex"
"fmt"
"net"
"os"
"strconv"
"strings"
"unsafe"
)
var netIndexOfLocal = -1
var netIndexOfUid = -1
var nativeEndian binary.ByteOrder
func QuerySocketUidFromProcFs(source, _ net.Addr) int {
if netIndexOfLocal < 0 || netIndexOfUid < 0 {
return -1
}
network := source.Network()
if strings.HasSuffix(network, "4") || strings.HasSuffix(network, "6") {
network = network[:len(network)-1]
}
path := "/proc/net/" + network
var sIP net.IP
var sPort int
switch s := source.(type) {
case *net.TCPAddr:
sIP = s.IP
sPort = s.Port
case *net.UDPAddr:
sIP = s.IP
sPort = s.Port
default:
return -1
}
sIP = sIP.To16()
if sIP == nil {
return -1
}
uid := doQuery(path+"6", sIP, sPort)
if uid == -1 {
sIP = sIP.To4()
if sIP == nil {
return -1
}
uid = doQuery(path, sIP, sPort)
}
return uid
}
func doQuery(path string, sIP net.IP, sPort int) int {
file, err := os.Open(path)
if err != nil {
return -1
}
defer func(file *os.File) {
_ = file.Close()
}(file)
reader := bufio.NewReader(file)
var bytes [2]byte
binary.BigEndian.PutUint16(bytes[:], uint16(sPort))
local := fmt.Sprintf("%s:%s", hex.EncodeToString(nativeEndianIP(sIP)), hex.EncodeToString(bytes[:]))
for {
row, _, err := reader.ReadLine()
if err != nil {
return -1
}
fields := strings.Fields(string(row))
if len(fields) <= netIndexOfLocal || len(fields) <= netIndexOfUid {
continue
}
if strings.EqualFold(local, fields[netIndexOfLocal]) {
uid, err := strconv.Atoi(fields[netIndexOfUid])
if err != nil {
return -1
}
return uid
}
}
}
func nativeEndianIP(ip net.IP) []byte {
result := make([]byte, len(ip))
for i := 0; i < len(ip); i += 4 {
value := binary.BigEndian.Uint32(ip[i:])
nativeEndian.PutUint32(result[i:], value)
}
return result
}
func init() {
file, err := os.Open("/proc/net/tcp")
if err != nil {
return
}
defer func(file *os.File) {
_ = file.Close()
}(file)
reader := bufio.NewReader(file)
header, _, err := reader.ReadLine()
if err != nil {
return
}
columns := strings.Fields(string(header))
var txQueue, rxQueue, tr, tmWhen bool
for idx, col := range columns {
offset := 0
if txQueue && rxQueue {
offset--
}
if tr && tmWhen {
offset--
}
switch col {
case "tx_queue":
txQueue = true
case "rx_queue":
rxQueue = true
case "tr":
tr = true
case "tm->when":
tmWhen = true
case "local_address":
netIndexOfLocal = idx + offset
case "uid":
netIndexOfUid = idx + offset
}
}
}
func init() {
var x uint32 = 0x01020304
if *(*byte)(unsafe.Pointer(&x)) == 0x01 {
nativeEndian = binary.BigEndian
} else {
nativeEndian = binary.LittleEndian
}
}

View File

@@ -8,7 +8,6 @@ import 'package:fl_clash/clash/interface.dart';
import 'package:fl_clash/common/common.dart';
import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/models/models.dart';
import 'package:fl_clash/state.dart';
import 'package:flutter/services.dart';
import 'package:path/path.dart';
@@ -67,12 +66,7 @@ class ClashCore {
Future<bool> init() async {
await initGeo();
final homeDirPath = await appPath.homeDirPath;
return await clashInterface.init(
InitParams(
homeDir: homeDirPath,
version: globalState.appState.version,
),
);
return await clashInterface.init(homeDirPath);
}
Future<bool> setState(CoreState state) async {

View File

@@ -2348,97 +2348,6 @@ class ClashFFI {
set suboptarg(ffi.Pointer<ffi.Char> value) => _suboptarg.value = value;
void protect(
protect_func fn,
ffi.Pointer<ffi.Void> tun_interface,
int fd,
) {
return _protect(
fn,
tun_interface,
fd,
);
}
late final _protectPtr = _lookup<
ffi.NativeFunction<
ffi.Void Function(
protect_func, ffi.Pointer<ffi.Void>, ffi.Int)>>('protect');
late final _protect = _protectPtr
.asFunction<void Function(protect_func, ffi.Pointer<ffi.Void>, int)>();
ffi.Pointer<ffi.Char> resolve_process(
resolve_process_func fn,
ffi.Pointer<ffi.Void> tun_interface,
int protocol,
ffi.Pointer<ffi.Char> source,
ffi.Pointer<ffi.Char> target,
int uid,
) {
return _resolve_process(
fn,
tun_interface,
protocol,
source,
target,
uid,
);
}
late final _resolve_processPtr = _lookup<
ffi.NativeFunction<
ffi.Pointer<ffi.Char> Function(
resolve_process_func,
ffi.Pointer<ffi.Void>,
ffi.Int,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
ffi.Int)>>('resolve_process');
late final _resolve_process = _resolve_processPtr.asFunction<
ffi.Pointer<ffi.Char> Function(
resolve_process_func,
ffi.Pointer<ffi.Void>,
int,
ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>,
int)>();
void release_object(
release_object_func fn,
ffi.Pointer<ffi.Void> obj,
) {
return _release_object(
fn,
obj,
);
}
late final _release_objectPtr = _lookup<
ffi.NativeFunction<
ffi.Void Function(
release_object_func, ffi.Pointer<ffi.Void>)>>('release_object');
late final _release_object = _release_objectPtr
.asFunction<void Function(release_object_func, ffi.Pointer<ffi.Void>)>();
void registerCallbacks(
protect_func markSocketFunc,
resolve_process_func resolveProcessFunc,
release_object_func releaseObjectFunc,
) {
return _registerCallbacks(
markSocketFunc,
resolveProcessFunc,
releaseObjectFunc,
);
}
late final _registerCallbacksPtr = _lookup<
ffi.NativeFunction<
ffi.Void Function(protect_func, resolve_process_func,
release_object_func)>>('registerCallbacks');
late final _registerCallbacks = _registerCallbacksPtr.asFunction<
void Function(protect_func, resolve_process_func, release_object_func)>();
void initNativeApiBridge(
ffi.Pointer<ffi.Void> api,
) {
@@ -2534,14 +2443,28 @@ class ClashFFI {
_lookup<ffi.NativeFunction<ffi.Void Function()>>('stopListener');
late final _stopListener = _stopListenerPtr.asFunction<void Function()>();
void attachInvokePort(
int mPort,
) {
return _attachInvokePort(
mPort,
);
}
late final _attachInvokePortPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.LongLong)>>(
'attachInvokePort');
late final _attachInvokePort =
_attachInvokePortPtr.asFunction<void Function(int)>();
void quickStart(
ffi.Pointer<ffi.Char> initParamsChar,
ffi.Pointer<ffi.Char> dirChar,
ffi.Pointer<ffi.Char> paramsChar,
ffi.Pointer<ffi.Char> stateParamsChar,
int port,
) {
return _quickStart(
initParamsChar,
dirChar,
paramsChar,
stateParamsChar,
port,
@@ -2556,21 +2479,19 @@ class ClashFFI {
void Function(ffi.Pointer<ffi.Char>, ffi.Pointer<ffi.Char>,
ffi.Pointer<ffi.Char>, int)>();
int startTUN(
ffi.Pointer<ffi.Char> startTUN(
int fd,
ffi.Pointer<ffi.Void> callback,
) {
return _startTUN(
fd,
callback,
);
}
late final _startTUNPtr = _lookup<
ffi.NativeFunction<GoUint8 Function(ffi.Int, ffi.Pointer<ffi.Void>)>>(
'startTUN');
late final _startTUNPtr =
_lookup<ffi.NativeFunction<ffi.Pointer<ffi.Char> Function(ffi.Int)>>(
'startTUN');
late final _startTUN =
_startTUNPtr.asFunction<int Function(int, ffi.Pointer<ffi.Void>)>();
_startTUNPtr.asFunction<ffi.Pointer<ffi.Char> Function(int)>();
ffi.Pointer<ffi.Char> getRunTime() {
return _getRunTime();
@@ -2590,6 +2511,20 @@ class ClashFFI {
_lookup<ffi.NativeFunction<ffi.Void Function()>>('stopTun');
late final _stopTun = _stopTunPtr.asFunction<void Function()>();
void setFdMap(
ffi.Pointer<ffi.Char> fdIdChar,
) {
return _setFdMap(
fdIdChar,
);
}
late final _setFdMapPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Char>)>>(
'setFdMap');
late final _setFdMap =
_setFdMapPtr.asFunction<void Function(ffi.Pointer<ffi.Char>)>();
ffi.Pointer<ffi.Char> getCurrentProfileName() {
return _getCurrentProfileName();
}
@@ -2637,6 +2572,20 @@ class ClashFFI {
'updateDns');
late final _updateDns =
_updateDnsPtr.asFunction<void Function(ffi.Pointer<ffi.Char>)>();
void setProcessMap(
ffi.Pointer<ffi.Char> s,
) {
return _setProcessMap(
s,
);
}
late final _setProcessMapPtr =
_lookup<ffi.NativeFunction<ffi.Void Function(ffi.Pointer<ffi.Char>)>>(
'setProcessMap');
late final _setProcessMap =
_setProcessMapPtr.asFunction<void Function(ffi.Pointer<ffi.Char>)>();
}
final class __mbstate_t extends ffi.Union {
@@ -3789,31 +3738,6 @@ typedef mode_t = __darwin_mode_t;
typedef __darwin_mode_t = __uint16_t;
typedef __uint16_t = ffi.UnsignedShort;
typedef Dart__uint16_t = int;
typedef protect_func = ffi.Pointer<ffi.NativeFunction<protect_funcFunction>>;
typedef protect_funcFunction = ffi.Void Function(
ffi.Pointer<ffi.Void> tun_interface, ffi.Int fd);
typedef Dartprotect_funcFunction = void Function(
ffi.Pointer<ffi.Void> tun_interface, int fd);
typedef resolve_process_func
= ffi.Pointer<ffi.NativeFunction<resolve_process_funcFunction>>;
typedef resolve_process_funcFunction = ffi.Pointer<ffi.Char> Function(
ffi.Pointer<ffi.Void> tun_interface,
ffi.Int protocol,
ffi.Pointer<ffi.Char> source,
ffi.Pointer<ffi.Char> target,
ffi.Int uid);
typedef Dartresolve_process_funcFunction = ffi.Pointer<ffi.Char> Function(
ffi.Pointer<ffi.Void> tun_interface,
int protocol,
ffi.Pointer<ffi.Char> source,
ffi.Pointer<ffi.Char> target,
int uid);
typedef release_object_func
= ffi.Pointer<ffi.NativeFunction<release_object_funcFunction>>;
typedef release_object_funcFunction = ffi.Void Function(
ffi.Pointer<ffi.Void> obj);
typedef Dartrelease_object_funcFunction = void Function(
ffi.Pointer<ffi.Void> obj);
final class GoInterface extends ffi.Struct {
external ffi.Pointer<ffi.Void> t;
@@ -3834,8 +3758,6 @@ final class GoSlice extends ffi.Struct {
typedef GoInt = GoInt64;
typedef GoInt64 = ffi.LongLong;
typedef DartGoInt64 = int;
typedef GoUint8 = ffi.UnsignedChar;
typedef DartGoUint8 = int;
const int __has_safe_buffers = 1;
@@ -4051,8 +3973,6 @@ const int __MAC_15_0 = 150000;
const int __MAC_15_1 = 150100;
const int __MAC_15_2 = 150200;
const int __IPHONE_2_0 = 20000;
const int __IPHONE_2_1 = 20100;
@@ -4215,8 +4135,6 @@ const int __IPHONE_18_0 = 180000;
const int __IPHONE_18_1 = 180100;
const int __IPHONE_18_2 = 180200;
const int __WATCHOS_1_0 = 10000;
const int __WATCHOS_2_0 = 20000;
@@ -4315,8 +4233,6 @@ const int __WATCHOS_11_0 = 110000;
const int __WATCHOS_11_1 = 110100;
const int __WATCHOS_11_2 = 110200;
const int __TVOS_9_0 = 90000;
const int __TVOS_9_1 = 90100;
@@ -4417,8 +4333,6 @@ const int __TVOS_18_0 = 180000;
const int __TVOS_18_1 = 180100;
const int __TVOS_18_2 = 180200;
const int __BRIDGEOS_2_0 = 20000;
const int __BRIDGEOS_3_0 = 30000;
@@ -4475,8 +4389,6 @@ const int __BRIDGEOS_9_0 = 90000;
const int __BRIDGEOS_9_1 = 90100;
const int __BRIDGEOS_9_2 = 90200;
const int __DRIVERKIT_19_0 = 190000;
const int __DRIVERKIT_20_0 = 200000;
@@ -4507,8 +4419,6 @@ const int __DRIVERKIT_24_0 = 240000;
const int __DRIVERKIT_24_1 = 240100;
const int __DRIVERKIT_24_2 = 240200;
const int __VISIONOS_1_0 = 10000;
const int __VISIONOS_1_1 = 10100;
@@ -4519,8 +4429,6 @@ const int __VISIONOS_2_0 = 20000;
const int __VISIONOS_2_1 = 20100;
const int __VISIONOS_2_2 = 20200;
const int MAC_OS_X_VERSION_10_0 = 1000;
const int MAC_OS_X_VERSION_10_1 = 1010;
@@ -4647,11 +4555,9 @@ const int MAC_OS_VERSION_15_0 = 150000;
const int MAC_OS_VERSION_15_1 = 150100;
const int MAC_OS_VERSION_15_2 = 150200;
const int __MAC_OS_X_VERSION_MIN_REQUIRED = 150000;
const int __MAC_OS_X_VERSION_MAX_ALLOWED = 150200;
const int __MAC_OS_X_VERSION_MAX_ALLOWED = 150100;
const int __ENABLE_LEGACY_MAC_AVAILABILITY = 1;

View File

@@ -7,7 +7,7 @@ import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/models/models.dart';
mixin ClashInterface {
Future<bool> init(InitParams params);
Future<bool> init(String homeDir);
Future<bool> preload();
@@ -74,10 +74,12 @@ mixin AndroidClashInterface {
Future<bool> setProcessMap(ProcessMapItem item);
// Future<bool> stopTun();
Future<bool> stopTun();
Future<bool> updateDns(String value);
Future<DateTime?> startTun(int fd);
Future<AndroidVpnOptions?> getAndroidVpnOptions();
Future<String> getCurrentProfileName();
@@ -189,10 +191,10 @@ abstract class ClashHandlerInterface with ClashInterface {
}
@override
Future<bool> init(InitParams params) {
Future<bool> init(String homeDir) {
return invoke<bool>(
method: ActionMethod.initClash,
data: json.encode(params),
data: homeDir,
);
}

View File

@@ -122,12 +122,25 @@ class ClashLib extends ClashHandlerInterface with AndroidClashInterface {
);
}
// @override
// Future<bool> stopTun() {
// return invoke<bool>(
// method: ActionMethod.stopTun,
// );
// }
@override
Future<DateTime?> startTun(int fd) async {
final res = await invoke<String>(
method: ActionMethod.startTun,
data: json.encode(fd),
);
if (res.isEmpty) {
return null;
}
return DateTime.fromMillisecondsSinceEpoch(int.parse(res));
}
@override
Future<bool> stopTun() {
return invoke<bool>(
method: ActionMethod.stopTun,
);
}
@override
Future<AndroidVpnOptions?> getAndroidVpnOptions() async {
@@ -211,12 +224,37 @@ class ClashLibHandler {
);
}
attachInvokePort(int invokePort) {
clashFFI.attachInvokePort(
invokePort,
);
}
DateTime? startTun(int fd) {
final runTimeRaw = clashFFI.startTUN(fd);
final runTimeString = runTimeRaw.cast<Utf8>().toDartString();
clashFFI.freeCString(runTimeRaw);
if (runTimeString.isEmpty) return null;
return DateTime.fromMillisecondsSinceEpoch(int.parse(runTimeString));
}
stopTun() {
clashFFI.stopTun();
}
updateDns(String dns) {
final dnsChar = dns.toNativeUtf8().cast<Char>();
clashFFI.updateDns(dnsChar);
malloc.free(dnsChar);
}
setProcessMap(ProcessMapItem processMapItem) {
final processMapItemChar =
json.encode(processMapItem).toNativeUtf8().cast<Char>();
clashFFI.setProcessMap(processMapItemChar);
malloc.free(processMapItemChar);
}
setState(CoreState state) {
final stateChar = json.encode(state).toNativeUtf8().cast<Char>();
clashFFI.setState(stateChar);
@@ -267,11 +305,17 @@ class ClashLibHandler {
return true;
}
setFdMap(String id) {
final idChar = id.toNativeUtf8().cast<Char>();
clashFFI.setFdMap(idChar);
malloc.free(idChar);
}
Future<String> quickStart(
InitParams initParams,
UpdateConfigParams updateConfigParams,
CoreState state,
) {
String homeDir,
UpdateConfigParams updateConfigParams,
CoreState state,
) {
final completer = Completer<String>();
final receiver = ReceivePort();
receiver.listen((message) {
@@ -281,18 +325,17 @@ class ClashLibHandler {
}
});
final params = json.encode(updateConfigParams);
final initValue = json.encode(initParams);
final stateParams = json.encode(state);
final initParamsChar = initValue.toNativeUtf8().cast<Char>();
final homeChar = homeDir.toNativeUtf8().cast<Char>();
final paramsChar = params.toNativeUtf8().cast<Char>();
final stateParamsChar = stateParams.toNativeUtf8().cast<Char>();
clashFFI.quickStart(
initParamsChar,
homeChar,
paramsChar,
stateParamsChar,
receiver.sendPort.nativePort,
);
malloc.free(initParamsChar);
malloc.free(homeChar);
malloc.free(paramsChar);
malloc.free(stateParamsChar);
return completer.future;

View File

@@ -14,13 +14,15 @@ class Protocol {
void register(String scheme) {
String protocolRegKey = 'Software\\Classes\\$scheme';
RegistryValue protocolRegValue = RegistryValue.string(
RegistryValue protocolRegValue = const RegistryValue(
'URL Protocol',
RegistryValueType.string,
'',
);
String protocolCmdRegKey = 'shell\\open\\command';
RegistryValue protocolCmdRegValue = RegistryValue.string(
RegistryValue protocolCmdRegValue = RegistryValue(
'',
RegistryValueType.string,
'"${Platform.resolvedExecutable}" "%1"',
);
final regKey = Registry.currentUser.createKey(protocolRegKey);
@@ -29,4 +31,4 @@ class Protocol {
}
}
final protocol = Protocol();
final protocol = Protocol();

View File

@@ -30,9 +30,8 @@ class AppController {
AppController(this.context, WidgetRef ref) : _ref = ref;
updateClashConfigDebounce() {
debouncer.call(DebounceTag.updateClashConfig, () async {
final isPatch = globalState.appState.needApply ? false : true;
await updateClashConfig(isPatch);
debouncer.call(DebounceTag.updateClashConfig, () {
updateClashConfig(true);
});
}
@@ -71,7 +70,7 @@ class AppController {
restartCore() async {
await clashService?.reStart();
await _initCore();
await initCore();
if (_ref.read(runTimeProvider.notifier).isStart) {
await globalState.handleStart();
@@ -101,6 +100,7 @@ class AppController {
_ref.read(trafficsProvider.notifier).clear();
_ref.read(totalTrafficProvider.notifier).value = Traffic();
_ref.read(runTimeProvider.notifier).value = null;
// tray.updateTrayTitle(null);
addCheckIpNumDebounce();
}
}
@@ -283,9 +283,6 @@ class AppController {
final res = await clashCore.updateConfig(
globalState.getUpdateConfigParams(isPatch),
);
if (isPatch == false) {
_ref.read(needApplyProvider.notifier).value = false;
}
if (res.isNotEmpty) throw res;
lastTunEnable = enableTun;
lastProfileModified = await profile?.profileLastModified;
@@ -420,7 +417,7 @@ class AppController {
Map<String, dynamic>? data,
bool handleError = false,
}) async {
if (globalState.isPre) {
if(globalState.isPre){
return;
}
if (data != null) {
@@ -481,7 +478,7 @@ class AppController {
await handleExit();
}
Future<void> _initCore() async {
Future<void> initCore() async {
final isInit = await clashCore.isInit;
if (!isInit) {
await clashCore.setState(
@@ -495,7 +492,7 @@ class AppController {
init() async {
await _handlePreference();
await _handlerDisclaimer();
await _initCore();
await initCore();
await _initStatus();
updateTray(true);
autoLaunch?.updateStatus(

View File

@@ -125,7 +125,7 @@ class _ConnectionsFragmentState extends ConsumerState<ConnectionsFragment>
return ConnectionItem(
key: Key(connection.id),
connection: connection,
onClickKeyword: (value) {
onClick: (value) {
context.commonScaffoldState?.addKeyword(value);
},
trailing: IconButton(

View File

@@ -9,15 +9,40 @@ import 'package:fl_clash/widgets/widgets.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
class ConnectionItem extends ConsumerWidget {
class FindProcessBuilder extends StatelessWidget {
final Widget Function(bool value) builder;
const FindProcessBuilder({
super.key,
required this.builder,
});
@override
Widget build(BuildContext context) {
return Consumer(
builder: (_, ref, __) {
final value = ref.watch(
patchClashConfigProvider.select(
(state) =>
state.findProcessMode == FindProcessMode.always &&
Platform.isAndroid,
),
);
return builder(value);
},
);
}
}
class ConnectionItem extends StatelessWidget {
final Connection connection;
final Function(String)? onClickKeyword;
final Function(String)? onClick;
final Widget? trailing;
const ConnectionItem({
super.key,
required this.connection,
this.onClickKeyword,
this.onClick,
this.trailing,
});
@@ -34,14 +59,7 @@ class ConnectionItem extends ConsumerWidget {
}
@override
Widget build(BuildContext context, ref) {
final value = ref.watch(
patchClashConfigProvider.select(
(state) =>
state.findProcessMode == FindProcessMode.always &&
Platform.isAndroid,
),
);
Widget build(BuildContext context) {
final title = Text(
connection.desc,
style: context.textTheme.bodyLarge,
@@ -68,143 +86,70 @@ class ConnectionItem extends ConsumerWidget {
CommonChip(
label: chain,
onPressed: () {
if (onClickKeyword == null) return;
onClickKeyword!(chain);
if (onClick == null) return;
onClick!(chain);
},
),
],
),
],
);
return CommonPopupBox(
targetBuilder: (open) {
if (!Platform.isAndroid) {
return ListItem(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
tileTitleAlignment: ListTileTitleAlignment.titleHeight,
title: title,
subtitle: subTitle,
trailing: trailing,
);
}
return FindProcessBuilder(
builder: (bool value) {
final leading = value
? GestureDetector(
onTap: () {
if (onClick == null) return;
final process = connection.metadata.process;
if (process.isEmpty) return;
onClick!(process);
},
child: Container(
margin: const EdgeInsets.only(top: 4),
width: 48,
height: 48,
child: FutureBuilder<ImageProvider?>(
future: _getPackageIcon(connection),
builder: (_, snapshot) {
if (!snapshot.hasData && snapshot.data == null) {
return Container();
} else {
return Image(
image: snapshot.data!,
gaplessPlayback: true,
width: 48,
height: 48,
);
}
},
),
),
)
: null;
return ListItem(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 4,
),
tileTitleAlignment: ListTileTitleAlignment.titleHeight,
leading: value
? GestureDetector(
onTap: () {
if (onClickKeyword == null) return;
final process = connection.metadata.process;
if (process.isEmpty) return;
onClickKeyword!(process);
},
child: Container(
margin: const EdgeInsets.only(top: 4),
width: 48,
height: 48,
child: FutureBuilder<ImageProvider?>(
future: _getPackageIcon(connection),
builder: (_, snapshot) {
if (!snapshot.hasData && snapshot.data == null) {
return Container();
} else {
return Image(
image: snapshot.data!,
gaplessPlayback: true,
width: 48,
height: 48,
);
}
},
),
),
)
: null,
leading: leading,
title: title,
subtitle: subTitle,
trailing: trailing,
);
// return InkWell(
// child: GestureDetector(
// onLongPressStart: (details) {
// if (!system.isDesktop) {
// return;
// }
// open(
// offset: details.localPosition.translate(
// 0,
// -12,
// ),
// );
// },
// onSecondaryTapDown: (details) {
// if (!system.isDesktop) {
// return;
// }
// open(
// offset: details.localPosition.translate(
// 0,
// -12,
// ),
// );
// },
// child: ListItem(
// padding: const EdgeInsets.symmetric(
// horizontal: 16,
// vertical: 4,
// ),
// tileTitleAlignment: ListTileTitleAlignment.titleHeight,
// leading: value
// ? GestureDetector(
// onTap: () {
// if (onClickKeyword == null) return;
// final process = connection.metadata.process;
// if (process.isEmpty) return;
// onClickKeyword!(process);
// },
// child: Container(
// margin: const EdgeInsets.only(top: 4),
// width: 48,
// height: 48,
// child: FutureBuilder<ImageProvider?>(
// future: _getPackageIcon(connection),
// builder: (_, snapshot) {
// if (!snapshot.hasData && snapshot.data == null) {
// return Container();
// } else {
// return Image(
// image: snapshot.data!,
// gaplessPlayback: true,
// width: 48,
// height: 48,
// );
// }
// },
// ),
// ),
// )
// : null,
// title: title,
// subtitle: subTitle,
// trailing: trailing,
// ),
// ),
// onTap: () {},
// );
},
popup: CommonPopupMenu(
minWidth: 160,
items: [
PopupMenuItemData(
label: "编辑规则",
onPressed: () {
// _handleShowEditExtendPage(context);
},
),
PopupMenuItemData(
label: "设置直连",
onPressed: () {},
),
PopupMenuItemData(
label: "一键屏蔽",
onPressed: () {},
),
],
),
);
}
}

View File

@@ -1,5 +1,3 @@
import 'dart:io';
import 'package:fl_clash/common/common.dart';
import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/models/models.dart';
@@ -138,19 +136,9 @@ class _RequestsFragmentState extends ConsumerState<RequestsFragment>
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (_, constraints) {
return Consumer(
builder: (_, ref, child) {
final value = ref.watch(
patchClashConfigProvider.select(
(state) =>
state.findProcessMode == FindProcessMode.always &&
Platform.isAndroid,
),
);
_handleTryClearCache(constraints.maxWidth - 40 - (value ? 60 : 0));
return child!;
},
child: ValueListenableBuilder<ConnectionsState>(
return FindProcessBuilder(builder: (value) {
_handleTryClearCache(constraints.maxWidth - 40 - (value ? 60 : 0));
return ValueListenableBuilder<ConnectionsState>(
valueListenable: _requestsStateNotifier,
builder: (_, state, __) {
final connections = state.list;
@@ -164,7 +152,7 @@ class _RequestsFragmentState extends ConsumerState<RequestsFragment>
(connection) => ConnectionItem(
key: Key(connection.id),
connection: connection,
onClickKeyword: (value) {
onClick: (value) {
context.commonScaffoldState?.addKeyword(value);
},
),
@@ -218,8 +206,8 @@ class _RequestsFragmentState extends ConsumerState<RequestsFragment>
),
);
},
),
);
);
});
},
);
}

View File

@@ -45,7 +45,6 @@ class _OverrideProfileState extends State<OverrideProfile> {
}
_handleSave(WidgetRef ref, OverrideData overrideData) {
ref.read(needApplyProvider.notifier).value = true;
ref.read(profilesProvider.notifier).updateProfile(
widget.profileId,
(state) => state.copyWith(

View File

@@ -296,6 +296,7 @@ class ProfileItem extends StatelessWidget {
@override
Widget build(BuildContext context) {
final controller = PopupController();
return CommonCard(
isSelected: profile.id == groupValue,
onPressed: () {
@@ -315,6 +316,7 @@ class ProfileItem extends StatelessWidget {
child: CircularProgressIndicator(),
)
: CommonPopupBox(
controller: controller,
popup: CommonPopupMenu(
items: [
PopupMenuItemData(
@@ -358,14 +360,12 @@ class ProfileItem extends StatelessWidget {
),
],
),
targetBuilder: (open) {
return IconButton(
onPressed: () {
open();
},
icon: Icon(Icons.more_vert),
);
},
target: IconButton(
onPressed: () {
controller.open();
},
icon: Icon(Icons.more_vert),
),
),
),
),

View File

@@ -13,11 +13,8 @@ import 'package:flutter_riverpod/flutter_riverpod.dart';
typedef UpdatingMap = Map<String, bool>;
class ProvidersView extends ConsumerStatefulWidget {
final SheetType type;
const ProvidersView({
super.key,
required this.type,
});
@override
@@ -25,6 +22,25 @@ class ProvidersView extends ConsumerStatefulWidget {
}
class _ProvidersViewState extends ConsumerState<ProvidersView> {
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback(
(_) {
globalState.appController.updateProviders();
context.commonScaffoldState?.actions = [
IconButton(
onPressed: () {
_updateProviders();
},
icon: const Icon(
Icons.sync,
),
)
];
},
);
}
_updateProviders() async {
final providers = ref.read(providersProvider);
@@ -86,24 +102,10 @@ class _ProvidersViewState extends ConsumerState<ProvidersView> {
title: appLocalizations.ruleProviders,
items: ruleProviders,
);
return AdaptiveSheetScaffold(
actions: [
IconButton(
onPressed: () {
_updateProviders();
},
icon: const Icon(
Icons.sync,
),
)
],
type: widget.type,
body: generateListView([
...proxySection,
...ruleSection,
]),
title: appLocalizations.providers,
);
return generateListView([
...proxySection,
...ruleSection,
]);
}
}

View File

@@ -31,8 +31,10 @@ class _ProxiesFragmentState extends ConsumerState<ProxiesFragment>
showExtend(
context,
builder: (_, type) {
return ProvidersView(
return AdaptiveSheetScaffold(
type: type,
body: const ProvidersView(),
title: appLocalizations.providers,
);
},
);

View File

@@ -5,7 +5,7 @@ import 'dart:io';
import 'dart:isolate';
import 'dart:ui';
import 'package:fl_clash/models/core.dart';
import 'package:fl_clash/enum/enum.dart';
import 'package:fl_clash/plugins/app.dart';
import 'package:fl_clash/plugins/tile.dart';
import 'package:fl_clash/plugins/vpn.dart';
@@ -17,6 +17,7 @@ import 'application.dart';
import 'clash/core.dart';
import 'clash/lib.dart';
import 'common/common.dart';
import 'models/models.dart';
Future<void> main() async {
globalState.isService = false;
@@ -46,6 +47,7 @@ Future<void> _service(List<String> flags) async {
onStop: () async {
await app?.tip(appLocalizations.stopVpn);
clashLibHandler.stopListener();
clashLibHandler.stopTun();
await vpn?.stop();
exit(0);
},
@@ -62,11 +64,43 @@ Future<void> _service(List<String> flags) async {
vpn?.addListener(
_VpnListenerWithService(
onStarted: (int fd) {
commonPrint.log("vpn started fd: $fd");
final time = clashLibHandler.startTun(fd);
commonPrint.log("vpn start tun time: $time");
},
onDnsChanged: (String dns) {
clashLibHandler.updateDns(dns);
},
),
);
final invokeReceiverPort = ReceivePort();
clashLibHandler.attachInvokePort(
invokeReceiverPort.sendPort.nativePort,
);
invokeReceiverPort.listen(
(message) async {
final invokeMessage = InvokeMessage.fromJson(json.decode(message));
switch (invokeMessage.type) {
case InvokeMessageType.protect:
final fd = Fd.fromJson(invokeMessage.data);
await vpn?.setProtect(fd.value);
clashLibHandler.setFdMap(fd.id);
case InvokeMessageType.process:
final process = ProcessData.fromJson(invokeMessage.data);
final processName = await vpn?.resolverProcess(process) ?? "";
clashLibHandler.setProcessMap(
ProcessMapItem(
id: process.id,
value: processName,
),
);
}
},
);
if (!quickStart) {
_handleMainIpc(clashLibHandler);
} else {
@@ -74,13 +108,9 @@ Future<void> _service(List<String> flags) async {
await ClashCore.initGeo();
app?.tip(appLocalizations.startVpn);
final homeDirPath = await appPath.homeDirPath;
final version = await system.version;
clashLibHandler
.quickStart(
InitParams(
homeDir: homeDirPath,
version: version,
),
homeDirPath,
globalState.getUpdateConfigParams(),
globalState.getCoreState(),
)
@@ -135,11 +165,20 @@ class _TileListenerWithService with TileListener {
@immutable
class _VpnListenerWithService with VpnListener {
final Function(int fd) _onStarted;
final Function(String dns) _onDnsChanged;
const _VpnListenerWithService({
required Function(int fd) onStarted,
required Function(String dns) onDnsChanged,
}) : _onDnsChanged = onDnsChanged;
}) : _onStarted = onStarted,
_onDnsChanged = onDnsChanged;
@override
void onStarted(int fd) {
super.onStarted(fd);
_onStarted(fd);
}
@override
void onDnsChanged(String dns) {

View File

@@ -1,9 +1,8 @@
import 'dart:async';
import 'dart:math';
import 'package:fl_clash/common/common.dart';
import 'package:fl_clash/models/models.dart';
import 'package:fl_clash/widgets/fade_box.dart';
import 'package:fl_clash/state.dart';
import 'package:flutter/material.dart';
class MessageManager extends StatefulWidget {
@@ -18,49 +17,41 @@ class MessageManager extends StatefulWidget {
State<MessageManager> createState() => MessageManagerState();
}
class MessageManagerState extends State<MessageManager> {
class MessageManagerState extends State<MessageManager>
with SingleTickerProviderStateMixin {
final _messagesNotifier = ValueNotifier<List<CommonMessage>>([]);
final List<CommonMessage> _bufferMessages = [];
Completer<bool>? _messageIngCompleter;
double maxWidth = 0;
Offset offset = Offset.zero;
late AnimationController _animationController;
final animationDuration = commonDuration * 2;
@override
void initState() {
super.initState();
_animationController = AnimationController(
vsync: this,
duration: Duration(milliseconds: 400),
);
}
@override
void dispose() {
_messagesNotifier.dispose();
_animationController.dispose();
super.dispose();
}
Future<void> message(String text) async {
message(String text) async {
final commonMessage = CommonMessage(
id: other.uuidV4,
text: text,
);
_bufferMessages.add(commonMessage);
_showMessage();
}
_showMessage() async {
if (_messageIngCompleter?.isCompleted == false) {
return;
}
while (_bufferMessages.isNotEmpty) {
final commonMessage = _bufferMessages.removeAt(0);
_messagesNotifier.value = List.from(_messagesNotifier.value)
..add(
commonMessage,
);
_messageIngCompleter = Completer();
await Future.delayed(Duration(seconds: 1));
Future.delayed(commonMessage.duration, () {
_handleRemove(commonMessage);
});
_messageIngCompleter?.complete(true);
}
_messagesNotifier.value = List.from(_messagesNotifier.value)
..add(
commonMessage,
);
}
_handleRemove(CommonMessage commonMessage) async {
@@ -73,49 +64,171 @@ class MessageManagerState extends State<MessageManager> {
return Stack(
children: [
widget.child,
ValueListenableBuilder(
valueListenable: _messagesNotifier,
builder: (_, messages, __) {
return FadeThroughBox(
alignment: Alignment.topRight,
child: messages.isEmpty
? SizedBox()
: LayoutBuilder(
key: Key(messages.last.id),
builder: (_, constraints) {
return Card(
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(12.0),
),
),
elevation: 10,
margin: EdgeInsets.only(
top: kToolbarHeight,
left: 12,
right: 12,
),
color: context.colorScheme.surfaceContainerHigh,
child: Container(
width: min(
constraints.maxWidth,
400,
),
padding: EdgeInsets.symmetric(
horizontal: 12,
vertical: 16,
),
child: Text(
messages.last.text,
),
),
);
},
),
LayoutBuilder(
builder: (context, container) {
maxWidth = container.maxWidth / 2 + 16;
return SizedBox(
width: maxWidth,
child: ValueListenableBuilder(
valueListenable: globalState.safeMessageOffsetNotifier,
builder: (_, offset, child) {
this.offset = offset;
if (offset == Offset.zero) {
return SizedBox();
}
return Transform.translate(
offset: offset,
child: child!,
);
},
child: Container(
padding: EdgeInsets.only(
right: 0,
left: 8,
top: 0,
bottom: 16,
),
alignment: Alignment.bottomLeft,
child: Stack(
alignment: Alignment.bottomLeft,
children: [
SingleChildScrollView(
reverse: true,
physics: NeverScrollableScrollPhysics(),
child: ValueListenableBuilder(
valueListenable: _messagesNotifier,
builder: (_, messages, ___) {
return Column(
mainAxisAlignment: MainAxisAlignment.end,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (final message in messages) ...[
if (message != messages.first)
SizedBox(
height: 12,
),
_MessageItem(
key: GlobalObjectKey(message.id),
message: message,
onRemove: _handleRemove,
),
],
],
);
},
),
),
],
),
),
),
);
},
),
)
],
);
}
}
class _MessageItem extends StatefulWidget {
final CommonMessage message;
final Function(CommonMessage message) onRemove;
const _MessageItem({
super.key,
required this.message,
required this.onRemove,
});
@override
State<_MessageItem> createState() => _MessageItemState();
}
class _MessageItemState extends State<_MessageItem>
with SingleTickerProviderStateMixin {
late AnimationController _controller;
late Animation<Offset> _offsetAnimation;
late Animation<double> _fadeAnimation;
@override
void initState() {
super.initState();
_controller = AnimationController(
vsync: this,
duration: commonDuration * 1.5,
);
_offsetAnimation = Tween<Offset>(
begin: Offset(-1.0, 0.0),
end: Offset.zero,
).animate(CurvedAnimation(
parent: _controller,
curve: Interval(
0.0,
1,
curve: Curves.easeOut,
),
));
_fadeAnimation = Tween<double>(
begin: 0.0,
end: 1,
).animate(CurvedAnimation(
parent: _controller,
curve: Interval(
0.0,
0.2,
curve: Curves.easeIn,
),
));
_controller.forward();
Future.delayed(
widget.message.duration,
() async {
await _controller.reverse();
widget.onRemove(
widget.message,
);
},
);
}
@override
void dispose() {
_controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return AnimatedBuilder(
animation: _controller.view,
builder: (_, child) {
return FadeTransition(
opacity: _fadeAnimation,
child: SlideTransition(
position: _offsetAnimation,
child: Material(
elevation: _controller.value * 12,
borderRadius: BorderRadius.circular(8),
color: context.colorScheme.surfaceContainer,
clipBehavior: Clip.none,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 16, horizontal: 16),
child: Text(
widget.message.text,
style: context.textTheme.bodyMedium?.copyWith(
color: context.colorScheme.onSurfaceVariant,
),
maxLines: 5,
overflow: TextOverflow.ellipsis,
),
),
),
),
);
},
);
}
}

View File

@@ -31,7 +31,6 @@ class AppState with _$AppState {
required FixedList<Log> logs,
required FixedList<Traffic> traffics,
required Traffic totalTraffic,
@Default(false) bool needApply,
}) = _AppState;
}

View File

@@ -123,7 +123,7 @@ class ProxyGroup with _$ProxyGroup {
String? filter,
@JsonKey(name: "expected-filter") String? excludeFilter,
@JsonKey(name: "exclude-type") String? excludeType,
@JsonKey(name: "expected-status") dynamic expectedStatus,
@JsonKey(name: "expected-status") int? expectedStatus,
bool? hidden,
String? icon,
}) = _ProxyGroup;

View File

@@ -82,17 +82,6 @@ class UpdateConfigParams with _$UpdateConfigParams {
_$UpdateConfigParamsFromJson(json);
}
@freezed
class InitParams with _$InitParams {
const factory InitParams({
@JsonKey(name: "home-dir") required String homeDir,
required int version,
}) = _InitParams;
factory InitParams.fromJson(Map<String, Object?> json) =>
_$InitParamsFromJson(json);
}
@freezed
class ChangeProxyParams with _$ChangeProxyParams {
const factory ChangeProxyParams({

View File

@@ -35,7 +35,6 @@ mixin _$AppState {
FixedList<Log> get logs => throw _privateConstructorUsedError;
FixedList<Traffic> get traffics => throw _privateConstructorUsedError;
Traffic get totalTraffic => throw _privateConstructorUsedError;
bool get needApply => throw _privateConstructorUsedError;
/// Create a copy of AppState
/// with the given fields replaced by the non-null parameter values.
@@ -67,8 +66,7 @@ abstract class $AppStateCopyWith<$Res> {
int version,
FixedList<Log> logs,
FixedList<Traffic> traffics,
Traffic totalTraffic,
bool needApply});
Traffic totalTraffic});
$ColorSchemesCopyWith<$Res> get colorSchemes;
}
@@ -106,7 +104,6 @@ class _$AppStateCopyWithImpl<$Res, $Val extends AppState>
Object? logs = null,
Object? traffics = null,
Object? totalTraffic = null,
Object? needApply = null,
}) {
return _then(_value.copyWith(
isInit: null == isInit
@@ -181,10 +178,6 @@ class _$AppStateCopyWithImpl<$Res, $Val extends AppState>
? _value.totalTraffic
: totalTraffic // ignore: cast_nullable_to_non_nullable
as Traffic,
needApply: null == needApply
? _value.needApply
: needApply // ignore: cast_nullable_to_non_nullable
as bool,
) as $Val);
}
@@ -225,8 +218,7 @@ abstract class _$$AppStateImplCopyWith<$Res>
int version,
FixedList<Log> logs,
FixedList<Traffic> traffics,
Traffic totalTraffic,
bool needApply});
Traffic totalTraffic});
@override
$ColorSchemesCopyWith<$Res> get colorSchemes;
@@ -263,7 +255,6 @@ class __$$AppStateImplCopyWithImpl<$Res>
Object? logs = null,
Object? traffics = null,
Object? totalTraffic = null,
Object? needApply = null,
}) {
return _then(_$AppStateImpl(
isInit: null == isInit
@@ -338,10 +329,6 @@ class __$$AppStateImplCopyWithImpl<$Res>
? _value.totalTraffic
: totalTraffic // ignore: cast_nullable_to_non_nullable
as Traffic,
needApply: null == needApply
? _value.needApply
: needApply // ignore: cast_nullable_to_non_nullable
as bool,
));
}
}
@@ -367,8 +354,7 @@ class _$AppStateImpl implements _AppState {
required this.version,
required this.logs,
required this.traffics,
required this.totalTraffic,
this.needApply = false})
required this.totalTraffic})
: _packages = packages,
_delayMap = delayMap,
_groups = groups,
@@ -443,13 +429,10 @@ class _$AppStateImpl implements _AppState {
final FixedList<Traffic> traffics;
@override
final Traffic totalTraffic;
@override
@JsonKey()
final bool needApply;
@override
String toString() {
return 'AppState(isInit: $isInit, pageLabel: $pageLabel, packages: $packages, colorSchemes: $colorSchemes, sortNum: $sortNum, viewSize: $viewSize, delayMap: $delayMap, groups: $groups, checkIpNum: $checkIpNum, brightness: $brightness, runTime: $runTime, providers: $providers, localIp: $localIp, requests: $requests, version: $version, logs: $logs, traffics: $traffics, totalTraffic: $totalTraffic, needApply: $needApply)';
return 'AppState(isInit: $isInit, pageLabel: $pageLabel, packages: $packages, colorSchemes: $colorSchemes, sortNum: $sortNum, viewSize: $viewSize, delayMap: $delayMap, groups: $groups, checkIpNum: $checkIpNum, brightness: $brightness, runTime: $runTime, providers: $providers, localIp: $localIp, requests: $requests, version: $version, logs: $logs, traffics: $traffics, totalTraffic: $totalTraffic)';
}
@override
@@ -483,34 +466,30 @@ class _$AppStateImpl implements _AppState {
(identical(other.traffics, traffics) ||
other.traffics == traffics) &&
(identical(other.totalTraffic, totalTraffic) ||
other.totalTraffic == totalTraffic) &&
(identical(other.needApply, needApply) ||
other.needApply == needApply));
other.totalTraffic == totalTraffic));
}
@override
int get hashCode => Object.hashAll([
runtimeType,
isInit,
pageLabel,
const DeepCollectionEquality().hash(_packages),
colorSchemes,
sortNum,
viewSize,
const DeepCollectionEquality().hash(_delayMap),
const DeepCollectionEquality().hash(_groups),
checkIpNum,
brightness,
runTime,
const DeepCollectionEquality().hash(_providers),
localIp,
requests,
version,
logs,
traffics,
totalTraffic,
needApply
]);
int get hashCode => Object.hash(
runtimeType,
isInit,
pageLabel,
const DeepCollectionEquality().hash(_packages),
colorSchemes,
sortNum,
viewSize,
const DeepCollectionEquality().hash(_delayMap),
const DeepCollectionEquality().hash(_groups),
checkIpNum,
brightness,
runTime,
const DeepCollectionEquality().hash(_providers),
localIp,
requests,
version,
logs,
traffics,
totalTraffic);
/// Create a copy of AppState
/// with the given fields replaced by the non-null parameter values.
@@ -540,8 +519,7 @@ abstract class _AppState implements AppState {
required final int version,
required final FixedList<Log> logs,
required final FixedList<Traffic> traffics,
required final Traffic totalTraffic,
final bool needApply}) = _$AppStateImpl;
required final Traffic totalTraffic}) = _$AppStateImpl;
@override
bool get isInit;
@@ -579,8 +557,6 @@ abstract class _AppState implements AppState {
FixedList<Traffic> get traffics;
@override
Traffic get totalTraffic;
@override
bool get needApply;
/// Create a copy of AppState
/// with the given fields replaced by the non-null parameter values.

View File

@@ -37,7 +37,7 @@ mixin _$ProxyGroup {
@JsonKey(name: "exclude-type")
String? get excludeType => throw _privateConstructorUsedError;
@JsonKey(name: "expected-status")
dynamic get expectedStatus => throw _privateConstructorUsedError;
int? get expectedStatus => throw _privateConstructorUsedError;
bool? get hidden => throw _privateConstructorUsedError;
String? get icon => throw _privateConstructorUsedError;
@@ -70,7 +70,7 @@ abstract class $ProxyGroupCopyWith<$Res> {
String? filter,
@JsonKey(name: "expected-filter") String? excludeFilter,
@JsonKey(name: "exclude-type") String? excludeType,
@JsonKey(name: "expected-status") dynamic expectedStatus,
@JsonKey(name: "expected-status") int? expectedStatus,
bool? hidden,
String? icon});
}
@@ -158,7 +158,7 @@ class _$ProxyGroupCopyWithImpl<$Res, $Val extends ProxyGroup>
expectedStatus: freezed == expectedStatus
? _value.expectedStatus
: expectedStatus // ignore: cast_nullable_to_non_nullable
as dynamic,
as int?,
hidden: freezed == hidden
? _value.hidden
: hidden // ignore: cast_nullable_to_non_nullable
@@ -192,7 +192,7 @@ abstract class _$$ProxyGroupImplCopyWith<$Res>
String? filter,
@JsonKey(name: "expected-filter") String? excludeFilter,
@JsonKey(name: "exclude-type") String? excludeType,
@JsonKey(name: "expected-status") dynamic expectedStatus,
@JsonKey(name: "expected-status") int? expectedStatus,
bool? hidden,
String? icon});
}
@@ -278,7 +278,7 @@ class __$$ProxyGroupImplCopyWithImpl<$Res>
expectedStatus: freezed == expectedStatus
? _value.expectedStatus
: expectedStatus // ignore: cast_nullable_to_non_nullable
as dynamic,
as int?,
hidden: freezed == hidden
? _value.hidden
: hidden // ignore: cast_nullable_to_non_nullable
@@ -362,7 +362,7 @@ class _$ProxyGroupImpl implements _ProxyGroup {
final String? excludeType;
@override
@JsonKey(name: "expected-status")
final dynamic expectedStatus;
final int? expectedStatus;
@override
final bool? hidden;
@override
@@ -394,8 +394,8 @@ class _$ProxyGroupImpl implements _ProxyGroup {
other.excludeFilter == excludeFilter) &&
(identical(other.excludeType, excludeType) ||
other.excludeType == excludeType) &&
const DeepCollectionEquality()
.equals(other.expectedStatus, expectedStatus) &&
(identical(other.expectedStatus, expectedStatus) ||
other.expectedStatus == expectedStatus) &&
(identical(other.hidden, hidden) || other.hidden == hidden) &&
(identical(other.icon, icon) || other.icon == icon));
}
@@ -416,7 +416,7 @@ class _$ProxyGroupImpl implements _ProxyGroup {
filter,
excludeFilter,
excludeType,
const DeepCollectionEquality().hash(expectedStatus),
expectedStatus,
hidden,
icon);
@@ -451,7 +451,7 @@ abstract class _ProxyGroup implements ProxyGroup {
final String? filter,
@JsonKey(name: "expected-filter") final String? excludeFilter,
@JsonKey(name: "exclude-type") final String? excludeType,
@JsonKey(name: "expected-status") final dynamic expectedStatus,
@JsonKey(name: "expected-status") final int? expectedStatus,
final bool? hidden,
final String? icon}) = _$ProxyGroupImpl;
@@ -488,7 +488,7 @@ abstract class _ProxyGroup implements ProxyGroup {
String? get excludeType;
@override
@JsonKey(name: "expected-status")
dynamic get expectedStatus;
int? get expectedStatus;
@override
bool? get hidden;
@override

View File

@@ -21,7 +21,7 @@ _$ProxyGroupImpl _$$ProxyGroupImplFromJson(Map<String, dynamic> json) =>
filter: json['filter'] as String?,
excludeFilter: json['expected-filter'] as String?,
excludeType: json['exclude-type'] as String?,
expectedStatus: json['expected-status'],
expectedStatus: (json['expected-status'] as num?)?.toInt(),
hidden: json['hidden'] as bool?,
icon: json['icon'] as String?,
);

View File

@@ -1151,178 +1151,6 @@ abstract class _UpdateConfigParams implements UpdateConfigParams {
throw _privateConstructorUsedError;
}
InitParams _$InitParamsFromJson(Map<String, dynamic> json) {
return _InitParams.fromJson(json);
}
/// @nodoc
mixin _$InitParams {
@JsonKey(name: "home-dir")
String get homeDir => throw _privateConstructorUsedError;
int get version => throw _privateConstructorUsedError;
/// Serializes this InitParams to a JSON map.
Map<String, dynamic> toJson() => throw _privateConstructorUsedError;
/// Create a copy of InitParams
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
$InitParamsCopyWith<InitParams> get copyWith =>
throw _privateConstructorUsedError;
}
/// @nodoc
abstract class $InitParamsCopyWith<$Res> {
factory $InitParamsCopyWith(
InitParams value, $Res Function(InitParams) then) =
_$InitParamsCopyWithImpl<$Res, InitParams>;
@useResult
$Res call({@JsonKey(name: "home-dir") String homeDir, int version});
}
/// @nodoc
class _$InitParamsCopyWithImpl<$Res, $Val extends InitParams>
implements $InitParamsCopyWith<$Res> {
_$InitParamsCopyWithImpl(this._value, this._then);
// ignore: unused_field
final $Val _value;
// ignore: unused_field
final $Res Function($Val) _then;
/// Create a copy of InitParams
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? homeDir = null,
Object? version = null,
}) {
return _then(_value.copyWith(
homeDir: null == homeDir
? _value.homeDir
: homeDir // ignore: cast_nullable_to_non_nullable
as String,
version: null == version
? _value.version
: version // ignore: cast_nullable_to_non_nullable
as int,
) as $Val);
}
}
/// @nodoc
abstract class _$$InitParamsImplCopyWith<$Res>
implements $InitParamsCopyWith<$Res> {
factory _$$InitParamsImplCopyWith(
_$InitParamsImpl value, $Res Function(_$InitParamsImpl) then) =
__$$InitParamsImplCopyWithImpl<$Res>;
@override
@useResult
$Res call({@JsonKey(name: "home-dir") String homeDir, int version});
}
/// @nodoc
class __$$InitParamsImplCopyWithImpl<$Res>
extends _$InitParamsCopyWithImpl<$Res, _$InitParamsImpl>
implements _$$InitParamsImplCopyWith<$Res> {
__$$InitParamsImplCopyWithImpl(
_$InitParamsImpl _value, $Res Function(_$InitParamsImpl) _then)
: super(_value, _then);
/// Create a copy of InitParams
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline')
@override
$Res call({
Object? homeDir = null,
Object? version = null,
}) {
return _then(_$InitParamsImpl(
homeDir: null == homeDir
? _value.homeDir
: homeDir // ignore: cast_nullable_to_non_nullable
as String,
version: null == version
? _value.version
: version // ignore: cast_nullable_to_non_nullable
as int,
));
}
}
/// @nodoc
@JsonSerializable()
class _$InitParamsImpl implements _InitParams {
const _$InitParamsImpl(
{@JsonKey(name: "home-dir") required this.homeDir,
required this.version});
factory _$InitParamsImpl.fromJson(Map<String, dynamic> json) =>
_$$InitParamsImplFromJson(json);
@override
@JsonKey(name: "home-dir")
final String homeDir;
@override
final int version;
@override
String toString() {
return 'InitParams(homeDir: $homeDir, version: $version)';
}
@override
bool operator ==(Object other) {
return identical(this, other) ||
(other.runtimeType == runtimeType &&
other is _$InitParamsImpl &&
(identical(other.homeDir, homeDir) || other.homeDir == homeDir) &&
(identical(other.version, version) || other.version == version));
}
@JsonKey(includeFromJson: false, includeToJson: false)
@override
int get hashCode => Object.hash(runtimeType, homeDir, version);
/// Create a copy of InitParams
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@override
@pragma('vm:prefer-inline')
_$$InitParamsImplCopyWith<_$InitParamsImpl> get copyWith =>
__$$InitParamsImplCopyWithImpl<_$InitParamsImpl>(this, _$identity);
@override
Map<String, dynamic> toJson() {
return _$$InitParamsImplToJson(
this,
);
}
}
abstract class _InitParams implements InitParams {
const factory _InitParams(
{@JsonKey(name: "home-dir") required final String homeDir,
required final int version}) = _$InitParamsImpl;
factory _InitParams.fromJson(Map<String, dynamic> json) =
_$InitParamsImpl.fromJson;
@override
@JsonKey(name: "home-dir")
String get homeDir;
@override
int get version;
/// Create a copy of InitParams
/// with the given fields replaced by the non-null parameter values.
@override
@JsonKey(includeFromJson: false, includeToJson: false)
_$$InitParamsImplCopyWith<_$InitParamsImpl> get copyWith =>
throw _privateConstructorUsedError;
}
ChangeProxyParams _$ChangeProxyParamsFromJson(Map<String, dynamic> json) {
return _ChangeProxyParams.fromJson(json);
}

View File

@@ -100,18 +100,6 @@ Map<String, dynamic> _$$UpdateConfigParamsImplToJson(
'params': instance.params,
};
_$InitParamsImpl _$$InitParamsImplFromJson(Map<String, dynamic> json) =>
_$InitParamsImpl(
homeDir: json['home-dir'] as String,
version: (json['version'] as num).toInt(),
);
Map<String, dynamic> _$$InitParamsImplToJson(_$InitParamsImpl instance) =>
<String, dynamic>{
'home-dir': instance.homeDir,
'version': instance.version,
};
_$ChangeProxyParamsImpl _$$ChangeProxyParamsImplFromJson(
Map<String, dynamic> json) =>
_$ChangeProxyParamsImpl(

View File

@@ -36,6 +36,7 @@ class EditorPage extends ConsumerStatefulWidget {
class _EditorPageState extends ConsumerState<EditorPage> {
late CodeLineEditingController _controller;
late CodeFindController _findController;
final _popupController = PopupController();
final _focusNode = FocusNode();
@override
@@ -120,12 +121,11 @@ class _EditorPageState extends ConsumerState<EditorPage> {
),
_wrapController(
(value) => CommonPopupBox(
targetBuilder: (open) {
return IconButton(
onPressed: open,
icon: const Icon(Icons.more_vert),
);
},
controller: _popupController,
target: IconButton(
onPressed: _popupController.open,
icon: const Icon(Icons.more_vert),
),
popup: CommonPopupMenu(
items: [
PopupMenuItemData(

View File

@@ -153,8 +153,26 @@ class CommonNavigationBar extends ConsumerWidget {
required this.currentIndex,
});
_updateSafeMessageOffset(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((_) {
final size = context.size;
if (viewMode == ViewMode.mobile) {
globalState.safeMessageOffsetNotifier.value = Offset(
0,
-(size?.height ?? 0),
);
} else {
globalState.safeMessageOffsetNotifier.value = Offset(
size?.width ?? 0,
0,
);
}
});
}
@override
Widget build(BuildContext context, ref) {
_updateSafeMessageOffset(context);
if (viewMode == ViewMode.mobile) {
return NavigationBarTheme(
data: _NavigationBarDefaultsM3(context),

View File

@@ -31,6 +31,7 @@ class Service {
Future<bool?> startVpn() async {
final options = await clashLib?.getAndroidVpnOptions();
// commonPrint.log("$options");
return await methodChannel.invokeMethod<bool>("startVpn", {
'data': json.encode(options),
});

View File

@@ -8,6 +8,8 @@ import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
abstract mixin class VpnListener {
void onStarted(int fd) {}
void onDnsChanged(String dns) {}
}
@@ -30,6 +32,10 @@ class Vpn {
default:
for (final VpnListener listener in _listeners) {
switch (call.method) {
case "started":
final fd = call.arguments as int;
listener.onStarted(fd);
break;
case "dnsChanged":
final dns = call.arguments as String;
listener.onDnsChanged(dns);
@@ -56,6 +62,16 @@ class Vpn {
return await methodChannel.invokeMethod<bool>("stop");
}
Future<bool?> setProtect(int fd) async {
return await methodChannel.invokeMethod<bool?>("setProtect", {'fd': fd});
}
Future<String?> resolverProcess(ProcessData process) async {
return await methodChannel.invokeMethod<String>("resolverProcess", {
"data": json.encode(process),
});
}
void addListener(VpnListener listener) {
_listeners.add(listener);
}

View File

@@ -356,18 +356,3 @@ class DelayDataSource extends _$DelayDataSource with AutoDisposeNotifierMixin {
}
}
}
@riverpod
class NeedApply extends _$NeedApply with AutoDisposeNotifierMixin {
@override
bool build() {
return globalState.appState.needApply;
}
@override
onUpdate(value) {
globalState.appState = globalState.appState.copyWith(
needApply: value,
);
}
}

View File

@@ -336,19 +336,5 @@ final delayDataSourceProvider =
);
typedef _$DelayDataSource = AutoDisposeNotifier<DelayMap>;
String _$needApplyHash() => r'62ff248d67b0525c6a55e556fbd29a2044e97766';
/// See also [NeedApply].
@ProviderFor(NeedApply)
final needApplyProvider = AutoDisposeNotifierProvider<NeedApply, bool>.internal(
NeedApply.new,
name: r'needApplyProvider',
debugGetCreateSourceHash:
const bool.fromEnvironment('dart.vm.product') ? null : _$needApplyHash,
dependencies: null,
allTransitiveDependencies: null,
);
typedef _$NeedApply = AutoDisposeNotifier<bool>;
// ignore_for_file: type=lint
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package

View File

@@ -32,6 +32,7 @@ class GlobalState {
late CommonTheme theme;
DateTime? startTime;
UpdateTasks tasks = [];
final safeMessageOffsetNotifier = ValueNotifier(Offset.zero);
final navigatorKey = GlobalKey<NavigatorState>();
late AppController appController;
GlobalKey<CommonScaffoldState> homeScaffoldKey = GlobalKey();
@@ -110,6 +111,7 @@ class GlobalState {
Future handleStop() async {
startTime = null;
await clashCore.stopListener();
await clashLib?.stopTun();
await service?.stopVpn();
stopUpdateTasks();
}

View File

@@ -4,12 +4,10 @@ import 'package:flutter/material.dart';
class FadeBox extends StatelessWidget {
final Widget child;
final Alignment? alignment;
const FadeBox({
super.key,
required this.child,
this.alignment,
});
@override
@@ -21,7 +19,7 @@ class FadeBox extends StatelessWidget {
secondaryAnimation,
) {
return Container(
alignment: alignment ?? Alignment.centerLeft,
alignment: Alignment.centerLeft,
child: FadeTransition(
opacity: animation,
child: child,
@@ -35,12 +33,10 @@ class FadeBox extends StatelessWidget {
class FadeThroughBox extends StatelessWidget {
final Widget child;
final Alignment? alignment;
const FadeThroughBox({
super.key,
required this.child,
this.alignment,
});
@override
@@ -52,7 +48,7 @@ class FadeThroughBox extends StatelessWidget {
secondaryAnimation,
) {
return Container(
alignment: alignment ?? Alignment.centerLeft,
alignment: Alignment.centerLeft,
child: FadeThroughTransition(
animation: animation,
fillColor: Colors.transparent,

View File

@@ -398,18 +398,15 @@ class MapInputPage extends StatelessWidget {
}
_handleDelete(MapEntry<String, String> item) {
final entries = List<MapEntry<String, String>>.from(
items,
);
final index = entries.indexWhere(
final index = items.indexWhere(
(entry) {
return entry.key == item.key && item.value == entry.value;
return entry.key == item.key;
},
);
if (index != -1) {
entries.removeAt(index);
items.removeAt(index);
}
onChange(Map.fromEntries(entries));
onChange(Map.fromEntries(items));
}
@override

View File

@@ -40,41 +40,39 @@ class CommonPopupRoute<T> extends PopupRoute<T> {
parent: animation,
curve: Curves.easeIn,
).value;
return SafeArea(
child: ValueListenableBuilder(
valueListenable: offsetNotifier,
builder: (_, value, child) {
return Align(
alignment: align,
child: CustomSingleChildLayout(
delegate: OverflowAwareLayoutDelegate(
offset: value.translate(
48,
-8,
),
return ValueListenableBuilder(
valueListenable: offsetNotifier,
builder: (_, value, child) {
return Align(
alignment: align,
child: CustomSingleChildLayout(
delegate: OverflowAwareLayoutDelegate(
offset: value.translate(
48,
12,
),
),
child: child,
),
);
},
child: AnimatedBuilder(
animation: animation,
builder: (_, Widget? child) {
return Opacity(
opacity: 0.1 + 0.9 * animationValue,
child: Transform.scale(
alignment: align,
scale: 0.8 + 0.2 * animationValue,
child: Transform.translate(
offset: Offset(0, -10) * (1 - animationValue),
child: child!,
),
child: child,
),
);
},
child: AnimatedBuilder(
animation: animation,
builder: (_, Widget? child) {
return Opacity(
opacity: 0.1 + 0.9 * animationValue,
child: Transform.scale(
alignment: align,
scale: 0.8 + 0.2 * animationValue,
child: Transform.translate(
offset: Offset(0, -10) * (1 - animationValue),
child: child!,
),
),
);
},
child: builder(
context,
),
child: builder(
context,
),
),
);
@@ -96,18 +94,16 @@ class PopupController extends ValueNotifier<bool> {
}
}
typedef PopupOpen = Function({
Offset offset,
});
class CommonPopupBox extends StatefulWidget {
final Widget Function(PopupOpen open) targetBuilder;
final Widget target;
final Widget popup;
final PopupController? controller;
const CommonPopupBox({
super.key,
required this.targetBuilder,
required this.target,
required this.popup,
this.controller,
});
@override
@@ -115,14 +111,38 @@ class CommonPopupBox extends StatefulWidget {
}
class _CommonPopupBoxState extends State<CommonPopupBox> {
bool _isOpen = false;
final _targetOffsetValueNotifier = ValueNotifier<Offset>(Offset.zero);
Offset _offset = Offset.zero;
final _targetOffsetValueNotifier = ValueNotifier(Offset.zero);
_open({Offset offset = Offset.zero}) {
_offset = offset;
_updateOffset();
_isOpen = true;
@override
void initState() {
widget.controller?.addListener(_handleChange);
super.initState();
}
@override
void didUpdateWidget(CommonPopupBox oldWidget) {
if (oldWidget.controller != widget.controller) {
oldWidget.controller?.removeListener(_handleChange);
oldWidget.controller?.dispose();
widget.controller?.addListener(_handleChange);
}
super.didUpdateWidget(oldWidget);
}
@override
void dispose() {
widget.controller?.removeListener(_handleChange);
super.dispose();
}
_handleChange() {
if (widget.controller?.value == true) {
_open();
}
}
_open() {
_handleTargetOffset();
Navigator.of(context)
.push(
CommonPopupRoute(
@@ -133,37 +153,24 @@ class _CommonPopupBoxState extends State<CommonPopupBox> {
offsetNotifier: _targetOffsetValueNotifier,
),
)
.then((_) {
_isOpen = false;
.then((res) {
widget.controller?.close();
});
}
_updateOffset() {
_handleTargetOffset() {
final renderBox = context.findRenderObject() as RenderBox?;
if (renderBox == null) {
return;
}
final viewPadding = MediaQuery.of(context).viewPadding;
_targetOffsetValueNotifier.value = renderBox
.localToGlobal(
Offset.zero.translate(viewPadding.right, viewPadding.top),
)
.translate(
_offset.dx,
_offset.dy,
);
_targetOffsetValueNotifier.value = renderBox.localToGlobal(
Offset.zero,
);
}
@override
Widget build(BuildContext context) {
return LayoutBuilder(builder: (_, __) {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (_isOpen) {
_updateOffset();
}
});
return widget.targetBuilder(_open);
});
return widget.target;
}
}
@@ -181,14 +188,14 @@ class OverflowAwareLayoutDelegate extends SingleChildLayoutDelegate {
@override
Offset getPositionForChild(Size size, Size childSize) {
final safeOffset = Offset(16, 16);
final saveOffset = Offset(16, 16);
double x = (offset.dx - childSize.width).clamp(
0,
size.width - safeOffset.dx - childSize.width,
size.width - saveOffset.dx - childSize.width,
);
double y = (offset.dy).clamp(
0,
size.height - safeOffset.dy - childSize.height,
size.height - saveOffset.dy - childSize.height,
);
return Offset(x, y);
}
@@ -201,12 +208,10 @@ class OverflowAwareLayoutDelegate extends SingleChildLayoutDelegate {
class CommonPopupMenu extends StatelessWidget {
final List<PopupMenuItemData> items;
final double? minWidth;
const CommonPopupMenu({
super.key,
required this.items,
this.minWidth,
});
Widget _popupMenuItem(
@@ -231,10 +236,7 @@ class CommonPopupMenu extends StatelessWidget {
onPressed();
}
: null,
child: Container(
constraints: BoxConstraints(
minWidth: minWidth ?? 120,
),
child: Padding(
padding: EdgeInsets.only(
left: 16,
right: 64,

View File

@@ -136,6 +136,11 @@ class _AdaptiveSheetScaffoldState extends State<AdaptiveSheetScaffold> {
: true,
centerTitle: bottomSheet,
backgroundColor: backgroundColor,
// titleTextStyle: bottomSheet
// ? context.textTheme.labelMedium?.copyWith(
// fontSize: 20,
// )
// : null,
title: Text(
widget.title,
),

View File

@@ -99,9 +99,9 @@ EXTERNAL SOURCES:
:path: Flutter/ephemeral/.symlinks/plugins/window_manager/macos
SPEC CHECKSUMS:
app_links: afe860c55c7ef176cea7fb630a2b7d7736de591d
app_links: 9028728e32c83a0831d9db8cf91c526d16cc5468
connectivity_plus: 2256d3e20624a7749ed21653aafe291a46446fee
device_info_plus: 4fb280989f669696856f8b129e4a5e3cd6c48f76
device_info_plus: a56e6e74dbbd2bb92f2da12c64ddd4f67a749041
dynamic_color: b820c000cc68df65e7ba7ff177cb98404ce56651
file_selector_macos: 6280b52b459ae6c590af5d78fc35c7267a3c4b31
FlutterMacOS: 8f6f14fa908a6fb3fba0cd85dbd81ec4b251fb24

View File

@@ -31,7 +31,6 @@
7AC6855B2B8AF836004C123B /* (null) in Bundle Framework */ = {isa = PBXBuildFile; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
CDD319C761C7664F6008596B /* Pods_Runner.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 4121E8CCDC7DC35194714CDE /* Pods_Runner.framework */; };
F50091052CF74B7700D43AEA /* FlClashCore in CopyFiles */ = {isa = PBXBuildFile; fileRef = F50091042CF74B7700D43AEA /* FlClashCore */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
F5AA39AF2DA1D9FB00F5C816 /* LaunchAtLogin in Frameworks */ = {isa = PBXBuildFile; productRef = F5AA39AE2DA1D9FB00F5C816 /* LaunchAtLogin */; };
/* End PBXBuildFile section */
/* Begin PBXContainerItemProxy section */
@@ -136,7 +135,6 @@
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
F5AA39AF2DA1D9FB00F5C816 /* LaunchAtLogin in Frameworks */,
CDD319C761C7664F6008596B /* Pods_Runner.framework in Frameworks */,
);
runOnlyForDeploymentPostprocessing = 0;
@@ -328,9 +326,6 @@
Base,
);
mainGroup = 33CC10E42044A3C60003C045;
packageReferences = (
F5AA39AD2DA1D9FB00F5C816 /* XCRemoteSwiftPackageReference "LaunchAtLogin" */,
);
productRefGroup = 33CC10EE2044A3C60003C045 /* Products */;
projectDirPath = "";
projectRoot = "";
@@ -832,25 +827,6 @@
defaultConfigurationName = Release;
};
/* End XCConfigurationList section */
/* Begin XCRemoteSwiftPackageReference section */
F5AA39AD2DA1D9FB00F5C816 /* XCRemoteSwiftPackageReference "LaunchAtLogin" */ = {
isa = XCRemoteSwiftPackageReference;
repositoryURL = "https://github.com/sindresorhus/LaunchAtLogin";
requirement = {
branch = main;
kind = branch;
};
};
/* End XCRemoteSwiftPackageReference section */
/* Begin XCSwiftPackageProductDependency section */
F5AA39AE2DA1D9FB00F5C816 /* LaunchAtLogin */ = {
isa = XCSwiftPackageProductDependency;
package = F5AA39AD2DA1D9FB00F5C816 /* XCRemoteSwiftPackageReference "LaunchAtLogin" */;
productName = LaunchAtLogin;
};
/* End XCSwiftPackageProductDependency section */
};
rootObject = 33CC10E52044A3C60003C045 /* Project object */;
}

View File

@@ -1,37 +1,19 @@
import Cocoa
import FlutterMacOS
import window_manager
import LaunchAtLogin
class MainFlutterWindow: NSWindow {
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
FlutterMethodChannel(
name: "launch_at_startup", binaryMessenger: flutterViewController.engine.binaryMessenger
)
.setMethodCallHandler { (_ call: FlutterMethodCall, result: @escaping FlutterResult) in
switch call.method {
case "launchAtStartupIsEnabled":
result(LaunchAtLogin.isEnabled)
case "launchAtStartupSetEnabled":
if let arguments = call.arguments as? [String: Any] {
LaunchAtLogin.isEnabled = arguments["setEnabledValue"] as! Bool
}
result(nil)
default:
result(FlutterMethodNotImplemented)
}
}
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
override public func order(_ place: NSWindow.OrderingMode, relativeTo otherWin: Int) {
super.order(place, relativeTo: otherWin)
hiddenWindowAtLaunch()
}
override func awakeFromNib() {
let flutterViewController = FlutterViewController()
let windowFrame = self.frame
self.contentViewController = flutterViewController
self.setFrame(windowFrame, display: true)
RegisterGeneratedPlugins(registry: flutterViewController)
super.awakeFromNib()
}
override public func order(_ place: NSWindow.OrderingMode, relativeTo otherWin: Int) {
super.order(place, relativeTo: otherWin)
hiddenWindowAtLaunch()
}
}

View File

@@ -42,34 +42,10 @@ packages:
dependency: "direct main"
description:
name: app_links
sha256: "85ed8fc1d25a76475914fff28cc994653bd900bc2c26e4b57a49e097febb54ba"
sha256: "3ced568a5d9e309e99af71285666f1f3117bddd0bd5b3317979dccc1a40cada4"
url: "https://pub.dev"
source: hosted
version: "6.4.0"
app_links_linux:
dependency: transitive
description:
name: app_links_linux
sha256: f5f7173a78609f3dfd4c2ff2c95bd559ab43c80a87dc6a095921d96c05688c81
url: "https://pub.dev"
source: hosted
version: "1.0.3"
app_links_platform_interface:
dependency: transitive
description:
name: app_links_platform_interface
sha256: "05f5379577c513b534a29ddea68176a4d4802c46180ee8e2e966257158772a3f"
url: "https://pub.dev"
source: hosted
version: "2.0.2"
app_links_web:
dependency: transitive
description:
name: app_links_web
sha256: af060ed76183f9e2b87510a9480e56a5352b6c249778d07bd2c95fc35632a555
url: "https://pub.dev"
source: hosted
version: "1.0.4"
version: "3.5.1"
archive:
dependency: "direct main"
description:
@@ -346,10 +322,10 @@ packages:
dependency: "direct main"
description:
name: device_info_plus
sha256: "306b78788d1bb569edb7c55d622953c2414ca12445b41c9117963e03afc5c513"
sha256: a7fd703482b391a87d60b6061d04dfdeab07826b96f9abd8f5ed98068acc0074
url: "https://pub.dev"
source: hosted
version: "11.3.3"
version: "10.1.2"
device_info_plus_platform_interface:
dependency: transitive
description:
@@ -410,10 +386,10 @@ packages:
dependency: "direct main"
description:
name: ffi
sha256: "289279317b4b16eb2bb7e271abccd4bf84ec9bdcbe999e278a94b804f5630418"
sha256: "16ed7b077ef01ad6170a3d0c57caa4a112a38d7a2ed5602e0aca9ca6f3d98da6"
url: "https://pub.dev"
source: hosted
version: "2.1.4"
version: "2.1.3"
ffigen:
dependency: "direct dev"
description:
@@ -774,10 +750,10 @@ packages:
dependency: "direct main"
description:
name: launch_at_startup
sha256: "7db33398b76ec0ed9e27f9f4640553e239977437564046625e215be89c91f084"
sha256: "93fc5638e088290004fae358bae691486673d469957d461d9dae5b12248593eb"
url: "https://pub.dev"
source: hosted
version: "0.5.1"
version: "0.2.2"
leak_tracker:
dependency: transitive
description:
@@ -1378,10 +1354,10 @@ packages:
dependency: "direct main"
description:
name: tray_manager
sha256: c2da0f0f1ddb455e721cf68d05d1281fec75cf5df0a1d3cb67b6ca0bdfd5709d
sha256: "80be6c508159a6f3c57983de795209ac13453e9832fd574143b06dceee188ed2"
url: "https://pub.dev"
source: hosted
version: "0.4.0"
version: "0.3.2"
typed_data:
dependency: transitive
description:
@@ -1530,18 +1506,18 @@ packages:
dependency: "direct main"
description:
name: win32
sha256: dc6ecaa00a7c708e5b4d10ee7bec8c270e9276dfcab1783f57e9962d7884305f
sha256: "8b338d4486ab3fbc0ba0db9f9b4f5239b6697fcee427939a40e720cbb9ee0a69"
url: "https://pub.dev"
source: hosted
version: "5.12.0"
version: "5.9.0"
win32_registry:
dependency: "direct main"
description:
name: win32_registry
sha256: "6f1b564492d0147b330dd794fee8f512cec4977957f310f9951b5f9d83618dae"
sha256: "21ec76dfc731550fd3e2ce7a33a9ea90b828fdf19a5c3bcf556fa992cfa99852"
url: "https://pub.dev"
source: hosted
version: "2.1.0"
version: "1.1.5"
window_ext:
dependency: "direct main"
description:
@@ -1598,5 +1574,5 @@ packages:
source: hosted
version: "2.2.1"
sdks:
dart: ">=3.7.0 <4.0.0"
dart: ">=3.7.0-0 <4.0.0"
flutter: ">=3.24.0"

View File

@@ -1,7 +1,7 @@
name: fl_clash
description: A multi-platform proxy client based on ClashMeta, simple and easy to use, open-source and ad-free.
publish_to: 'none'
version: 0.8.82+202504151
version: 0.8.81+202504151
environment:
sdk: '>=3.1.0 <4.0.0'
@@ -20,14 +20,14 @@ dependencies:
path: plugins/proxy
window_ext:
path: plugins/window_ext
launch_at_startup: ^0.5.1
launch_at_startup: ^0.2.2
windows_single_instance: ^1.0.1
json_annotation: ^4.9.0
file_picker: ^8.0.3
mobile_scanner: ^6.0.2
app_links: ^6.4.0
win32_registry: ^2.0.0
tray_manager: ^0.4.0
app_links: ^3.5.0
win32_registry: ^1.1.5
tray_manager: ^0.3.2
collection: ^1.18.0
animations: ^2.0.11
package_info_plus: ^8.0.0
@@ -46,7 +46,7 @@ dependencies:
cached_network_image: ^3.4.0
hotkey_manager: ^0.2.3
uni_platform: ^0.1.3
device_info_plus: ^11.3.3
device_info_plus: ^10.1.2
connectivity_plus: ^6.1.0
screen_retriever: ^0.2.0
defer_pointer: ^0.0.2

View File

@@ -199,7 +199,6 @@ class Build {
required Mode mode,
required Target target,
Arch? arch,
bool stable = false,
}) async {
final isLib = mode == Mode.lib;
@@ -238,9 +237,7 @@ class Build {
if (isLib) {
env["CGO_ENABLED"] = "1";
env["CC"] = _getCc(item);
if (stable) {
env["CFLAGS"] = "-O3 -Werror";
}
env["CFLAGS"] = "-O3 -Werror";
} else {
env["CGO_ENABLED"] = "0";
}
@@ -248,7 +245,7 @@ class Build {
final execLines = [
"go",
"build",
if (stable) "-ldflags=-w -s",
"-ldflags=-w -s",
"-tags=$tags",
if (isLib) "-buildmode=c-shared",
"-o",
@@ -473,7 +470,6 @@ class BuildCommand extends Command {
target: target,
arch: arch,
mode: mode,
stable: env == "stable"
);
if (target == Target.windows) {