Unverified Commit 99146c20 authored by Chris Bracken's avatar Chris Bracken Committed by GitHub

[macOS] platform_channel sample style cleanups (#123569)

[macOS] platform_channel sample style cleanups
parent b0ad7c45
...@@ -5,15 +5,16 @@ ...@@ -5,15 +5,16 @@
import Cocoa import Cocoa
import FlutterMacOS import FlutterMacOS
class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeDelegate { class MainFlutterWindow: NSWindow {
private let powerSource = PowerSource() private let powerSource = PowerSource()
private let stateChangeSource = PowerSourceStateChangeHandler() private let stateChangeHandler = PowerSourceStateChangeHandler()
private var eventSink: FlutterEventSink? private var eventSink: FlutterEventSink?
override func awakeFromNib() { override func awakeFromNib() {
let flutterViewController = FlutterViewController() let flutterViewController = FlutterViewController()
let windowFrame = self.frame let windowFrame = self.frame
self.contentViewController = flutterViewController self.contentViewController = flutterViewController
self.displayIfNeeded()
self.setFrame(windowFrame, display: true) self.setFrame(windowFrame, display: true)
// Register battery method channel. // Register battery method channel.
...@@ -21,18 +22,18 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD ...@@ -21,18 +22,18 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD
let batteryChannel = FlutterMethodChannel( let batteryChannel = FlutterMethodChannel(
name: "samples.flutter.io/battery", name: "samples.flutter.io/battery",
binaryMessenger: registrar.messenger) binaryMessenger: registrar.messenger)
batteryChannel.setMethodCallHandler({ [weak self] (call, result) in batteryChannel.setMethodCallHandler { [powerSource = self.powerSource] (call, result) in
switch call.method { switch call.method {
case "getBatteryLevel": case "getBatteryLevel":
if self?.powerSource.hasBattery() == false { guard powerSource.hasBattery() else {
result(FlutterError( result(
code: "NO_BATTERY", FlutterError(
message: "Device does not have a battery", code: "NO_BATTERY",
details: nil)) message: "Device does not have a battery",
details: nil))
return return
} }
let level = self?.powerSource.getCurrentCapacity() guard let level = powerSource.getCurrentCapacity() else {
if level == -1 {
result( result(
FlutterError( FlutterError(
code: "UNAVAILABLE", code: "UNAVAILABLE",
...@@ -44,7 +45,7 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD ...@@ -44,7 +45,7 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD
default: default:
result(FlutterMethodNotImplemented) result(FlutterMethodNotImplemented)
} }
}) }
// Register charging event channel. // Register charging event channel.
let chargingChannel = FlutterEventChannel( let chargingChannel = FlutterEventChannel(
...@@ -57,36 +58,40 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD ...@@ -57,36 +58,40 @@ class MainFlutterWindow: NSWindow, FlutterStreamHandler, PowerSourceStateChangeD
super.awakeFromNib() super.awakeFromNib()
} }
/// Emit a power status event to the registered event sink.
func emitPowerStatusEvent() {
if let sink = self.eventSink {
switch self.powerSource.getPowerState() {
case .ac:
sink("charging")
case .battery:
sink("discharging")
case .unknown:
sink("UNAVAILABLE")
}
}
}
}
extension MainFlutterWindow: FlutterStreamHandler {
func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink)
-> FlutterError? -> FlutterError?
{ {
self.eventSink = events self.eventSink = events
self.emitPowerStatusEvent() self.emitPowerStatusEvent()
self.stateChangeSource.delegate = self self.stateChangeHandler.delegate = self
return nil return nil
} }
func onCancel(withArguments arguments: Any?) -> FlutterError? { func onCancel(withArguments arguments: Any?) -> FlutterError? {
self.stateChangeSource.delegate = nil self.stateChangeHandler.delegate = nil
self.eventSink = nil self.eventSink = nil
return nil return nil
} }
}
func onPowerSourceStateChanged() { extension MainFlutterWindow: PowerSourceStateChangeDelegate {
func didChangePowerSourceState() {
self.emitPowerStatusEvent() self.emitPowerStatusEvent()
} }
func emitPowerStatusEvent() {
if let sink = self.eventSink {
switch self.powerSource.getPowerState() {
case .ac:
sink("charging")
case .battery:
sink("discharging")
case .unknown:
sink("UNAVAILABLE")
}
}
}
} }
...@@ -12,9 +12,13 @@ enum PowerState { ...@@ -12,9 +12,13 @@ enum PowerState {
} }
/// A convenience wrapper for an IOKit power source. /// A convenience wrapper for an IOKit power source.
class PowerSource { final class PowerSource {
let info = IOPSCopyPowerSourcesInfo().takeRetainedValue() let info = IOPSCopyPowerSourcesInfo().takeRetainedValue()
lazy var sources = IOPSCopyPowerSourcesList(info).takeRetainedValue() as Array let sources: Array<CFTypeRef>
init() {
sources = IOPSCopyPowerSourcesList(info).takeRetainedValue() as Array
}
func hasBattery() -> Bool { func hasBattery() -> Bool {
return !sources.isEmpty return !sources.isEmpty
...@@ -22,7 +26,7 @@ class PowerSource { ...@@ -22,7 +26,7 @@ class PowerSource {
/// Returns the current power source capacity. Apple-defined power sources will return this value /// Returns the current power source capacity. Apple-defined power sources will return this value
/// as a percentage. /// as a percentage.
func getCurrentCapacity() -> Int { func getCurrentCapacity() -> Int? {
if let source = sources.first { if let source = sources.first {
let description = let description =
IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [String: AnyObject] IOPSGetPowerSourceDescription(info, source).takeUnretainedValue() as! [String: AnyObject]
...@@ -30,7 +34,7 @@ class PowerSource { ...@@ -30,7 +34,7 @@ class PowerSource {
return level return level
} }
} }
return -1 return nil
} }
/// Returns whether the device is drawing battery power or connected to an external power source. /// Returns whether the device is drawing battery power or connected to an external power source.
...@@ -54,11 +58,11 @@ class PowerSource { ...@@ -54,11 +58,11 @@ class PowerSource {
} }
protocol PowerSourceStateChangeDelegate: AnyObject { protocol PowerSourceStateChangeDelegate: AnyObject {
func onPowerSourceStateChanged() func didChangePowerSourceState()
} }
/// A listener for system power source state change events. Notifies the delegate on each event. /// A listener for system power source state change events. Notifies the delegate on each event.
class PowerSourceStateChangeHandler { final class PowerSourceStateChangeHandler {
private var runLoopSource: CFRunLoopSource? private var runLoopSource: CFRunLoopSource?
weak var delegate: PowerSourceStateChangeDelegate? weak var delegate: PowerSourceStateChangeDelegate?
...@@ -66,10 +70,10 @@ class PowerSourceStateChangeHandler { ...@@ -66,10 +70,10 @@ class PowerSourceStateChangeHandler {
let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
self.runLoopSource = IOPSNotificationCreateRunLoopSource( self.runLoopSource = IOPSNotificationCreateRunLoopSource(
{ (context: UnsafeMutableRawPointer?) in { (context: UnsafeMutableRawPointer?) in
let weakSelf = Unmanaged<PowerSourceStateChangeHandler>.fromOpaque( let unownedSelf = Unmanaged<PowerSourceStateChangeHandler>.fromOpaque(
UnsafeRawPointer(context!) UnsafeRawPointer(context!)
).takeUnretainedValue() ).takeUnretainedValue()
weakSelf.delegate?.onPowerSourceStateChanged() unownedSelf.delegate?.didChangePowerSourceState()
}, context }, context
).takeRetainedValue() ).takeRetainedValue()
CFRunLoopAddSource(CFRunLoopGetCurrent(), self.runLoopSource, .defaultMode) CFRunLoopAddSource(CFRunLoopGetCurrent(), self.runLoopSource, .defaultMode)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment