Refactor command client

This commit is contained in:
世界
2023-08-15 17:20:44 +08:00
parent 1ac5df7f72
commit dbd8700145
20 changed files with 378 additions and 572 deletions
@@ -1,120 +0,0 @@
import Foundation
import Libbox
import Library
import SwiftUI
public class LogClient: ObservableObject {
private var maxLines: Int
@Published public var isConnected: Bool
@Published public var logList: [String]
private var commandClient: LibboxCommandClient!
private var connectTask: Task<Void, Error>?
public init(_ maxLines: Int) {
self.maxLines = maxLines
isConnected = false
logList = []
}
deinit {
if let connectTask {
connectTask.cancel()
}
if let commandClient {
try? commandClient.disconnect()
}
}
public func reconnect() {
if ApplicationLibrary.inPreview {
logList = [
"(packet-tunnel) log server started",
"INFO[0000] router: loaded geoip database: 250 codes",
"INFO[0000] router: loaded geosite database: 1400 codes",
"INFO[0000] router: updated default interface en0, index 11",
"inbound/tun[0]: started at utun3",
"sing-box started (1.666s)",
]
isConnected = true
} else {
if isConnected {
return
}
if let connectTask {
connectTask.cancel()
}
connectTask = Task.detached {
await self.connect()
}
}
}
private func connect() async {
let clientOptions = LibboxCommandClientOptions()
clientOptions.command = LibboxCommandLog
clientOptions.statusInterval = Int64(2 * NSEC_PER_SEC)
let client = LibboxNewCommandClient(FilePath.sharedDirectory.relativePath, logHandler(self), clientOptions)!
do {
for i in 0 ..< 10 {
try await Task.sleep(nanoseconds: UInt64(Double(100 + (i * 50)) * Double(NSEC_PER_MSEC)))
try Task.checkCancellation()
let isConnected: Bool
do {
try client.connect()
isConnected = true
} catch {
isConnected = false
}
try Task.checkCancellation()
if isConnected {
commandClient = client
return
}
}
} catch {
try? client.disconnect()
}
}
private class logHandler: NSObject, LibboxCommandClientHandlerProtocol {
private let logClient: LogClient
init(_ logClient: LogClient) {
self.logClient = logClient
}
@MainActor
func connected() {
logClient.logList.removeAll()
logClient.isConnected = true
}
@MainActor
func disconnected(_ message: String?) {
if let message {
logClient.logList.append("(log client closed) \(message)")
} else {
logClient.logList.append("(log client closed)")
}
try? logClient.commandClient?.disconnect()
logClient.commandClient = nil
logClient.isConnected = false
}
@MainActor
func writeLog(_ message: String?) {
guard let message else {
return
}
if logClient.logList.count > logClient.maxLines {
logClient.logList.removeFirst()
}
logClient.logList.append(message)
}
func writeStatus(_: LibboxStatusMessage?) {}
func writeGroups(_: LibboxOutboundGroupIteratorProtocol?) {}
}
}
+38 -65
View File
@@ -1,80 +1,53 @@
import Library
import SwiftUI
public struct LogView: View {
@Environment(\.logClient) private var logClient
@Environment(\.selection) private var selection
@EnvironmentObject private var environments: ExtensionEnvironments
private let logFont = Font.system(.caption2, design: .monospaced)
public init() {}
public var body: some View {
viewBuilder {
if let logClient = logClient.wrappedValue {
LogView0().environmentObject(logClient)
} else {
Text("Service not started")
}
}
}
private struct LogView0: View {
@Environment(\.selection) private var selection
@Environment(\.extensionProfile) private var extensionProfile
@EnvironmentObject private var logClient: LogClient
private let logFont = Font.system(.caption2, design: .monospaced)
var body: some View {
viewBuilder {
if logClient.logList.isEmpty {
VStack {
if logClient.isConnected {
Text("Empty logs")
} else {
Text("Service not started").onAppear(perform: connectLog)
}
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
if environments.logClient.logList.isEmpty {
VStack {
if environments.logClient.isConnected {
Text("Empty logs")
} else {
ScrollViewReader { reader in
ScrollView {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(logClient.logList.enumerated()), id: \.offset) { it in
Text(it.element)
.font(logFont)
#if os(tvOS)
.focusable()
#endif
Spacer(minLength: 8)
}
.onChangeCompat(of: logClient.logList.count) { newCount in
withAnimation {
reader.scrollTo(newCount - 1)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding()
}
#if os(tvOS)
.focusEffectDisabled()
.focusSection()
#endif
.onAppear {
reader.scrollTo(logClient.logList.count - 1)
}
Text("Service not started").onAppear {
environments.connectLog()
}
}
}
}
}.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
} else {
ScrollViewReader { reader in
ScrollView {
VStack(alignment: .leading, spacing: 0) {
ForEach(Array(environments.logClient.logList.enumerated()), id: \.offset) { it in
Text(it.element)
.font(logFont)
#if os(tvOS)
.focusable()
#endif
Spacer(minLength: 8)
}
private func connectLog() {
if ApplicationLibrary.inPreview {
logClient.reconnect()
} else {
guard let profile = extensionProfile.wrappedValue else {
return
.onChangeCompat(of: environments.logClient.logList.count) { newCount in
withAnimation {
reader.scrollTo(newCount - 1)
}
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
.padding()
}
if profile.status.isConnected, !logClient.isConnected {
logClient.reconnect()
#if os(tvOS)
.focusEffectDisabled()
.focusSection()
#endif
.onAppear {
reader.scrollTo(environments.logClient.logList.count - 1)
}
}
}