Swift 6.4 migration and exhancements (#1)
This PR contains the work done to update the library and the attached example project to use the Swift 6.4 computer as a minimum supported version and also, to use the latest features introduced in it. Reviewed-on: #1 Co-authored-by: Javier Cicchelli <javier@rock-n-code.com>
This commit was merged in pull request #1.
This commit is contained in:
@@ -4,46 +4,44 @@ internal import CPlaydate
|
||||
public enum System {}
|
||||
|
||||
extension System {
|
||||
/// The cached `playdate->system` C API table.
|
||||
/// Cached `playdate->system` table.
|
||||
private static var api: UnsafePointer<playdate_sys> { Playdate.systemAPI.unsafelyUnwrapped }
|
||||
|
||||
// MARK: - Memory
|
||||
|
||||
/// The system allocator. Pass `nil` to allocate, `size` 0 to free.
|
||||
/// System allocator (`realloc` semantics): `nil` allocates; `size` 0 frees, returns `nil`.
|
||||
@discardableResult
|
||||
public static func realloc(_ pointer: UnsafeMutableRawPointer?, size: Int) -> UnsafeMutableRawPointer? {
|
||||
api.pointee.realloc.unsafelyUnwrapped(pointer, size)
|
||||
}
|
||||
|
||||
/// Frees memory that the Playdate OS handed to the caller (e.g. strings
|
||||
/// returned by `localizedText(forKey:)`).
|
||||
/// Frees OS-allocated memory, e.g. `localizedText(forKey:language:)` strings.
|
||||
static func systemFree(_ pointer: UnsafeMutableRawPointer?) {
|
||||
_ = api.pointee.realloc.unsafelyUnwrapped(pointer, 0)
|
||||
}
|
||||
|
||||
// MARK: - Logging
|
||||
|
||||
/// Logs a message to the console (device serial or simulator console).
|
||||
/// Logs to the device serial or simulator console.
|
||||
public static func log(_ message: String) {
|
||||
message.withPlaydateCString { cplaydate_log(Playdate.apiPointer, $0) }
|
||||
message.withCString { cplaydate_log(Playdate.apiPointer, $0) }
|
||||
}
|
||||
|
||||
/// Stops execution and displays the message as a fatal error.
|
||||
/// Logs `message` as an error, then pauses execution.
|
||||
public static func error(_ message: String) {
|
||||
message.withPlaydateCString { cplaydate_error(Playdate.apiPointer, $0) }
|
||||
message.withCString { cplaydate_error(Playdate.apiPointer, $0) }
|
||||
}
|
||||
|
||||
// MARK: - Time
|
||||
// MARK: - Language and time
|
||||
|
||||
/// The system language setting.
|
||||
public static var language: Language { Language(api.pointee.getLanguage.unsafelyUnwrapped()) }
|
||||
|
||||
/// Milliseconds since the game launched. Wraps around after about 49 days.
|
||||
/// Milliseconds since an arbitrary point; pauses while asleep; wraps after ~49 days.
|
||||
public static var currentTimeMilliseconds: UInt32 {
|
||||
UInt32(api.pointee.getCurrentTimeMilliseconds.unsafelyUnwrapped())
|
||||
}
|
||||
|
||||
/// Seconds (and sub-second milliseconds) since midnight 2000-01-01 UTC.
|
||||
/// Seconds, plus millisecond remainder, since 2000-01-01 00:00 UTC.
|
||||
public static var secondsSinceEpoch: (seconds: UInt32, milliseconds: UInt32) {
|
||||
var milliseconds: UInt32 = 0
|
||||
let seconds = withUnsafeMutablePointer(to: &milliseconds) {
|
||||
@@ -52,41 +50,39 @@ extension System {
|
||||
return (UInt32(seconds), milliseconds)
|
||||
}
|
||||
|
||||
/// High-resolution timer value, in seconds.
|
||||
/// Seconds since `resetElapsedTime()`, with microsecond accuracy.
|
||||
public static var elapsedTime: Float { api.pointee.getElapsedTime.unsafelyUnwrapped() }
|
||||
|
||||
/// Resets the high-resolution timer to zero.
|
||||
public static func resetElapsedTime() { api.pointee.resetElapsedTime.unsafelyUnwrapped() }
|
||||
|
||||
/// Offset from UTC of the user-set timezone, in seconds.
|
||||
/// Offset from UTC, in seconds.
|
||||
public static var timezoneOffset: Int32 { api.pointee.getTimezoneOffset.unsafelyUnwrapped() }
|
||||
|
||||
/// Whether the user prefers 24-hour time display.
|
||||
/// The user's 24-hour time setting.
|
||||
public static var shouldDisplay24HourTime: Bool {
|
||||
api.pointee.shouldDisplay24HourTime.unsafelyUnwrapped() != 0
|
||||
}
|
||||
|
||||
/// Converts seconds since the 2000-01-01 epoch to a calendar date.
|
||||
/// `epoch` is seconds since 2000-01-01.
|
||||
public static func convertEpochToDateTime(_ epoch: UInt32) -> DateTime {
|
||||
var dateTime = PDDateTime()
|
||||
api.pointee.convertEpochToDateTime.unsafelyUnwrapped(epoch, &dateTime)
|
||||
return DateTime(dateTime)
|
||||
}
|
||||
|
||||
/// Converts a calendar date to seconds since the 2000-01-01 epoch.
|
||||
/// Returns seconds since 2000-01-01.
|
||||
public static func convertDateTimeToEpoch(_ dateTime: DateTime) -> UInt32 {
|
||||
var cValue = dateTime.cValue
|
||||
return api.pointee.convertDateTimeToEpoch.unsafelyUnwrapped(&cValue)
|
||||
}
|
||||
|
||||
/// Blocks execution for the given number of milliseconds.
|
||||
/// Blocks execution.
|
||||
public static func delay(milliseconds: UInt32) {
|
||||
api.pointee.delay.unsafelyUnwrapped(milliseconds)
|
||||
}
|
||||
|
||||
/// Requests the server time. The completion receives the time string or
|
||||
/// an error string. Only one request is tracked at a time; a second call
|
||||
/// before the first completes replaces the stored completion.
|
||||
/// Asynchronously fetches the server time: `time` is seconds since 2000-01-01 UTC,
|
||||
/// as a string. One completion at a time; calling again replaces a pending one.
|
||||
public static func getServerTime(_ completion: @escaping (_ time: String?, _ error: String?) -> Void) {
|
||||
serverTimeCompletion = completion
|
||||
api.pointee.getServerTime.unsafelyUnwrapped { time, error in
|
||||
@@ -100,7 +96,7 @@ extension System {
|
||||
|
||||
// MARK: - Update loop
|
||||
|
||||
/// Sets the per-frame update callback. Return `true` to redraw the display.
|
||||
/// Sets the per-frame callback, replacing any previous one; return `true` to redraw.
|
||||
public static func setUpdateCallback(_ callback: @escaping () -> Bool) {
|
||||
updateCallback = callback
|
||||
api.pointee.setUpdateCallback.unsafelyUnwrapped({ _ in
|
||||
@@ -110,23 +106,23 @@ extension System {
|
||||
|
||||
nonisolated(unsafe) private static var updateCallback: (() -> Bool)?
|
||||
|
||||
/// Draws the current frames-per-second value at the given point.
|
||||
/// Draws the current FPS at (`x`, `y`).
|
||||
public static func drawFPS(x: Int = 0, y: Int = 0) {
|
||||
api.pointee.drawFPS.unsafelyUnwrapped(Int32(x), Int32(y))
|
||||
}
|
||||
|
||||
// MARK: - Input
|
||||
|
||||
/// The current button state: held, pressed this frame, released this frame.
|
||||
/// Buttons held now, and those pushed or released during the previous update.
|
||||
public static var buttonState: (current: Buttons, pushed: Buttons, released: Buttons) {
|
||||
var current = PDButtons(0), pushed = PDButtons(0), released = PDButtons(0)
|
||||
api.pointee.getButtonState.unsafelyUnwrapped(¤t, &pushed, &released)
|
||||
return (Buttons(current), Buttons(pushed), Buttons(released))
|
||||
}
|
||||
|
||||
/// Installs a callback invoked for every button press/release. `queueSize`
|
||||
/// sets how many events are buffered between frames. The return value of
|
||||
/// the callback is reserved by the OS; return 0.
|
||||
/// Calls `callback` per button down/up in the previous update, replacing any previous
|
||||
/// one; `nil` removes it. `queueSize`: events buffered per update (5 suffices at 30 FPS).
|
||||
/// `callback` returns 0, or non-zero to signal an error.
|
||||
public static func setButtonCallback(queueSize: Int = 5,
|
||||
_ callback: ((_ button: Buttons, _ isDown: Bool, _ when: UInt32) -> Int32)?) {
|
||||
buttonCallback = callback
|
||||
@@ -141,45 +137,42 @@ extension System {
|
||||
|
||||
nonisolated(unsafe) private static var buttonCallback: ((Buttons, Bool, UInt32) -> Int32)?
|
||||
|
||||
/// Enables the given peripherals (e.g. the accelerometer), disabling
|
||||
/// the rest.
|
||||
/// Enables `peripherals`, disabling the rest; accelerometer data arrives next update.
|
||||
public static func setPeripheralsEnabled(_ peripherals: Peripherals) {
|
||||
api.pointee.setPeripheralsEnabled.unsafelyUnwrapped(PDPeripherals(PDPeripherals.RawValue(peripherals.rawValue)))
|
||||
}
|
||||
|
||||
/// The most recent accelerometer reading, in g. Enable the accelerometer
|
||||
/// with `setPeripheralsEnabled(.accelerometer)` first.
|
||||
/// Last reading, in g; requires `setPeripheralsEnabled(.accelerometer)`.
|
||||
public static var accelerometer: (x: Float, y: Float, z: Float) {
|
||||
var x: Float = 0, y: Float = 0, z: Float = 0
|
||||
api.pointee.getAccelerometer.unsafelyUnwrapped(&x, &y, &z)
|
||||
return (x, y, z)
|
||||
}
|
||||
|
||||
/// Degrees the crank moved since the last frame.
|
||||
/// Degrees moved since last read; negative is counterclockwise.
|
||||
public static var crankChange: Float { api.pointee.getCrankChange.unsafelyUnwrapped() }
|
||||
|
||||
/// The crank position in degrees; 0 points along the +Y axis.
|
||||
/// Degrees, 0...360; 0 points up, increasing clockwise viewed from the right side.
|
||||
public static var crankAngle: Float { api.pointee.getCrankAngle.unsafelyUnwrapped() }
|
||||
|
||||
/// Whether the crank is folded into the device.
|
||||
public static var isCrankDocked: Bool { api.pointee.isCrankDocked.unsafelyUnwrapped() != 0 }
|
||||
|
||||
/// Disables or enables the crank dock/undock sounds. Returns the previous setting.
|
||||
/// Toggles crank dock/undock sounds; returns the previous `disabled` value.
|
||||
@discardableResult
|
||||
public static func setCrankSoundsDisabled(_ disabled: Bool) -> Bool {
|
||||
api.pointee.setCrankSoundsDisabled.unsafelyUnwrapped(disabled ? 1 : 0) != 0
|
||||
}
|
||||
|
||||
/// Whether the user has the "flipped" system setting enabled.
|
||||
/// The user's "flipped" system setting.
|
||||
public static var isFlipped: Bool { api.pointee.getFlipped.unsafelyUnwrapped() != 0 }
|
||||
|
||||
/// Disables or re-enables the automatic screen lock.
|
||||
/// Toggles the 3-minute auto lock; either call resets its timer.
|
||||
public static func setAutoLockDisabled(_ disabled: Bool) {
|
||||
api.pointee.setAutoLockDisabled.unsafelyUnwrapped(disabled ? 1 : 0)
|
||||
}
|
||||
|
||||
/// Installs a callback invoked when a message is received on the serial port
|
||||
/// via `msg <text>`.
|
||||
/// Calls `callback` for serial `msg <text>` messages; `nil` removes it. One closure
|
||||
/// at a time.
|
||||
public static func setSerialMessageCallback(_ callback: ((String) -> Void)?) {
|
||||
serialMessageCallback = callback
|
||||
if callback != nil {
|
||||
@@ -196,6 +189,7 @@ extension System {
|
||||
|
||||
// MARK: - System menu
|
||||
|
||||
// Retains items until removed; the OS holds only unretained userdata pointers.
|
||||
nonisolated(unsafe) private static var liveMenuItems: [MenuItem] = []
|
||||
|
||||
private static let menuItemTrampoline: @convention(c) (UnsafeMutableRawPointer?) -> Void = { userdata in
|
||||
@@ -204,23 +198,24 @@ extension System {
|
||||
item.onSelect(item)
|
||||
}
|
||||
|
||||
/// Adds a plain menu item to the system menu.
|
||||
/// Adds an action item; `onSelect` runs when picked. `nil` if the OS can't add it.
|
||||
@discardableResult
|
||||
public static func addMenuItem(title: String, onSelect: @escaping (MenuItem) -> Void) -> MenuItem? {
|
||||
var item: MenuItem?
|
||||
title.withPlaydateCString { cTitle in
|
||||
title.withCString { cTitle in
|
||||
let pointer = api.pointee.addMenuItem.unsafelyUnwrapped(cTitle, menuItemTrampoline, nil)
|
||||
item = MenuItem(pointer: pointer, onSelect: onSelect)
|
||||
}
|
||||
return registered(item)
|
||||
}
|
||||
|
||||
/// Adds a menu item with a checkbox.
|
||||
/// Adds a checkmark item; `onSelect` runs when the menu closes after a toggle.
|
||||
/// `nil` if the OS can't add it.
|
||||
@discardableResult
|
||||
public static func addCheckmarkMenuItem(title: String, isChecked: Bool = false,
|
||||
onSelect: @escaping (MenuItem) -> Void) -> MenuItem? {
|
||||
var item: MenuItem?
|
||||
title.withPlaydateCString { cTitle in
|
||||
title.withCString { cTitle in
|
||||
let pointer = api.pointee.addCheckmarkMenuItem.unsafelyUnwrapped(
|
||||
cTitle, isChecked ? 1 : 0, menuItemTrampoline, nil)
|
||||
item = MenuItem(pointer: pointer, onSelect: onSelect)
|
||||
@@ -228,16 +223,16 @@ extension System {
|
||||
return registered(item)
|
||||
}
|
||||
|
||||
/// Adds a menu item that cycles through the given options.
|
||||
/// Adds an item cycling through `options`; `onSelect` runs when the menu closes
|
||||
/// after a change. `nil` if the OS can't add it.
|
||||
@discardableResult
|
||||
public static func addOptionsMenuItem(title: String, options: [String],
|
||||
onSelect: @escaping (MenuItem) -> Void) -> MenuItem? {
|
||||
// The OS keeps the option title pointers, so copy and retain them for
|
||||
// the lifetime of the menu item.
|
||||
// The OS keeps the title pointers; the copies live until the item is removed.
|
||||
let copies = options.map { $0.copiedPlaydateCString() }
|
||||
var cOptions: [UnsafePointer<CChar>?] = copies.map { UnsafePointer($0) }
|
||||
var item: MenuItem?
|
||||
title.withPlaydateCString { cTitle in
|
||||
title.withCString { cTitle in
|
||||
cOptions.withUnsafeMutableBufferPointer { buffer in
|
||||
let pointer = api.pointee.addOptionsMenuItem.unsafelyUnwrapped(
|
||||
cTitle, buffer.baseAddress, Int32(options.count), menuItemTrampoline, nil)
|
||||
@@ -247,7 +242,7 @@ extension System {
|
||||
return registered(item)
|
||||
}
|
||||
|
||||
/// Registers the wrapper as the item's userdata and keeps it alive.
|
||||
/// Sets `item` as its own userdata and retains it until removed.
|
||||
private static func registered(_ item: MenuItem?) -> MenuItem? {
|
||||
guard let item else { return nil }
|
||||
api.pointee.setMenuItemUserdata.unsafelyUnwrapped(
|
||||
@@ -256,62 +251,68 @@ extension System {
|
||||
return item
|
||||
}
|
||||
|
||||
/// Removes `item`; the OS frees it, so don't use `item` afterwards.
|
||||
public static func removeMenuItem(_ item: MenuItem) {
|
||||
api.pointee.removeMenuItem.unsafelyUnwrapped(item.pointer)
|
||||
item.deallocateRetainedTitles()
|
||||
liveMenuItems.removeAll { $0 === item }
|
||||
}
|
||||
|
||||
/// Removes all custom items; existing `MenuItem`s must not be used afterwards.
|
||||
public static func removeAllMenuItems() {
|
||||
api.pointee.removeAllMenuItems.unsafelyUnwrapped()
|
||||
for item in liveMenuItems { item.deallocateRetainedTitles() }
|
||||
liveMenuItems = []
|
||||
}
|
||||
|
||||
/// Sets a custom image for the pause menu, optionally shifted left by
|
||||
/// `xOffset` (0...200).
|
||||
/// Sets the 400x240 menu image; only its left 200 px stay visible. `xOffset`
|
||||
/// (0...200 px) shifts it left as the menu animates in.
|
||||
public static func setMenuImage(_ bitmap: Graphics.Bitmap?, xOffset: Int = 0) {
|
||||
api.pointee.setMenuImage.unsafelyUnwrapped(bitmap?.pointer, Int32(xOffset))
|
||||
}
|
||||
|
||||
// MARK: - Device state
|
||||
|
||||
/// Whether the user has enabled the "reduce flashing" accessibility setting.
|
||||
/// The user's "reduce flashing" accessibility setting.
|
||||
public static var reduceFlashing: Bool { api.pointee.getReduceFlashing.unsafelyUnwrapped() != 0 }
|
||||
|
||||
/// Battery charge, 0...100.
|
||||
/// 0 (empty)...100 (full).
|
||||
public static var batteryPercentage: Float { api.pointee.getBatteryPercentage.unsafelyUnwrapped() }
|
||||
|
||||
/// The battery voltage, in volts.
|
||||
/// In volts.
|
||||
public static var batteryVoltage: Float { api.pointee.getBatteryVoltage.unsafelyUnwrapped() }
|
||||
|
||||
/// Flushes the CPU instruction cache after loading code at runtime.
|
||||
/// Flushes the CPU instruction cache; needed only after modifying code at runtime.
|
||||
public static func clearICache() { api.pointee.clearICache.unsafelyUnwrapped() }
|
||||
|
||||
/// Quits the current game and restarts it with the given launch arguments.
|
||||
/// Reinitializes the runtime and restarts the game with `launchArguments`.
|
||||
public static func restartGame(launchArguments: String? = nil) {
|
||||
if let launchArguments {
|
||||
launchArguments.withPlaydateCString { api.pointee.restartGame.unsafelyUnwrapped($0) }
|
||||
launchArguments.withCString { api.pointee.restartGame.unsafelyUnwrapped($0) }
|
||||
} else {
|
||||
api.pointee.restartGame.unsafelyUnwrapped(nil)
|
||||
}
|
||||
}
|
||||
|
||||
/// The arguments the game was launched with, and the path of the pdx.
|
||||
/// Launch arguments (simulator command line, device `run`, or `restartGame`) and
|
||||
/// the loaded game's path.
|
||||
public static var launchArguments: (arguments: String?, path: String?) {
|
||||
var path: UnsafePointer<CChar>?
|
||||
let arguments = api.pointee.getLaunchArgs.unsafelyUnwrapped(&path)
|
||||
return (String(playdateCString: arguments), String(playdateCString: path))
|
||||
}
|
||||
|
||||
/// Sends data over the mirror connection. Returns `false` if mirroring is
|
||||
/// not active or the send fails.
|
||||
/// Sends `data` with `command` over Mirror; `false` if not mirroring or the send fails.
|
||||
@discardableResult
|
||||
public static func sendMirrorData(command: UInt8, data: UnsafeMutableRawBufferPointer) -> Bool {
|
||||
api.pointee.sendMirrorData.unsafelyUnwrapped(command, data.baseAddress, Int32(data.count))
|
||||
public static func sendMirrorData(command: UInt8, data: Span<UInt8>) -> Bool {
|
||||
data.withUnsafeBufferPointer { buffer in
|
||||
// The C API takes a non-const pointer but only reads the data.
|
||||
api.pointee.sendMirrorData.unsafelyUnwrapped(
|
||||
command, UnsafeMutableRawPointer(mutating: buffer.baseAddress), Int32(buffer.count))
|
||||
}
|
||||
}
|
||||
|
||||
/// OS, language, and pdx version information.
|
||||
/// OS version, system language, and the SDK version the game was built with.
|
||||
public static var info: Info {
|
||||
let info = api.pointee.getSystemInfo.unsafelyUnwrapped().unsafelyUnwrapped.pointee
|
||||
return Info(osVersion: info.osversion,
|
||||
@@ -319,9 +320,10 @@ extension System {
|
||||
pdxVersion: info.pdxversion)
|
||||
}
|
||||
|
||||
/// Looks up a localized string by key from the game's strings files.
|
||||
/// Looks up `key` in `language`'s `.strings` file; `nil` if the key or file is missing.
|
||||
/// `.system` falls back to the other language's file if the system one can't load.
|
||||
public static func localizedText(forKey key: String, language: Language = .system) -> String? {
|
||||
key.withPlaydateCString { cKey in
|
||||
key.withCString { cKey in
|
||||
guard let cString = api.pointee.getLocalizedText.unsafelyUnwrapped(cKey, language.cValue) else {
|
||||
return nil
|
||||
}
|
||||
@@ -331,14 +333,13 @@ extension System {
|
||||
}
|
||||
}
|
||||
|
||||
/// The system volume, 0...1.
|
||||
/// Menu volume, 0...1.
|
||||
public static var volume: Float { api.pointee.getVolume.unsafelyUnwrapped() }
|
||||
|
||||
/// The battery and power supply state.
|
||||
public static var powerStatus: PowerStatus {
|
||||
PowerStatus(rawValue: UInt32(api.pointee.getPowerStatus.unsafelyUnwrapped().rawValue))
|
||||
}
|
||||
|
||||
/// Quits the game and returns to the launcher.
|
||||
/// Sends the game `kEventTerminate`, then quits to the launcher.
|
||||
public static func exitToLauncher() { api.pointee.exitToLauncher.unsafelyUnwrapped() }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user