-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Add clipboard automations #1422
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
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| import Defaults | ||
| import Foundation | ||
|
|
||
| // A user-configured rule that runs an action when copied text matches a regular expression. | ||
| // | ||
| // Persisted as configuration via the `Defaults` library (like `ignoreRegexp`), not SwiftData. | ||
| // `Defaults.Serializable` is free for `Codable` types, and arrays of serializable values are | ||
| // themselves serializable, so `Defaults.Key<[Automation]>` works out of the box. | ||
| struct Automation: Identifiable, Codable, Hashable, Defaults.Serializable { | ||
| var id = UUID() | ||
| var name = "" | ||
| var regexp = "" | ||
| var isEnabled = true | ||
| var action: AutomationAction = .runScript(RunScriptConfig()) | ||
|
|
||
| // Returns true when `text` matches `regexp`. An empty or invalid pattern never matches. | ||
| func matches(_ text: String) -> Bool { | ||
| guard !regexp.isEmpty, let regex = try? NSRegularExpression(pattern: regexp) else { | ||
| return false | ||
| } | ||
|
|
||
| let range = NSRange(text.startIndex..., in: text) | ||
| return regex.numberOfMatches(in: text, range: range) > 0 | ||
| } | ||
| } | ||
|
|
||
| // The action performed when an automation matches. New actions are added as new cases. | ||
| enum AutomationAction: Codable, Hashable { | ||
| case runScript(RunScriptConfig) | ||
| } | ||
|
|
||
| struct RunScriptConfig: Codable, Hashable { | ||
| var scriptName = "" // filename within the Application Scripts directory | ||
| var parseResultAsHTML = false | ||
| } | ||
|
|
||
| // Convenience accessors so SwiftUI can bind directly to action fields. They no-op for | ||
| // automations whose action is not `.runScript`, which keeps the editor bindings simple while | ||
| // the action set is small. | ||
| extension Automation { | ||
| var scriptName: String { | ||
| get { | ||
| guard case let .runScript(config) = action else { return "" } | ||
| return config.scriptName | ||
| } | ||
| set { | ||
| guard case var .runScript(config) = action else { return } | ||
| config.scriptName = newValue | ||
| action = .runScript(config) | ||
| } | ||
| } | ||
|
|
||
| var parseResultAsHTML: Bool { | ||
| get { | ||
| guard case let .runScript(config) = action else { return false } | ||
| return config.parseResultAsHTML | ||
| } | ||
| set { | ||
| guard case var .runScript(config) = action else { return } | ||
| config.parseResultAsHTML = newValue | ||
| action = .runScript(config) | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,96 @@ | ||
| import AppKit | ||
| import Defaults | ||
| import Foundation | ||
| import Logging | ||
|
|
||
| // Runs user-configured automations against freshly copied text. | ||
| // | ||
| // Registered as an `onNewCopy` hook *after* `History.add`, so by the time it runs the original | ||
| // item is already in history. When one or more automations match, their scripts are chained | ||
| // (each transforms the previous output) and a single new item is produced: it becomes the | ||
| // current clipboard contents and the most-recent history entry, while the original copy is | ||
| // preserved. | ||
| @MainActor | ||
| final class AutomationProcessor { | ||
| static let shared = AutomationProcessor() | ||
|
|
||
| // Injectable so tests can stub script execution. | ||
| var scriptRunner: ScriptRunning = ScriptRunner.shared | ||
|
|
||
| private let logger = Logger(label: "org.p0deje.Maccy") | ||
|
|
||
| // Synchronous entry point for the clipboard hook. | ||
| func process(_ item: HistoryItem) { | ||
| guard shouldProcess(item), let text = item.text else { return } | ||
|
|
||
| let source = item.application | ||
| Task { @MainActor in | ||
| if let result = await buildResult(forText: text, source: source) { | ||
| History.shared.add(result) | ||
| Clipboard.shared.copy(result) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Skip Maccy's own writes (prevents re-trigger loops) and non-text items. | ||
| func shouldProcess(_ item: HistoryItem) -> Bool { | ||
| !item.fromMaccy && (item.text?.isEmpty == false) | ||
| } | ||
|
|
||
| // Testable core: matches, chains scripts, and builds the resulting item without publishing | ||
| // it. Returns nil when nothing matched, a script failed, or the output was empty/unchanged. | ||
| func buildResult(forText text: String, source: String?) async -> HistoryItem? { | ||
| let matching = Defaults[.automations].filter { $0.isEnabled && $0.matches(text) } | ||
| guard !matching.isEmpty else { return nil } | ||
|
|
||
| var current = text | ||
| var isHTML = false | ||
|
|
||
| for automation in matching { | ||
| guard case let .runScript(config) = automation.action, !config.scriptName.isEmpty else { | ||
| continue | ||
| } | ||
|
|
||
| do { | ||
| let output = try await scriptRunner.run(scriptName: config.scriptName, input: current) | ||
| let cleaned = trimTrailingNewlines(output) | ||
| guard !cleaned.isEmpty else { continue } | ||
| current = cleaned | ||
| isHTML = config.parseResultAsHTML | ||
| } catch { | ||
| logger.error("Automation '\(automation.name)' script failed: \(error.localizedDescription)") | ||
| return nil | ||
| } | ||
| } | ||
|
|
||
| guard current != text else { return nil } | ||
| return makeItem(output: current, isHTML: isHTML, source: source) | ||
| } | ||
|
|
||
| private func makeItem(output: String, isHTML: Bool, source: String?) -> HistoryItem { | ||
| var contents = [HistoryItemContent]() | ||
|
|
||
| if isHTML { | ||
| let htmlData = Data(output.utf8) | ||
| contents.append(HistoryItemContent(type: NSPasteboard.PasteboardType.html.rawValue, value: htmlData)) | ||
| // Plain-text fallback so paste-without-formatting and title generation still work. | ||
| let plain = NSAttributedString(html: htmlData, documentAttributes: nil)?.string ?? output | ||
| contents.append(HistoryItemContent(type: NSPasteboard.PasteboardType.string.rawValue, value: Data(plain.utf8))) | ||
| } else { | ||
| contents.append(HistoryItemContent(type: NSPasteboard.PasteboardType.string.rawValue, value: Data(output.utf8))) | ||
| } | ||
|
|
||
| let item = HistoryItem(contents: contents) | ||
| item.application = source | ||
| item.title = item.generateTitle() | ||
| return item | ||
| } | ||
|
|
||
| private func trimTrailingNewlines(_ string: String) -> String { | ||
| var result = Substring(string) | ||
| while let last = result.last, last == "\n" || last == "\r" { | ||
| result = result.dropLast() | ||
| } | ||
| return String(result) | ||
| } | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This creates a problem if users want to intentionally trailing newlines in their script output.
Probably we should just strip a single trailing newline, which allows people to use
echoand variants as they normally would.