david-swift e989bea14e
All checks were successful
Deploy Docs / publish (push) Successful in 2m38s
Initial commit
2024-12-02 22:14:13 +01:00

116 lines
3.3 KiB
Swift

//
// KeyboardShortcut.swift
// MacBackend
//
// Created by david-swift on 10.09.2024.
//
import AppKit
/// A keyboard shortcut used e.g. in menus.
public struct KeyboardShortcut: Equatable {
/// The character or a sequence representing a letter or symbol.
public var character: ShortcutCharacter
/// Whether the Ctrl key is part of the shortcut.
public var command: Bool
/// Whether the Shift key is part of the shortcut.
public var shift: Bool
/// Whether the Alt key is part of the shortcut.
public var option: Bool
/// The modifiers for the macOS shortcut.
var modifiers: NSEvent.ModifierFlags {
var flags: NSEvent.ModifierFlags = []
if command {
flags.insert(.command)
}
if shift {
flags.insert(.shift)
}
if option {
flags.insert(.option)
}
return flags
}
/// Initialize a keyboard shortcut.
/// - Parameters:
/// - character: A letter.
/// - ctrl: Whether Ctrl is part of the shortcut.
/// - shift: Whether Shift is part of the shortcut.
/// - alt: Whether Alt is part of the shortcut.
public init(_ character: Character, ctrl: Bool = true, shift: Bool = false, alt: Bool = false) {
self.character = .character(character)
self.command = ctrl
self.shift = shift
self.option = alt
}
/// Initialize a keyboard shortcut.
/// - Parameters:
/// - symbol: A character.
/// - ctrl: Whether Ctrl is part of the shortcut.
/// - shift: Whether Shift is part of the shortcut.
/// - alt: Whether Alt is part of the shortcut.
public init(symbol: ShortcutCharacter, ctrl: Bool = true, shift: Bool = false, alt: Bool = false) {
self.character = symbol
self.command = ctrl
self.shift = shift
self.option = alt
}
/// The special characters available for shortcuts.
public enum ShortcutCharacter: Equatable {
/// The character.
case backspace
/// The character.
case delete
/// The character.
case tab
/// The character.
case enter
/// The character.
case escape
/// The character.
case space
// swiftlint:disable identifier_name
/// An arrow key.
case up, down, left, right
// swiftlint:enable identifier_name
/// A custom character.
case character(_ character: Character)
/// A representation of the keys for macOS.
var macOSRepresentation: String {
switch self {
case .backspace:
return "\u{8}"
case .delete:
return "\u{7F}"
case .tab:
return "\u{9}"
case .enter:
return "\u{A}"
case .escape:
return "\u{1B}"
case .space:
return " "
case .up:
return ""
case .down:
return ""
case .left:
return ""
case .right:
return ""
case let .character(character):
return "\(character)"
}
}
}
}