Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for reading configuration from home directory #91

Merged
merged 3 commits into from
Oct 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,7 @@ root = true
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = true

[*.swift]
indent_style = space
indent_size = 4
9 changes: 9 additions & 0 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,15 @@
"revision": "0687f71944021d616d34d922343dcef086855920",
"version": "600.0.1"
}
},
{
"package": "Yams",
"repositoryURL": "https://github.com/jpsim/Yams.git",
"state": {
"branch": null,
"revision": "3036ba9d69cf1fd04d433527bc339dc0dc75433d",
"version": "5.1.3"
}
}
]
},
Expand Down
2 changes: 2 additions & 0 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ let package = Package(
// Dependencies declare other packages that this package depends on.
.package(url: "https://github.com/apple/swift-argument-parser", from: "1.5.0"),
.package(url: "https://github.com/apple/swift-format", from: "600.0.0"),
.package(url: "https://github.com/jpsim/Yams.git", from: "5.1.3"),
],
targets: [
// Targets are the basic building blocks of a package. A target can define a module or a test suite.
Expand All @@ -23,6 +24,7 @@ let package = Package(
name: "SendKeysLib",
dependencies: [
.product(name: "ArgumentParser", package: "swift-argument-parser"),
.product(name: "Yams", package: "Yams"),
]),
.testTarget(
name: "SendKeysTests",
Expand Down
17 changes: 15 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,11 @@ _Activates the Notes application and sends keystrokes piped from `stdout` of the
values results in smoother animations. Defaults to `0.01` seconds.
- `--terminate-command <command>`: The command that should be used to terminate the application. Not set by default.
Follows a similar convention to `--characters`. (e.g. `f12:command,shift`).
- `--keyboard-layout <layout>`: Use alternate keyboard layout. Defaults to `qwerty`. (`colemak` and `dvorak` are also
supported).
- `--keyboard-layout <layout>`: Use alternate keyboard layout. Defaults to `qwerty`. `colemak` and `dvorak` are also
supported, pull requests for other common keyboard layouts may be considered. If a specific keyboard layout is not
supported, a custom layout can be defined in using the `--config` option or using the
[`.sendkeysrc.yml`](./examples/.sendkeysrc.yml) configuration file (`send.remap`).
- `--config <yaml-file>`: Configuration file to load settings from.

## Installation

Expand Down Expand Up @@ -334,6 +337,16 @@ SendKeys will use `--application-name` to activate the first application instanc
name or bundle id (case insensitive). If there are no exact matches, it will attempt to match on whole words for the
application name, followed by the bundle id.

## Configuration

Common arguments can be stored in a [`.sendkeysrc.yml`](./examples/.senkeysrc.yml) configuration file. Configuration
values are applied and merged in the following priority order:

1. Command line arguments
2. Configuration file defined with `--config` option
3. Configuration file defined in `~/.sendkeysrc.yml`
4. Default values

## Prerequisites

This application will only run on macOS 10.11 or later.
Expand Down
19 changes: 19 additions & 0 deletions Sources/SendKeysLib/Configuration/AllConfiguration.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
struct AllConfiguration: Codable {
var send: SendConfig?
var mousePosition: MousePositionConfig?
var transformer: TransformerConfig?

init(send: SendConfig? = nil, mousePosition: MousePositionConfig? = nil, transformer: TransformerConfig? = nil) {
self.send = send
self.mousePosition = mousePosition
self.transformer = transformer
}

func merge(with other: AllConfiguration?) -> AllConfiguration {
return AllConfiguration(
send: other?.send?.merge(with: self.send) ?? self.send,
mousePosition: other?.mousePosition?.merge(with: self.mousePosition) ?? self.mousePosition,
transformer: other?.transformer?.merge(with: self.transformer) ?? self.transformer
)
}
}
35 changes: 35 additions & 0 deletions Sources/SendKeysLib/Configuration/ConfigLoader.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import Foundation
import Yams

let defaultConfigFiles = [
NSString("~/.sendkeysrc.yml").expandingTildeInPath,
NSString("~/.sendkeysrc.yaml").expandingTildeInPath,
]

struct ConfigLoader {
static func loadConfig(_ file: String? = nil) -> AllConfiguration {
var config = AllConfiguration()

let configFiles =
if file != nil {
[file!]
} else {
defaultConfigFiles
}

for configFile in configFiles {
if !configFile.isEmpty && FileManager.default.fileExists(atPath: configFile) {
if let contents = FileManager.default.contents(atPath: configFile) {
do {
let decoder = YAMLDecoder()
config = config.merge(with: try decoder.decode(AllConfiguration.self, from: contents))
} catch {
print("Unable to read \(configFile): \(error)")
}
}
}
}

return config
}
}
19 changes: 19 additions & 0 deletions Sources/SendKeysLib/Configuration/MousePositionConfig.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
struct MousePositionConfig: Codable {
var watch: Bool?
var output: OutputMode?
var duration: Double?

init(watch: Bool? = nil, output: OutputMode? = nil, duration: Double? = nil) {
self.watch = watch
self.output = output
self.duration = duration
}

func merge(with other: MousePositionConfig?) -> MousePositionConfig {
return MousePositionConfig(
watch: other?.watch ?? self.watch,
output: other?.output ?? self.output,
duration: other?.duration ?? self.duration
)
}
}
38 changes: 38 additions & 0 deletions Sources/SendKeysLib/Configuration/SendConfig.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
struct SendConfig: Codable {
var activate: Bool?
var animationInterval: Double?
var delay: Double?
var initialDelay: Double?
var keyboardLayout: KeyMappings.Layouts?
var remap: [String: String]?
var targeted: Bool?
var terminateCommand: String?

init(
activate: Bool? = nil, animationInterval: Double? = nil, delay: Double? = nil, initialDelay: Double? = nil,
keyboardLayout: KeyMappings.Layouts? = nil, remap: [String: String]? = nil, targeted: Bool? = nil,
terminateCommand: String? = nil
) {
self.activate = activate
self.animationInterval = animationInterval
self.delay = delay
self.initialDelay = initialDelay
self.keyboardLayout = keyboardLayout
self.remap = remap
self.targeted = targeted
self.terminateCommand = terminateCommand
}

func merge(with other: SendConfig?) -> SendConfig {
return SendConfig(
activate: other?.activate ?? self.activate,
animationInterval: other?.animationInterval ?? self.animationInterval,
delay: other?.delay ?? self.delay,
initialDelay: other?.initialDelay ?? self.initialDelay,
keyboardLayout: other?.keyboardLayout ?? self.keyboardLayout,
remap: other?.remap ?? self.remap,
targeted: other?.targeted ?? self.targeted,
terminateCommand: other?.terminateCommand ?? self.terminateCommand
)
}
}
16 changes: 16 additions & 0 deletions Sources/SendKeysLib/Configuration/TransformerConfig.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
struct TransformerConfig: Codable {
var indent: Bool?
var autoClose: String?

init(indent: Bool? = nil, autoClose: String? = nil) {
self.indent = indent
self.autoClose = autoClose
}

func merge(with other: TransformerConfig?) -> TransformerConfig {
return TransformerConfig(
indent: other?.indent ?? self.indent,
autoClose: other?.autoClose ?? self.autoClose
)
}
}
3 changes: 2 additions & 1 deletion Sources/SendKeysLib/KeyCodes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,8 @@ struct KeyCodes {
private static var remappingDictionary: [String: String] = [:]

static func updateMapping(_ newOldMapping: [String: String]) {
remappingDictionary = newOldMapping
// Merge the new mapping with the existing one
remappingDictionary.merge(newOldMapping) { current, new in new }
}

private static func getRemappedKey(_ key: String) -> String {
Expand Down
2 changes: 1 addition & 1 deletion Sources/SendKeysLib/KeyMappings.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import ArgumentParser

struct KeyMappings {
enum Layouts: String, ExpressibleByArgument {
enum Layouts: String, Codable, ExpressibleByArgument {
case qwerty
case colemak
case dvorak
Expand Down
28 changes: 18 additions & 10 deletions Sources/SendKeysLib/MousePosition.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,24 @@ class MousePosition: ParsableCommand {
abstract: "Prints the current mouse position."
)

@Flag(name: .shortAndLong, help: "Watch and display the mouse positions as the mouse is clicked.")
var watch = false
@Flag(
name: .shortAndLong, inversion: FlagInversion.prefixedNo,
help: "Watch and display the mouse positions as the mouse is clicked.")
var watch: Bool?

@Option(
name: NameSpecification([.customShort("o"), .customLong("output", withSingleDash: false)]),
help: "Displays results as either a series of coordinates or commands.")
var mode = OutputMode.coordinates
var mode: OutputMode?

@Option(
name: .shortAndLong,
help:
"Duration (in seconds) to output for mouse events. A negative value uses elapsed time between mouse events."
)
var duration: Double = -1
var duration: Double?

var config: MousePositionConfig

static let eventProcessor = MouseEventProcessor()

Expand All @@ -38,10 +42,15 @@ class MousePosition: ParsableCommand {
}

required init() {
self.config = MousePositionConfig(watch: false, output: .commands, duration: -1)
}

func run() {
if watch {
self.config = self.config
.merge(with: ConfigLoader.loadConfig().mousePosition)
.merge(with: MousePositionConfig(watch: watch, output: mode, duration: duration))

if self.config.watch! {
watchMouseInput()
} else {
printMousePosition(nil)
Expand Down Expand Up @@ -112,13 +121,12 @@ class MousePosition: ParsableCommand {
let command: MousePosition = bridge(ptr: UnsafeRawPointer(refcon)!)

if let mouseEvent = MousePosition.eventProcessor.consumeEvent(type: eventType, event: event) {

// if duration is set, override all mouse event durations
if command.duration >= 0 {
mouseEvent.duration = command.duration
if command.config.duration! >= 0 {
mouseEvent.duration = command.config.duration!
}

switch command.mode {
switch command.config.output! {
case .coordinates:
if mouseEvent.eventType == .click {
command.printMousePosition(mouseEvent.endPoint)
Expand Down Expand Up @@ -148,7 +156,7 @@ class MousePosition: ParsableCommand {
func eventCallback(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent, refcon: UnsafeMutableRawPointer?)
-> Unmanaged<CGEvent>?
{
switch mode {
switch self.config.output! {
case .coordinates:
printMousePosition(nil)
case .commands:
Expand Down
58 changes: 48 additions & 10 deletions Sources/SendKeysLib/Sender.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,17 @@ public struct Sender: ParsableCommand {
@Flag(
name: .long, inversion: FlagInversion.prefixedNo,
help: "Activate the specified app or process before sending commands.")
var activate: Bool = true
var activate: Bool?

@Flag(name: .long, help: "Only send keystrokes to the targeted app or process.")
var targeted: Bool = false
@Flag(
name: .long, inversion: FlagInversion.prefixedNo, help: "Only send keystrokes to the targeted app or process.")
var targeted: Bool?

@Option(name: .shortAndLong, help: "Default delay between keystrokes in seconds.")
var delay: Double = 0.1
var delay: Double?

@Option(name: .shortAndLong, help: "Initial delay before sending commands in seconds.")
var initialDelay: Double = 1
var initialDelay: Double?

@Option(name: NameSpecification([.customShort("f"), .long]), help: "File containing keystroke instructions.")
var inputFile: String?
Expand All @@ -38,15 +39,26 @@ public struct Sender: ParsableCommand {
var characters: String?

@Option(help: "Number of seconds between animation updates.")
var animationInterval: Double = 0.01
var animationInterval: Double?

@Option(name: .shortAndLong, help: "Character sequence to use to terminate execution (e.g. f12:command).")
var terminateCommand: String?

@Option(
name: NameSpecification([.customLong("config")]),
help: "Configuration file to load settings from (yaml format).")
var configurationFile: String?

@Option(name: .long, help: "Keyboard layout to use for sending keystrokes.")
var keyboardLayout: KeyMappings.Layouts = .qwerty
var keyboardLayout: KeyMappings.Layouts?

public init() {}
var config: SendConfig

public init() {
self.config = SendConfig(
activate: true, animationInterval: 0.01, delay: 0.1, initialDelay: 1,
targeted: false, terminateCommand: nil)
}

public mutating func run() throws {
let accessEnabled = AXIsProcessTrustedWithOptions(
Expand All @@ -62,7 +74,33 @@ public struct Sender: ParsableCommand {
let app: NSRunningApplication? = try activator.find()
let keyPresser: KeyPresser

KeyPresser.setKeyboardLayout(keyboardLayout)
// load from home directory by default
self.config = self.config.merge(with: ConfigLoader.loadConfig().send)

if !(configurationFile ?? "").isEmpty {
self.config = self.config.merge(with: ConfigLoader.loadConfig(configurationFile!).send)
}

self.config = self.config.merge(
with: SendConfig(
activate: activate, animationInterval: animationInterval, delay: delay, initialDelay: initialDelay,
keyboardLayout: keyboardLayout, targeted: targeted, terminateCommand: terminateCommand))

let activate = activate ?? self.config.activate!
let targeted = targeted ?? self.config.targeted!
let delay = delay ?? self.config.delay!
let initialDelay = initialDelay ?? self.config.initialDelay!
let animationInterval = animationInterval ?? self.config.animationInterval!
let terminateCommand = terminateCommand ?? self.config.terminateCommand
let keyboardLayout = keyboardLayout ?? self.config.keyboardLayout

if keyboardLayout != nil {
KeyPresser.setKeyboardLayout(keyboardLayout!)
}

if self.config.remap != nil {
KeyCodes.updateMapping(self.config.remap!)
}

if targeted {
if app == nil {
Expand All @@ -89,7 +127,7 @@ public struct Sender: ParsableCommand {
}

var listener: TerminationListener?
if terminateCommand != nil {
if terminateCommand != nil && !terminateCommand!.isEmpty {
listener = TerminationListener(sequence: terminateCommand!) {
Sender.exit()
}
Expand Down
Loading