ghostty/macos/Sources/Features/Services/ServiceProvider.swift
Jon Parise 652f551bec macos: simplify some ServiceProvider code
First, remove the always-inlined openTerminalFromPasteboard code and
combine it with openTerminal. Now that we're doing a bit of work inside
openTerminal, there's little better to having an intermediate, inlined
function.

Second, combine some type-casting operations (saving a .map() call).

Lastly, adjust some variable names because a generic `objs` or `urls`
was a little ambiguous now that we're all in one function scope.
2025-06-02 20:11:18 -04:00

65 lines
1.9 KiB
Swift

import Foundation
import AppKit
class ServiceProvider: NSObject {
static private let errorNoString = NSString(string: "Could not load any text from the clipboard.")
/// The target for an open operation
private enum OpenTarget {
case tab
case window
}
@objc func openTab(
_ pasteboard: NSPasteboard,
userData: String?,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
openTerminal(from: pasteboard, target: .tab, error: error)
}
@objc func openWindow(
_ pasteboard: NSPasteboard,
userData: String?,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
openTerminal(from: pasteboard, target: .window, error: error)
}
private func openTerminal(
from pasteboard: NSPasteboard,
target: OpenTarget,
error: AutoreleasingUnsafeMutablePointer<NSString>
) {
guard let delegate = NSApp.delegate as? AppDelegate else { return }
let terminalManager = delegate.terminalManager
guard let pathURLs = pasteboard.readObjects(forClasses: [NSURL.self]) as? [URL] else {
error.pointee = Self.errorNoString
return
}
// Build a set of unique directory URLs to open. File paths are truncated
// to their directories because that's the only thing we can open.
let directoryURLs = Set(
pathURLs.map { url -> URL in
url.hasDirectoryPath ? url : url.deletingLastPathComponent()
}
)
for url in directoryURLs {
var config = Ghostty.SurfaceConfiguration()
config.workingDirectory = url.path(percentEncoded: false)
switch (target) {
case .window:
terminalManager.newWindow(withBaseConfig: config)
case .tab:
terminalManager.newTab(withBaseConfig: config)
}
}
}
}