Skip to content
Closed
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
41 changes: 38 additions & 3 deletions Maccy.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,13 @@
DAFE2DDA268A521B00990986 /* String+Shortened.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAFE2DD9268A521A00990986 /* String+Shortened.swift */; };
DAFE2DE9268A9B1B00990986 /* HistoryItemTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAFE2DE8268A9B1B00990986 /* HistoryItemTests.swift */; };
DAFEF0B8249D7DEE006029E8 /* KeyboardShortcuts.Name+Shortcuts.swift in Sources */ = {isa = PBXBuildFile; fileRef = DAFEF0B7249D7DEE006029E8 /* KeyboardShortcuts.Name+Shortcuts.swift */; };
FE100000000000000000A200 /* Automation.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000A100 /* Automation.swift */; };
FE100000000000000000A500 /* AutomationsSettings.strings in Resources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000A300 /* AutomationsSettings.strings */; };
FE100000000000000000B200 /* ScriptRunner.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000B100 /* ScriptRunner.swift */; };
FE100000000000000000C200 /* AutomationProcessor.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000C100 /* AutomationProcessor.swift */; };
FE100000000000000000D200 /* AutomationsSettingsPane.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000D100 /* AutomationsSettingsPane.swift */; };
FE100000000000000000E200 /* AutomationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000E100 /* AutomationTests.swift */; };
FE100000000000000000F200 /* AutomationProcessorTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE100000000000000000F100 /* AutomationProcessorTests.swift */; };
/* End PBXBuildFile section */

