This commit is contained in:
zeus
2025-01-22 16:22:33 +08:00
parent 09b9cec8ec
commit 738c373a77
2534 changed files with 0 additions and 486292 deletions
@@ -1,95 +0,0 @@
import Libbox
import Library
import SwiftUI
public struct CoreView: View {
@State private var isLoading = true
@State private var version = ""
@State private var dataSize = ""
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task {
await loadSettings()
}
}
} else {
FormView {
FormTextItem("Version", version)
FormTextItem("Data Size", dataSize)
Section("Working Directory") {
#if os(macOS)
FormButton {
NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: FilePath.workingDirectory.relativePath)
} label: {
Label("Open", systemImage: "macwindow.and.cursorarrow")
}
#endif
FormButton(role: .destructive) {
Task {
await destroyWorkingDirectory()
}
} label: {
Label("Destroy", systemImage: "trash.fill")
}
.foregroundColor(.red)
}
}
}
}
.navigationTitle("Core")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
private nonisolated func loadSettings() async {
if ApplicationLibrary.inPreview {
version = "<redacted>"
dataSize = LibboxFormatBytes(1000 * 1000 * 10)
isLoading = false
} else {
version = LibboxVersion()
dataSize = "Loading..."
isLoading = false
await loadSettingsBackground()
}
}
private nonisolated func loadSettingsBackground() async {
let dataSize = (try? FilePath.workingDirectory.formattedSize()) ?? "Unknown"
await MainActor.run {
self.dataSize = dataSize
}
}
private nonisolated func destroyWorkingDirectory() async {
try? FileManager.default.removeItem(at: FilePath.workingDirectory)
await MainActor.run {
isLoading = true
}
}
}
private extension URL {
func formattedSize() throws -> String? {
guard let urls = FileManager.default.enumerator(at: self, includingPropertiesForKeys: nil)?.allObjects as? [URL] else {
return nil
}
let size = try urls.lazy.reduce(0) {
try ($1.resourceValues(forKeys: [.totalFileAllocatedSizeKey]).totalFileAllocatedSize ?? 0) + $0
}
let formatter = ByteCountFormatter()
formatter.countStyle = .file
guard let byteCount = formatter.string(for: size) else {
return nil
}
return byteCount
}
}
@@ -1,152 +0,0 @@
#if os(macOS)
import AppKit
import Library
import ServiceManagement
import SwiftUI
public struct MacAppView: View {
@State private var isLoading = true
@State private var startAtLogin = false
@Environment(\.showMenuBarExtra) private var showMenuBarExtra
@State private var menuBarExtraInBackground = false
@State private var alert: Alert?
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task {
await loadSettings()
}
}
} else {
FormView {
FormToggle("Start At Login", "Launch the application when the system is logged in. If enabled at the same time as `Show in Menu Bar` and `Keep Menu Bar in Background`, the application interface will not be opened automatically.", $startAtLogin) { newValue in
updateLoginItems(newValue)
}
Toggle("Show in Menu Bar", isOn: showMenuBarExtra)
.onChangeCompat(of: showMenuBarExtra.wrappedValue) { newValue in
Task {
await SharedPreferences.showMenuBarExtra.set(newValue)
if !newValue {
menuBarExtraInBackground = false
}
}
}
if showMenuBarExtra.wrappedValue {
Toggle("Keep Menu Bar in Background", isOn: $menuBarExtraInBackground)
.onChangeCompat(of: menuBarExtraInBackground) { newValue in
Task {
await SharedPreferences.menuBarExtraInBackground.set(newValue)
}
}
}
if Variant.useSystemExtension {
Section("System Extension") {
FormButton {
Task {
await updateSystemExtension()
}
} label: {
Label("Update", systemImage: "arrow.down.doc.fill")
}
FormButton(role: .destructive) {
Task {
await uninstallSystemExtension()
}
} label: {
Label("Uninstall", systemImage: "trash.fill").foregroundColor(.red)
}
}
}
}
}
}
.alertBinding($alert)
.navigationTitle("App")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
private func loadSettings() async {
startAtLogin = SMAppService.mainApp.status == .enabled
menuBarExtraInBackground = await SharedPreferences.menuBarExtraInBackground.get()
isLoading = false
}
private func updateLoginItems(_ startAtLogin: Bool) {
do {
if startAtLogin {
if SMAppService.mainApp.status == .enabled {
try? SMAppService.mainApp.unregister()
}
try SMAppService.mainApp.register()
} else {
try SMAppService.mainApp.unregister()
}
} catch {
alert = Alert(error)
}
}
private func updateSystemExtension() async {
do {
if let result = try await SystemExtension.install(forceUpdate: true) {
switch result {
case .completed:
alert = Alert(
title: Text("Update"),
message: Text("System Extension updated."),
dismissButton: .default(Text("Ok")) {}
)
case .willCompleteAfterReboot:
alert = Alert(
title: Text("Update"),
message: Text("Reboot required."),
dismissButton: .default(Text("Ok")) {}
)
@unknown default:
fatalError()
}
}
} catch {
alert = Alert(error)
}
}
private func uninstallSystemExtension() async {
do {
if let result = try await SystemExtension.uninstall() {
switch result {
case .completed:
alert = Alert(
title: Text("Uninstall"),
message: Text("System Extension removed."),
dismissButton: .default(Text("Ok")) {}
)
case .willCompleteAfterReboot:
alert = Alert(
title: Text("Uninstall"),
message: Text("Reboot required."),
dismissButton: .default(Text("Ok")) {}
)
@unknown default:
fatalError()
}
}
} catch {
alert = Alert(error)
}
}
}
#endif
@@ -1,50 +0,0 @@
import Foundation
import Library
import SwiftUI
public struct OnDemandRulesView: View {
@State private var isLoading = true
@State private var alwaysOn = false
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task.detached {
await loadSettings()
}
}
} else {
FormView {
FormToggle("Always On", """
Implement always-on via on-demand rules.
This should not be an intended use of the API, so you cannot disable VPN in system settings. To stop the service manually, use the in-app interface or simply delete the VPN profile.
""", $alwaysOn) { newValue in
await SharedPreferences.alwaysOn.set(newValue)
}
FormButton {
Task {
await SharedPreferences.resetOnDemandRules()
isLoading = true
}
} label: {
Label("Reset", systemImage: "eraser.fill")
}
.foregroundColor(.red)
}
}
}
.navigationTitle("On Demand Rules")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
private func loadSettings() async {
alwaysOn = await SharedPreferences.alwaysOn.get()
isLoading = false
}
}
@@ -1,108 +0,0 @@
import Library
import SwiftUI
public struct PacketTunnelView: View {
@State private var isLoading = true
@State private var ignoreMemoryLimit = false
@State private var includeAllNetworks = false
@State private var excludeAPNs = false
@State private var excludeCellularServices = false
@State private var excludeLocalNetworks = false
@State private var enforceRoutes = false
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task.detached {
await loadSettings()
}
}
} else {
FormView {
FormToggle("Ignore Memory Limit", """
Do not enforce memory limits on sing-box. Will cause OOM on non-jailbroken iOS and tvOS devices.
""", $ignoreMemoryLimit) { newValue in
await SharedPreferences.ignoreMemoryLimit.set(newValue)
}
#if !os(tvOS)
FormToggle("includeAllNetworks", """
If this property is true, the system routes network traffic through the tunnel except traffic for designated system services necessary for maintaining expected device functionality. You can exclude some types of traffic using the **excludeAPNs**, **excludeLocalNetworks**, and **excludeCellularServices** properties in combination with this property.
when enabled, the default TUN stack is changed to `gvisor`, and the `system` and `mixed` stacks are not available.
[Apple Documentation](https://developer.apple.com/documentation/networkextension/nevpnprotocol/3131931-includeallnetworks)
""", $includeAllNetworks) { newValue in
await SharedPreferences.includeAllNetworks.set(newValue)
}
FormToggle("excludeAPNs", """
If this property is true, the system excludes Apple Push Notification services (APNs) traffic, but only when the **includeAllNetworks** property is also true.
[Apple Documentation](https://developer.apple.com/documentation/networkextension/nevpnprotocol/4140516-excludeapns)
""", $excludeAPNs) { newValue in
await SharedPreferences.excludeAPNs.set(newValue)
}
FormToggle("excludeCellularServices", """
If this property is true, the system excludes cellular services — such as Wi-Fi Calling, MMS, SMS, and Visual Voicemail — but only when the **includeAllNetworks** property is also true. This property doesnt impact services that use the cellular network only — such as VoLTE — which the system automatically excludes.
[Apple Documentation](https://developer.apple.com/documentation/networkextension/nevpnprotocol/4140517-excludecellularservices)
""", $excludeCellularServices) { newValue in
await SharedPreferences.excludeCellularServices.set(newValue)
}
FormToggle("excludeLocalNetworks", """
If this property is true, the system excludes network connections to hosts on the local network — such as AirPlay, AirDrop, and CarPlay — but only when the **includeAllNetworks** or **enforceRoutes** property is also true.
[Apple Documentation](https://developer.apple.com/documentation/networkextension/nevpnprotocol/3143658-excludelocalnetworks)
""", $excludeLocalNetworks) { newValue in
await SharedPreferences.excludeLocalNetworks.set(newValue)
}
FormToggle("enforceRoutes", """
If this property is true when the **includeAllNetworks** property is false, the system scopes the included routes to the VPN and the excluded routes to the current primary network interface. This property supersedes the system routing table and scoping operations by apps.
If you set both the **enforceRoutes** and **excludeLocalNetworks** properties to true, the system excludes network connections to hosts on the local network.
[Apple Documentation](https://developer.apple.com/documentation/networkextension/nevpnprotocol/3689459-enforceroutes)
""", $enforceRoutes) { newValue in
await SharedPreferences.enforceRoutes.set(newValue)
}
#endif
FormButton {
Task {
await SharedPreferences.resetPacketTunnel()
isLoading = true
}
} label: {
Label("Reset", systemImage: "eraser.fill")
}
.foregroundColor(.red)
}
}
}
.navigationTitle("Packet Tunnel")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
private func loadSettings() async {
ignoreMemoryLimit = await SharedPreferences.ignoreMemoryLimit.get()
#if !os(tvOS)
includeAllNetworks = await SharedPreferences.includeAllNetworks.get()
excludeAPNs = await SharedPreferences.excludeAPNs.get()
excludeCellularServices = await SharedPreferences.excludeCellularServices.get()
excludeLocalNetworks = await SharedPreferences.excludeLocalNetworks.get()
enforceRoutes = await SharedPreferences.enforceRoutes.get()
#endif
isLoading = false
}
}
@@ -1,59 +0,0 @@
import Library
import SwiftUI
public struct ProfileOverrideView: View {
@State private var isLoading = true
@State private var excludeDefaultRoute = false
@State private var autoRouteUseSubRangesByDefault = false
@State private var excludeAPNsRoute = false
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task.detached {
await loadSettings()
}
}
} else {
FormView {
FormToggle("Hide VPN Icon", "Append `0.0.0.0/31` to `inet4_route_exclude_address` if not exists.", $excludeDefaultRoute) { newValue in
await SharedPreferences.excludeDefaultRoute.set(newValue)
}
FormToggle("No Default Route", """
By default, segment routing is used in `auto_route` instead of global routing. If `*_<route_address/route_exclude_address>` exists in the configuration, this item will not take effect on the corresponding network (commonly used to resolve HomeKit compatibility issues).
""", $autoRouteUseSubRangesByDefault) { newValue in
await SharedPreferences.autoRouteUseSubRangesByDefault.set(newValue)
}
FormToggle("Exclude APNs Route", "Append `push.apple.com` to `bypass_domain`, and `17.0.0.0/8` to `inet4_route_exclude_address`.", $excludeAPNsRoute) { newValue in
await SharedPreferences.excludeAPNsRoute.set(newValue)
}
FormButton {
Task {
await SharedPreferences.resetProfileOverride()
isLoading = true
}
} label: {
Label("Reset", systemImage: "eraser.fill")
}
.foregroundColor(.red)
}
}
}
.navigationTitle("Profile Override")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
private func loadSettings() async {
excludeDefaultRoute = await SharedPreferences.excludeDefaultRoute.get()
autoRouteUseSubRangesByDefault = await SharedPreferences.autoRouteUseSubRangesByDefault.get()
excludeAPNsRoute = await SharedPreferences.excludeAPNsRoute.get()
isLoading = false
}
}
@@ -1,112 +0,0 @@
import Foundation
import Library
import SwiftUI
@MainActor
public struct ServiceLogView: View {
@Environment(\.dismiss) private var dismiss
@State private var isLoading = true
@State private var content = ""
@State private var alert: Alert?
private let logFont = Font.system(.caption, design: .monospaced)
public init() {}
public var body: some View {
viewBuilder {
if isLoading {
ProgressView().onAppear {
Task {
await loadContent()
}
}
} else {
if content.isEmpty {
Text("Empty content")
} else {
ScrollView {
Text(content)
.font(logFont)
.frame(maxWidth: .infinity, alignment: .topLeading)
}
.padding()
}
}
}
.toolbar {
if !content.isEmpty {
#if !os(tvOS)
ShareButtonCompat($alert) {
Label("Export", systemImage: "square.and.arrow.up.fill")
} itemURL: {
try content.generateShareFile(name: "service.log")
}
#endif
Button(role: .destructive) {
Task {
await deleteContent()
}
} label: {
#if !os(tvOS)
Label("Delete", systemImage: "trash.fill")
#else
Image(systemName: "trash.fill")
#endif
}
}
}
.alertBinding($alert)
.navigationTitle("Service Log")
#if os(tvOS)
.focusable()
#endif
}
private nonisolated func loadContent() async {
var content = ""
do {
content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log"))
} catch {}
if content.isEmpty {
do {
content = try String(contentsOf: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old"))
} catch {}
}
#if DEBUG
if content.isEmpty {
content = "Empty content"
}
#endif
if !content.isEmpty {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let machineName = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
var deviceInfo = "Machine: " + machineName + "\n"
#if os(iOS)
await deviceInfo += "System: " + (UIDevice.current.systemName) + " " + (UIDevice.current.systemVersion) + "\n"
#elseif os(macOS)
deviceInfo += "System: macOS " + ProcessInfo().operatingSystemVersionString + "\n"
#endif
content = deviceInfo + "\n" + content
}
await MainActor.run { [content] in
self.content = content
isLoading = false
}
}
private nonisolated func deleteContent() async {
try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log"))
try? FileManager.default.removeItem(at: FilePath.cacheDirectory.appendingPathComponent("stderr.log.old"))
await MainActor.run {
dismiss()
isLoading = true
}
}
}
@@ -1,154 +0,0 @@
import Library
import SwiftUI
public struct SettingView: View {
private enum Tabs: Int, CaseIterable, Identifiable {
public var id: Self {
self
}
#if os(macOS)
case app
#endif
case core, packetTunnel, onDemandRules, profileOverride, sponsors
var label: some View {
Label(title, systemImage: iconImage)
}
var title: String {
switch self {
#if os(macOS)
case .app:
return NSLocalizedString("App", comment: "")
#endif
case .core:
return NSLocalizedString("Core", comment: "")
case .packetTunnel:
return NSLocalizedString("Packet Tunnel", comment: "")
case .onDemandRules:
return NSLocalizedString("On Demand Rules", comment: "")
case .profileOverride:
return NSLocalizedString("Profile Override", comment: "")
case .sponsors:
return NSLocalizedString("Sponsors", comment: "")
}
}
private var iconImage: String {
switch self {
#if os(macOS)
case .app:
return "app.badge.fill"
#endif
case .core:
return "shippingbox.fill"
case .packetTunnel:
return "aspectratio.fill"
case .onDemandRules:
return "filemenu.and.selection"
case .profileOverride:
return "square.dashed.inset.filled"
case .sponsors:
return "heart.fill"
}
}
@MainActor
var contentView: some View {
viewBuilder {
switch self {
#if os(macOS)
case .app:
MacAppView()
#endif
case .core:
CoreView()
case .packetTunnel:
PacketTunnelView()
case .onDemandRules:
OnDemandRulesView()
case .profileOverride:
ProfileOverrideView()
case .sponsors:
SponsorsView()
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
#if os(iOS)
.background(Color(uiColor: .systemGroupedBackground))
#endif
}
@MainActor
var navigationLink: some View {
FormNavigationLink {
contentView
} label: {
label
}
}
}
@State private var isLoading = true
@State private var taiwanFlagAvailable = false
public init() {}
public var body: some View {
FormView {
#if os(macOS)
Tabs.app.navigationLink
#endif
ForEach([Tabs.core, Tabs.packetTunnel, Tabs.onDemandRules, Tabs.profileOverride]) { it in
it.navigationLink
}
#if !os(tvOS)
Section("About") {
Link(destination: URL(string: "https://sing-box.sagernet.org/")!) {
Label("Documentation", systemImage: "doc.on.doc.fill")
}
.buttonStyle(.plain)
.foregroundColor(.accentColor)
RequestReviewButton {
Label("Rate on the App Store", systemImage: "text.bubble.fill")
}
#if os(macOS)
if Variant.useSystemExtension {
Tabs.sponsors.navigationLink
}
#endif
}
#endif
Section("Debug") {
FormNavigationLink {
ServiceLogView()
} label: {
Label("Service Log", systemImage: "doc.on.clipboard")
}
FormTextItem("Taiwan Flag Available", "touchid") {
if isLoading {
Text("Loading...")
.onAppear {
Task.detached {
let available: Bool
if ApplicationLibrary.inPreview {
available = true
} else {
available = !DeviceCensorship.isChinaDevice()
}
await MainActor.run {
taiwanFlagAvailable = available
isLoading = false
}
}
}
} else {
Text(taiwanFlagAvailable.description)
}
}
}
}
}
}
@@ -1,29 +0,0 @@
import Foundation
import SwiftUI
public struct SponsorsView: View {
@Environment(\.openURL) private var openURL
public init() {}
public var body: some View {
FormView {
Section {
EmptyView()
} footer: {
Text("**If Ive defended your modern life, please consider sponsoring me.**")
.frame(maxWidth: .infinity, alignment: .leading)
}
FormButton("GitHub Sponsor (recommended)") {
openURL(URL(string: "https://github.com/sponsors/nekohasekai")!)
}
FormButton("Other methods") {
openURL(URL(string: "https://sekai.icu/sponsors/")!)
}
}
.navigationTitle("Sponsors")
#if os(iOS)
.navigationBarTitleDisplayMode(.inline)
#endif
}
}