|
| 1 | +import Foundation |
| 2 | +import SQLite3 |
| 3 | +#if canImport(AppKit) |
| 4 | +import AppKit |
| 5 | +#endif |
| 6 | + |
| 7 | +/// macOSのユーザ辞書データを取り出すためのヘルパー |
| 8 | +/// |
| 9 | +/// - note: |
| 10 | +/// `bash`コマンドとしては次の通りのものに対応 |
| 11 | +/// ```bash |
| 12 | +/// sqlite3 -header -csv ~/Library/KeyboardServices/TextReplacements.db "SELECT ZSHORTCUT, ZPHRASE FROM ZTEXTREPLACEMENTENTRY" |
| 13 | +/// ``` |
| 14 | +public enum SystemUserDictionaryHelper: Sendable { |
| 15 | + #if canImport(AppKit) |
| 16 | + /// Delegate that allows the user to choose **only** a directory named "KeyboardServices". |
| 17 | + private final class KeyboardServicesDirectoryDelegate: NSObject, NSOpenSavePanelDelegate { |
| 18 | + private let allowedFolderName = "KeyboardServices" |
| 19 | + |
| 20 | + /// Controls which items are enabled in the open panel. |
| 21 | + func panel(_ sender: Any, shouldEnable url: URL) -> Bool { |
| 22 | + // Enable selection only for the target directory itself. |
| 23 | + url.hasDirectoryPath && url.lastPathComponent == allowedFolderName |
| 24 | + } |
| 25 | + |
| 26 | + /// Validates the final URL when the user presses “Open”. |
| 27 | + func panel(_ sender: Any, validate url: URL) throws { |
| 28 | + guard url.lastPathComponent == allowedFolderName else { |
| 29 | + throw NSError( |
| 30 | + domain: NSCocoaErrorDomain, |
| 31 | + code: NSUserCancelledError, |
| 32 | + userInfo: [NSLocalizedDescriptionKey: "KeyboardServicesという名前のフォルダのみ選択できます。"] |
| 33 | + ) |
| 34 | + } |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + /// A shared delegate instance that remains alive for the lifetime of the open panel. |
| 39 | + @MainActor private static let keyboardServicesDelegate = KeyboardServicesDirectoryDelegate() |
| 40 | + #endif |
| 41 | + |
| 42 | + public struct Entry: Sendable { |
| 43 | + public let shortcut: String |
| 44 | + public let phrase: String |
| 45 | + } |
| 46 | + |
| 47 | + public enum FetchError: Sendable, Error { |
| 48 | + case fileNotExist(String) |
| 49 | + case fileNotReadable(String) |
| 50 | + case failedToOpenDatabase(status: Int32) |
| 51 | + case failedToPrepareStatement(status: Int32) |
| 52 | + } |
| 53 | + |
| 54 | + @MainActor static func promptUserForTextReplacementDirectory() -> URL? { |
| 55 | + let panel = NSOpenPanel() |
| 56 | + panel.title = "システムのユーザ辞書ディレクトリ(KeyboardServices)を選択してください" |
| 57 | + panel.message = "システムのユーザ辞書ディレクトリ(KeyboardServices)を選択してください" |
| 58 | + panel.canChooseDirectories = true |
| 59 | + panel.canChooseFiles = false |
| 60 | + panel.allowsMultipleSelection = false |
| 61 | + panel.directoryURL = FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent("Library/KeyboardServices") |
| 62 | + #if canImport(AppKit) |
| 63 | + panel.delegate = keyboardServicesDelegate |
| 64 | + #endif |
| 65 | + |
| 66 | + let response = panel.runModal() |
| 67 | + return response == .OK ? panel.url : nil |
| 68 | + } |
| 69 | + |
| 70 | + @MainActor public static func fetchEntries() throws(FetchError) -> [Entry] { |
| 71 | + let userName = NSUserName() |
| 72 | + var dbPath = "/Users/\(userName)/Library/KeyboardServices/TextReplacements.db" |
| 73 | + guard FileManager.default.fileExists(atPath: dbPath) else { |
| 74 | + throw .fileNotExist(dbPath) |
| 75 | + } |
| 76 | + // 事前に取得を試みる |
| 77 | + print("dbPath", dbPath) |
| 78 | + |
| 79 | + let url: URL |
| 80 | + let needStop: Bool |
| 81 | + if !FileManager.default.isReadableFile(atPath: dbPath) { |
| 82 | + #if canImport(AppKit) |
| 83 | + guard let authorizedURL = Self.promptUserForTextReplacementDirectory(), authorizedURL.startAccessingSecurityScopedResource() else { |
| 84 | + throw FetchError.fileNotReadable(dbPath) |
| 85 | + } |
| 86 | + needStop = true |
| 87 | + url = authorizedURL |
| 88 | + #else |
| 89 | + throw FetchError.fileNotReadable(dbPath) |
| 90 | + #endif |
| 91 | + } else { |
| 92 | + needStop = false |
| 93 | + url = URL(fileURLWithPath: dbPath) |
| 94 | + } |
| 95 | + defer { |
| 96 | + if needStop { |
| 97 | + url.stopAccessingSecurityScopedResource() |
| 98 | + } |
| 99 | + } |
| 100 | + |
| 101 | + var db: OpaquePointer? |
| 102 | + |
| 103 | + let openStatus = sqlite3_open_v2(dbPath, &db, SQLITE_OPEN_READONLY, nil) |
| 104 | + guard openStatus == SQLITE_OK else { |
| 105 | + print("Failed to open database") |
| 106 | + throw .failedToOpenDatabase(status: openStatus) |
| 107 | + } |
| 108 | + |
| 109 | + defer { |
| 110 | + sqlite3_close(db) |
| 111 | + } |
| 112 | + |
| 113 | + let query = "SELECT ZSHORTCUT, ZPHRASE FROM ZTEXTREPLACEMENTENTRY" |
| 114 | + var statement: OpaquePointer? |
| 115 | + |
| 116 | + let prepareStatus = sqlite3_prepare_v2(db, query, -1, &statement, nil) |
| 117 | + guard prepareStatus == SQLITE_OK else { |
| 118 | + print("Failed to prepare statement") |
| 119 | + throw .failedToPrepareStatement(status: prepareStatus) |
| 120 | + } |
| 121 | + |
| 122 | + defer { |
| 123 | + sqlite3_finalize(statement) |
| 124 | + } |
| 125 | + |
| 126 | + var entries: [Entry] = [] |
| 127 | + while sqlite3_step(statement) == SQLITE_ROW { |
| 128 | + if let shortcutC = sqlite3_column_text(statement, 0), |
| 129 | + let phraseC = sqlite3_column_text(statement, 1) { |
| 130 | + let shortcut = String(cString: shortcutC) |
| 131 | + let phrase = String(cString: phraseC) |
| 132 | + entries.append(Entry(shortcut: shortcut, phrase: phrase)) |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + return entries |
| 137 | + } |
| 138 | +} |
0 commit comments