/* Begin PBXContainerItemProxy section */
Expand Down Expand Up @@ -204,7 +211,6 @@
2FB5BC9F2CD8F73C008B33F4 /* ApplicationImage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApplicationImage.swift; sourceTree = "<group>"; };
2FF2E94D2E774B570093D72C /* NavigationManager.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NavigationManager.swift; sourceTree = "<group>"; };
2FF2E94F2E7808420093D72C /* AppImageView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppImageView.swift; sourceTree = "<group>"; };
2FFF8BCF2CE2116600235A78 /* Data+Encoding.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Data+Encoding.swift"; sourceTree = "<group>"; };
3EBDD1E32BBEF22800C57500 /* nl */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = nl; path = nl.lproj/Localizable.strings; sourceTree = "<group>"; };
4762D6982467226100B3A2BA /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/Localizable.strings; sourceTree = "<group>"; };
4762D69A2467226400B3A2BA /* es */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = es; path = es.lproj/Localizable.strings; sourceTree = "<group>"; };
Expand Down Expand Up @@ -555,6 +561,13 @@
DAFE2DD9268A521A00990986 /* String+Shortened.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Shortened.swift"; sourceTree = "<group>"; };
DAFE2DE8268A9B1B00990986 /* HistoryItemTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HistoryItemTests.swift; sourceTree = "<group>"; };
DAFEF0B7249D7DEE006029E8 /* KeyboardShortcuts.Name+Shortcuts.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "KeyboardShortcuts.Name+Shortcuts.swift"; sourceTree = "<group>"; };
FE100000000000000000A100 /* Automation.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = Automation.swift; sourceTree = "<group>"; };
FE100000000000000000A400 /* en */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = en; path = en.lproj/AutomationsSettings.strings; sourceTree = "<group>"; };
FE100000000000000000B100 /* ScriptRunner.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ScriptRunner.swift; sourceTree = "<group>"; };
FE100000000000000000C100 /* AutomationProcessor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutomationProcessor.swift; sourceTree = "<group>"; };
FE100000000000000000D100 /* AutomationsSettingsPane.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutomationsSettingsPane.swift; sourceTree = "<group>"; };
FE100000000000000000E100 /* AutomationTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutomationTests.swift; sourceTree = "<group>"; };
FE100000000000000000F100 /* AutomationProcessorTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AutomationProcessorTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXFrameworksBuildPhase section */
Expand Down Expand Up @@ -634,6 +647,7 @@
children = (
DA05B5132C234DCF006980FE /* HistoryItem.swift */,
DA05B5122C234DCF006980FE /* HistoryItemContent.swift */,
FE100000000000000000A100 /* Automation.swift */,
);
path = Models;
sourceTree = "<group>";
Expand Down Expand Up @@ -662,6 +676,8 @@
DA689FAE2C1CD3B00009B887 /* StorageSettings.strings */,
DAA365CD2C4BF9DD00A394F8 /* PinsSettingsPane.swift */,
DAA365CF2C4C147400A394F8 /* PinsSettings.strings */,
FE100000000000000000D100 /* AutomationsSettingsPane.swift */,
FE100000000000000000A300 /* AutomationsSettings.strings */,
);
path = Settings;
sourceTree = "<group>";
Expand Down Expand Up @@ -723,6 +739,8 @@
DAFE2DE8268A9B1B00990986 /* HistoryItemTests.swift */,
DA384E85232746D800603999 /* SearchTests.swift */,
DA696BD12401EEE900DE80CF /* SorterTests.swift */,
FE100000000000000000E100 /* AutomationTests.swift */,
FE100000000000000000F100 /* AutomationProcessorTests.swift */,
DA360DB41E3DF137005C6F6B /* Info.plist */,
);
path = MaccyTests;
Expand All @@ -740,6 +758,7 @@
DA3BCB8D2C3E015000B01BC1 /* ModifierFlags.swift */,
DAE8F5D32C43262B00851CA9 /* Popup.swift */,
2F578C3E2EFFE8720088B759 /* SlideoutController.swift */,
FE100000000000000000C100 /* AutomationProcessor.swift */,
);
path = Observables;
sourceTree = "<group>";
Expand Down Expand Up @@ -831,6 +850,7 @@
DA20FA712B082DD600056DD5 /* Notifier.swift */,
DA689FC72C1D15140009B887 /* PinsPosition.swift */,
DA689FC52C1D14F10009B887 /* PopupPosition.swift */,
FE100000000000000000B100 /* ScriptRunner.swift */,
DAC14123232367B200FCFA30 /* Search.swift */,
2F1A79BF2C6DFB7800C98EBD /* SearchVisibility.swift */,
2F0EC77C2E773314003E2EA9 /* Selection.swift */,
Expand Down Expand Up @@ -1039,6 +1059,7 @@
DA5E62802C39E53F00F4C710 /* PreviewItemView.strings in Resources */,
DA009932256411F90030E697 /* README.md in Resources */,
DA9C3C4A2C20D4B40056795D /* IgnoreSettings.strings in Resources */,
FE100000000000000000A500 /* AutomationsSettings.strings in Resources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
Expand All @@ -1064,13 +1085,19 @@
DA384E86232746D800603999 /* SearchTests.swift in Sources */,
DA696BD22401EEE900DE80CF /* SorterTests.swift in Sources */,
DA360DB31E3DF137005C6F6B /* HistoryTests.swift in Sources */,
FE100000000000000000E200 /* AutomationTests.swift in Sources */,
FE100000000000000000F200 /* AutomationProcessorTests.swift in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
DAEE383F1E3DBEB100DD2966 /* Sources */ = {
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
FE100000000000000000A200 /* Automation.swift in Sources */,
FE100000000000000000B200 /* ScriptRunner.swift in Sources */,
FE100000000000000000C200 /* AutomationProcessor.swift in Sources */,
FE100000000000000000D200 /* AutomationsSettingsPane.swift in Sources */,
DA19691C2C3F3EAC00258481 /* Collection+Surrounding.swift in Sources */,
DA1969142C3F11D600258481 /* PreviewItemView.swift in Sources */,
2FF2E9502E7808470093D72C /* AppImageView.swift in Sources */,
Expand Down Expand Up @@ -1499,6 +1526,14 @@
name = GeneralSettings.strings;
sourceTree = "<group>";
};
FE100000000000000000A300 /* AutomationsSettings.strings */ = {
isa = PBXVariantGroup;
children = (
FE100000000000000000A400 /* en */,
);
name = AutomationsSettings.strings;
sourceTree = "<group>";
};
/* End PBXVariantGroup section */

