|
| 1 | +import AppIntents |
| 2 | +import Library |
| 3 | +import SwiftUI |
| 4 | +import WidgetKit |
| 5 | + |
| 6 | +struct ServiceToggleControl: ControlWidget { |
| 7 | + var body: some ControlWidgetConfiguration { |
| 8 | + StaticControlConfiguration( |
| 9 | + kind: ExtensionProfile.controlKind, |
| 10 | + provider: Provider() |
| 11 | + ) { value in |
| 12 | + ControlWidgetToggle( |
| 13 | + "sing-box", |
| 14 | + isOn: value, |
| 15 | + action: ToggleServiceIntent() |
| 16 | + ) { isOn in |
| 17 | + Label(isOn ? "Running" : "Stopped", systemImage: "shippingbox.fill") |
| 18 | + } |
| 19 | + .tint(.init(red: CGFloat(Double(69) / 255), green: CGFloat(Double(90) / 255), blue: CGFloat(Double(100) / 255))) |
| 20 | + } |
| 21 | + .displayName("Toggle") |
| 22 | + .description("Start or stop sing-box service.") |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +extension ServiceToggleControl { |
| 27 | + struct Provider: ControlValueProvider { |
| 28 | + var previewValue: Bool { |
| 29 | + false |
| 30 | + } |
| 31 | + |
| 32 | + func currentValue() async throws -> Bool { |
| 33 | + guard let extensionProfile = try await (ExtensionProfile.load()) else { |
| 34 | + return false |
| 35 | + } |
| 36 | + return extensionProfile.status.isStarted |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +struct ToggleServiceIntent: SetValueIntent, LiveActivityIntent { |
| 42 | + static var title: LocalizedStringResource = "Toggle sing-box" |
| 43 | + |
| 44 | + static var description = |
| 45 | + IntentDescription("Toggle sing-box service") |
| 46 | + |
| 47 | + @Parameter(title: "Running") |
| 48 | + var value: Bool |
| 49 | + |
| 50 | + func perform() async throws -> some IntentResult { |
| 51 | + guard let extensionProfile = try await (ExtensionProfile.load()) else { |
| 52 | + return .result() |
| 53 | + } |
| 54 | + if value { |
| 55 | + try await extensionProfile.start() |
| 56 | + } else { |
| 57 | + try await extensionProfile.stop() |
| 58 | + } |
| 59 | + return .result() |
| 60 | + } |
| 61 | +} |
0 commit comments