-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathrunner.swift
191 lines (167 loc) · 5.2 KB
/
runner.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
//
// Copyright (c) 2023-2024 PADL Software Pty Ltd
//
// Licensed under the Apache License, Version 2.0 (the License);
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import AsyncAlgorithms
import FlutterSwift
import Foundation
import Logging
#if canImport(AndroidLogging)
import AndroidLogging
#endif
private var NSEC_PER_SEC: UInt64 = 1_000_000_000
final class ChannelManager: @unchecked Sendable {
fileprivate static var shared: ChannelManager!
typealias Arguments = FlutterNull
typealias Event = Int32
typealias Stream = AsyncThrowingChannel<Event?, FlutterSwift.FlutterError>
var flutterBasicMessageChannel: FlutterSwift.FlutterBasicMessageChannel!
var flutterEventChannel: FlutterSwift.FlutterEventChannel!
var flutterMethodChannel: FlutterSwift.FlutterMethodChannel!
var task: Task<(), Error>?
var counter: Event = 0
var logger: Logger
let magicCookie = 0xCAFE_BABE
var flutterEventStream = Stream()
private func messageHandler(_ arguments: String?) async -> Int? {
logger.debug("received message \(String(describing: arguments))")
return magicCookie
}
@Sendable
private func onListen(_ arguments: Arguments?) throws -> FlutterEventStream<Event> {
flutterEventStream.eraseToAnyAsyncSequence()
}
@Sendable
private func onCancel(_ arguments: Arguments?) throws {
stop()
}
private func methodCallHandler(
call: FlutterSwift
.FlutterMethodCall<Int>
) async throws -> Bool {
logger.debug("received method call \(call)")
guard call.arguments == magicCookie else {
throw FlutterError(code: "bad cookie")
}
if task == nil {
run()
} else {
stop()
}
return task != nil
}
func run() {
task = Task {
repeat {
counter += 1
await flutterEventStream.send(counter)
logger.trace("counter is now \(counter)")
try await Task.sleep(nanoseconds: NSEC_PER_SEC)
} while !Task.isCancelled
logger.info("task was cancelled")
}
}
func stop() {
if let task {
logger.info("cancelling task...")
task.cancel()
self.task = nil
}
}
init(binaryMessenger: FlutterSwift.FlutterBinaryMessenger) {
#if canImport(Android)
LoggingSystem.bootstrap(AndroidLogHandler.taggedBySource)
#else
LoggingSystem.bootstrap(StreamLogHandler.standardError)
#endif
logger = Logger(label: "com.example.counter")
flutterBasicMessageChannel = FlutterBasicMessageChannel(
name: "com.example.counter.basic",
binaryMessenger: binaryMessenger,
codec: FlutterJSONMessageCodec.shared
)
flutterEventChannel = FlutterEventChannel(
name: "com.example.counter.events",
binaryMessenger: binaryMessenger
)
flutterMethodChannel = FlutterMethodChannel(
name: "com.example.counter.toggle",
binaryMessenger: binaryMessenger
)
Task {
try! await flutterBasicMessageChannel.setMessageHandler(messageHandler)
try! await flutterEventChannel.setStreamHandler(onListen: onListen, onCancel: onCancel)
try! await flutterMethodChannel.setMethodCallHandler(methodCallHandler)
run()
}
}
}
#if os(Linux) && canImport(Glibc)
extension ChannelManager {
convenience init(viewController: FlutterViewController) {
self.init(binaryMessenger: viewController.engine.binaryMessenger)
}
}
@main
enum Counter {
static func main() {
guard CommandLine.arguments.count > 1 else {
print("usage: Counter [flutter_path]")
exit(1)
}
let dartProject = DartProject(path: CommandLine.arguments[1])
let viewProperties = FlutterViewController.ViewProperties(
width: 800,
height: 480,
title: "Counter",
appId: "com.example.counter"
)
let window = FlutterWindow(properties: viewProperties, project: dartProject)
guard let window else {
exit(2)
}
_ = ChannelManager(viewController: window.viewController)
Task { @MainActor in
try await window.run()
}
RunLoop.main.run()
}
}
#elseif canImport(Android)
import FlutterAndroid
import JavaKit
import JavaRuntime
@JavaClass("com.example.counter.ChannelManager")
open class _ChannelManager: JavaObject {
@JavaField(isFinal: true)
public var binaryMessenger: FlutterAndroid.FlutterBinaryMessenger!
@JavaMethod
@_nonoverride
public convenience init(
_ binaryMessenger: FlutterAndroid.FlutterBinaryMessenger?,
environment: JNIEnvironment? = nil
)
}
protocol _ChannelManagerNativeMethods {
func initChannelManager()
}
@JavaImplementation("com.example.counter.ChannelManager")
extension _ChannelManager: _ChannelManagerNativeMethods {
@JavaMethod
public func initChannelManager() {
let wrappedMessenger = FlutterPlatformMessenger(wrapping: binaryMessenger!)
ChannelManager.shared = ChannelManager(binaryMessenger: wrappedMessenger)
}
}
#endif