/* Begin XCBuildConfiguration section */
Expand Down Expand Up @@ -1736,7 +1771,7 @@
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 60;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = MN3X4648SC;
DEVELOPMENT_TEAM = HYTDW9825S;
ENABLE_HARDENED_RUNTIME = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
Expand Down Expand Up @@ -1771,7 +1806,7 @@
COMBINE_HIDPI_IMAGES = YES;
CURRENT_PROJECT_VERSION = 60;
DEAD_CODE_STRIPPING = YES;
DEVELOPMENT_TEAM = MN3X4648SC;
DEVELOPMENT_TEAM = HYTDW9825S;
ENABLE_HARDENED_RUNTIME = YES;
FRAMEWORK_SEARCH_PATHS = (
"$(inherited)",
Expand Down
1 change: 1 addition & 0 deletions Maccy/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
AppState.shared.appDelegate = self

Clipboard.shared.onNewCopy { History.shared.add($0) }
Clipboard.shared.onNewCopy { AutomationProcessor.shared.process($0) }
Clipboard.shared.start()

Task {
Expand Down
1 change: 1 addition & 0 deletions Maccy/Extensions/Defaults.Keys+Names.swift
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ extension Defaults.Keys {
static let size = Key<Int>("historySize", default: 200)
static let sortBy = Key<Sorter.By>("sortBy", default: .lastCopiedAt)
static let suppressClearAlert = Key<Bool>("suppressClearAlert", default: false)
static let automations = Key<[Automation]>("automations", default: [])
static let windowSize = Key<NSSize>("windowSize", default: NSSize(width: 450, height: 800))
static let windowPosition = Key<NSPoint>("windowPosition", default: NSPoint(x: 0.5, y: 0.8))
static let showApplicationIcons = Key<Bool>("showApplicationIcons", default: false)
Expand Down
1 change: 1 addition & 0 deletions Maccy/Extensions/NSImage+Names.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ extension NSImage {
static let pincircle = NSImage(systemSymbolName: "pin.circle", accessibilityDescription: "pin.cirlce")
static let nosign = NSImage(systemSymbolName: "nosign", accessibilityDescription: "nosign")
static let gearshape2 = NSImage(systemSymbolName: "gearshape.2", accessibilityDescription: "gearshape2")
static let bolt = NSImage(systemSymbolName: "bolt", accessibilityDescription: "bolt")
}

extension NSImage.Name {
Expand Down
1 change: 1 addition & 0 deletions Maccy/Extensions/Settings.PaneIdentifier+Panes.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,5 @@ extension Settings.PaneIdentifier {
static let ignore = Self("ignore")
static let pins = Self("pins")
static let storage = Self("storage")
static let automations = Self("automations")
}
64 changes: 64 additions & 0 deletions Maccy/Models/Automation.swift
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)
}
}
}
7 changes: 7 additions & 0 deletions Maccy/Observables/AppState.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,13 @@ class AppState: Sendable {
) {
IgnoreSettingsPane()
},
Settings.Pane(
identifier: Settings.PaneIdentifier.automations,
title: NSLocalizedString("Title", tableName: "AutomationsSettings", comment: ""),
toolbarIcon: NSImage.bolt!
) {
AutomationsSettingsPane()
},
Settings.Pane(
identifier: Settings.PaneIdentifier.advanced,
title: NSLocalizedString("Title", tableName: "AdvancedSettings", comment: ""),
Expand Down
96 changes: 96 additions & 0 deletions Maccy/Observables/AutomationProcessor.swift
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)

Copy link
Copy Markdown
Author

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 echo and variants as they normally would.

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)
}
}
Loading