diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 3f852e9a..0fdcdff9 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -406,7 +406,7 @@ jobs: # --- 9. 创建 GitHub Release --- - name: Create Release - uses: softprops/action-gh-release@v2 + uses: softprops/action-gh-release@v3 with: files: | ${{ env.ZIP_NAME }} diff --git a/CHANGELOG.md b/CHANGELOG.md index bf971645..406d06d7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] ### Changed +- Copy Path now copies every selected item, one path per line, and writes file URLs so Finder can paste the files themselves. Copy File Name copies every selected item's name the same way - Keep Finder workspace icon caches warm with background preloading and main-thread image resizing - Use lightweight heartbeat replies and reconnect from the last peer activity - Direct Delete now always asks for confirmation before permanently removing files. Hold Option while choosing it to skip the prompt @@ -21,6 +22,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/). - Settings open on manual launch/reopen while hint-triggered and detected login launches stay quiet ### Fixed +- Updates no longer report success when the install failed. Installation errors are surfaced, the staged bundle's version is checked before it replaces the old app, and a failed relaunch keeps the current app running instead of quitting +- Updating from outside /Applications installs the new version and moves the old copy to the Trash, and an older RClick instance now quits itself as soon as a newer one starts. Two copies used to stay on disk and handle every Finder click twice +- External disks and mounted disk images no longer wear RClick's app icon in the Finder sidebar. RClick declares the `externaldrive` symbol, so those entries keep a drive icon instead - Reset All Settings now restores apps, actions, file types, common folders and preferences instead of only writing a log line - New-file auto-rename no longer depends on fixed delays: it waits for Finder to become active, so it stops missing the rename step on slow folders - Auto-rename now explains the missing Accessibility permission once (granted to the RClick app, not the Finder extension) instead of failing silently diff --git a/FinderSyncExt/FinderSyncExt.swift b/FinderSyncExt/FinderSyncExt.swift index bbd77899..39a3988b 100644 --- a/FinderSyncExt/FinderSyncExt.swift +++ b/FinderSyncExt/FinderSyncExt.swift @@ -695,12 +695,10 @@ class FinderSyncExt: FIFinderSync, @unchecked Sendable { sendClickEvent(event) } - /// 快链路:复制路径(与主程序 ActionService.copyPath 语义一致,取第一项) + /// 快链路:复制全部选中项的路径(每行一个),同时写入文件 URL。 + /// 与主程序 ActionService.copyPath 共用 Clipboard 实现,语义不会分叉。 private func copyPathsLocally(_ itemPaths: [String]) { - guard let first = itemPaths.first else { return } - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - pasteboard.setString(first.removingPercentEncoding ?? first, forType: .string) + Clipboard.copyPaths(itemPaths) } @objc private func handleAppClick(_ sender: NSMenuItem) { diff --git a/RClick.xcodeproj/project.pbxproj b/RClick.xcodeproj/project.pbxproj index 35ba53d7..e30a00b5 100644 --- a/RClick.xcodeproj/project.pbxproj +++ b/RClick.xcodeproj/project.pbxproj @@ -76,6 +76,13 @@ ); target = 5C8A29172F83D74A00FE687C /* FinderSyncExt */; }; + 5C96A3902F8A9E2B00D022F8 /* Exceptions for "RClick" folder in "RClick" target */ = { + isa = PBXFileSystemSynchronizedBuildFileExceptionSet; + membershipExceptions = ( + Info.plist, + ); + target = 5C8A28D92F83D65900FE687C /* RClick */; + }; /* End PBXFileSystemSynchronizedBuildFileExceptionSet section */ /* Begin PBXFileSystemSynchronizedRootGroup section */ @@ -84,6 +91,7 @@ exceptions = ( 5C96A3872F8A9E2B00D022F8 /* Exceptions for "RClick" folder in "RClickTests" target */, 5C96A3892F8A9E2B00D022F8 /* Exceptions for "RClick" folder in "FinderSyncExt" target */, + 5C96A3902F8A9E2B00D022F8 /* Exceptions for "RClick" folder in "RClick" target */, ); path = RClick; sourceTree = ""; @@ -489,13 +497,14 @@ CODE_SIGN_ENTITLEMENTS = RClick/RClickDebug.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 20261107001; + CURRENT_PROJECT_VERSION = 20261114001; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 4L3563XCBN; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_PREVIEWS = YES; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = RClick/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = RClick; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity"; INFOPLIST_KEY_LSUIElement = YES; @@ -505,7 +514,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.6; - MARKETING_VERSION = 2.3.3; + MARKETING_VERSION = 2.3.4; PRODUCT_BUNDLE_IDENTIFIER = cn.wflixu.RClick; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -527,13 +536,14 @@ CODE_SIGN_ENTITLEMENTS = RClick/RClick.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 20261107001; + CURRENT_PROJECT_VERSION = 20261114001; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 4L3563XCBN; ENABLE_APP_SANDBOX = YES; ENABLE_HARDENED_RUNTIME = YES; ENABLE_PREVIEWS = YES; GENERATE_INFOPLIST_FILE = YES; + INFOPLIST_FILE = RClick/Info.plist; INFOPLIST_KEY_CFBundleDisplayName = RClick; INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity"; INFOPLIST_KEY_LSUIElement = YES; @@ -543,7 +553,7 @@ "@executable_path/../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.6; - MARKETING_VERSION = 2.3.3; + MARKETING_VERSION = 2.3.4; PRODUCT_BUNDLE_IDENTIFIER = cn.wflixu.RClick; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -606,7 +616,7 @@ CODE_SIGN_ENTITLEMENTS = FinderSyncExt/FinderSyncExt.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 20261107001; + CURRENT_PROJECT_VERSION = 20261114001; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 4L3563XCBN; ENABLE_APP_SANDBOX = YES; @@ -622,7 +632,7 @@ "@executable_path/../../../../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.6; - MARKETING_VERSION = 2.3.3; + MARKETING_VERSION = 2.3.4; PRODUCT_BUNDLE_IDENTIFIER = cn.wflixu.RClick.FinderSyncExt; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; @@ -641,7 +651,7 @@ CODE_SIGN_ENTITLEMENTS = FinderSyncExt/FinderSyncExt.entitlements; CODE_SIGN_STYLE = Automatic; COMBINE_HIDPI_IMAGES = YES; - CURRENT_PROJECT_VERSION = 20261107001; + CURRENT_PROJECT_VERSION = 20261114001; DEAD_CODE_STRIPPING = YES; DEVELOPMENT_TEAM = 4L3563XCBN; ENABLE_APP_SANDBOX = YES; @@ -657,7 +667,7 @@ "@executable_path/../../../../Frameworks", ); MACOSX_DEPLOYMENT_TARGET = 15.6; - MARKETING_VERSION = 2.3.3; + MARKETING_VERSION = 2.3.4; PRODUCT_BUNDLE_IDENTIFIER = cn.wflixu.RClick.FinderSyncExt; PRODUCT_NAME = "$(TARGET_NAME)"; REGISTER_APP_GROUPS = YES; diff --git a/RClick/Info.plist b/RClick/Info.plist index 0761ceaa..a706212e 100644 --- a/RClick/Info.plist +++ b/RClick/Info.plist @@ -2,16 +2,19 @@ - NSAppTransportSecurity + + CFBundleIcons - NSAllowsArbitraryLoads - + CFBundlePrimaryIcon + + CFBundleSymbolName + externaldrive + - NSApplicationSupportsIndirectInputEvents - - NSServices - - - diff --git a/RClick/Localizable.xcstrings b/RClick/Localizable.xcstrings index 0117390a..2cc48412 100644 --- a/RClick/Localizable.xcstrings +++ b/RClick/Localizable.xcstrings @@ -6933,6 +6933,41 @@ } } }, + "The updated application could not be opened. Please start RClick manually." : { + "extractionState" : "manual", + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "translated", + "value" : "The updated application could not be opened. Please start RClick manually." + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "No se pudo abrir la aplicación actualizada. Inicia RClick manualmente." + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Impossible d’ouvrir l’application mise à jour. Veuillez lancer RClick manuellement." + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "更新後のアプリを開けませんでした。RClick を手動で起動してください。" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "无法打开更新后的应用,请手动启动 RClick。" + } + } + } + }, "The user cancelled authorization." : { "extractionState" : "manual", "localizations" : { diff --git a/RClick/RClickApp.swift b/RClick/RClickApp.swift index 4d1b3117..c6554a8b 100644 --- a/RClick/RClickApp.swift +++ b/RClick/RClickApp.swift @@ -97,6 +97,11 @@ class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { logger.info("applicationDidFinishLaunching called") + // 更新后 /Applications 里是新副本,废纸篓或原位置可能还留着旧副本,两者 + // 可以同时运行,并且都会响应 Finder 扩展的点击。在注册任何消息处理器之前 + // 先收敛成一个;如果另一个副本更该留下,这里直接退出。 + guard SingleInstanceGuard.enforceTermination() else { return } + // 设置窗口打开策略。注意 RClick 是 LSUIElement 应用,启动时系统不会 // 激活它(NSApp.isActive 恒为 false),无法用激活状态区分启动来源, // 改用两个显式信号: diff --git a/RClick/Runtime/ActionService.swift b/RClick/Runtime/ActionService.swift index c08dc813..cf216079 100644 --- a/RClick/Runtime/ActionService.swift +++ b/RClick/Runtime/ActionService.swift @@ -30,24 +30,15 @@ final class ActionService { // MARK: - SystemActions /// 复制路径到剪贴板 + /// 复制全部选中项的路径到剪贴板(一行一个),并写入文件 URL。 + /// 与扩展内的离线快链路共用 Clipboard 实现。 func copyPath(_ target: [String]) { - if let dirPath = target.first { - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - pasteboard.setString(dirPath.removingPercentEncoding ?? dirPath, forType: .string) - } + Clipboard.copyPaths(target) } - /// 复制文件名(不含路径)到剪贴板 + /// 复制全部选中项的文件名(不含路径)到剪贴板,一行一个。 func copyFileName(_ target: [String]) { - guard let path = target.first else { return } - let decoded = path.removingPercentEncoding ?? path - let name = URL(fileURLWithPath: decoded).lastPathComponent - guard !name.isEmpty else { return } - - let pasteboard = NSPasteboard.general - pasteboard.clearContents() - pasteboard.setString(name, forType: .string) + Clipboard.copyFileNames(target) } // MARK: - AppActions diff --git a/RClick/Shared/SingleInstanceGuard.swift b/RClick/Shared/SingleInstanceGuard.swift new file mode 100644 index 00000000..ef593a5c --- /dev/null +++ b/RClick/Shared/SingleInstanceGuard.swift @@ -0,0 +1,109 @@ +import AppKit + +/// 同一个 bundle id 的多个副本可以同时运行:它们的路径不同(更新后 /Applications +/// 里是新副本,废纸篓、下载目录或挂载的 DMG 里还留着旧副本),LaunchServices +/// 不会把它们当成同一个实例。Finder 扩展的点击走全局 DistributedNotificationCenter, +/// 两个进程都会收到并各执行一次——打开、删除这类操作会被重复执行。 +/// +/// 沙盒应用**不能终止其他进程**:`NSRunningApplication.terminate()` / +/// `forceTerminate()` 在 App Sandbox 里返回 false(Apple 文档明确说明)。所以收敛 +/// 只能由落败者自己完成:每个实例启动时检查一次,之后每 2 秒再查一次,发现自己 +/// 不该留下就 `NSApp.terminate`。这一条对之后的所有版本都成立;已经发布的旧版本 +/// 没有这段逻辑,只能靠更新流程在安装后重启来避免残留。 +@MainActor +enum SingleInstanceGuard { + struct InstanceInfo: Equatable { + let version: String + let launchDate: Date + let pid: pid_t + } + + private static var monitorTask: Task? + + /// 两个实例之间谁留下。 + /// + /// 版本高者留下;版本相同时后启动的留下——用户刚打开的副本才是他要用的那个 + /// (从 Xcode 跑 Debug 构建也会正确接管,而不是被已经在跑的正式版挤掉)。 + /// 启动时间相同(极罕见)时按 PID 决胜,保证同时启动的两个进程不会互相退出。 + static func shouldKeepSelf(current: InstanceInfo, other: InstanceInfo) -> Bool { + let versionOrder = Version.compare(current.version, other.version) + if versionOrder != .orderedSame { + return versionOrder == .orderedDescending + } + if current.launchDate != other.launchDate { + return current.launchDate > other.launchDate + } + return current.pid < other.pid + } + + /// 启动早期调用。如果已经有更该留下的实例,当前进程直接退出并返回 `false`。 + /// + /// 必须在注册 DistributedNotificationCenter 处理器之前调用,否则在收敛前 + /// 已经有两个进程同时响应 Finder 扩展的点击了。 + @discardableResult + static func enforceTermination() -> Bool { + // 单元测试的宿主进程用的是同一个 bundle id,但它不是用户打开的副本: + // 让它把自己退掉会让测试跑不起来。 + guard !isRunningTests, let bundleID = Bundle.main.bundleIdentifier else { return true } + + let current = currentInstanceInfo() + if let winner = peers(bundleID: bundleID, excluding: current.pid) + .first(where: { !shouldKeepSelf(current: current, other: $0) }) + { + print("Another RClick instance (pid=\(winner.pid) version=\(winner.version)) should keep running; quitting this one") + NSApp.terminate(nil) + return false + } + + startMonitoring(bundleID: bundleID) + return true + } + + /// 另一份副本可能在当前进程启动之后才出现(用户从废纸篓、下载目录或第二份 + /// 安装位置打开它)。每 2 秒复查一次,发现自己该让位就退出。 + private static func startMonitoring(bundleID: String) { + guard monitorTask == nil else { return } + monitorTask = Task { @MainActor in + while !Task.isCancelled { + try? await Task.sleep(for: .seconds(2)) + let current = currentInstanceInfo() + let hasWinner = peers(bundleID: bundleID, excluding: current.pid) + .contains { !shouldKeepSelf(current: current, other: $0) } + if hasWinner { + print("A newer RClick instance appeared; quitting this one") + NSApp.terminate(nil) + return + } + } + } + } + + private static func currentInstanceInfo() -> InstanceInfo { + InstanceInfo( + version: version(of: Bundle.main.bundleURL), + launchDate: NSRunningApplication.current.launchDate ?? .distantPast, + pid: ProcessInfo.processInfo.processIdentifier + ) + } + + private static func peers(bundleID: String, excluding pid: pid_t) -> [InstanceInfo] { + NSRunningApplication.runningApplications(withBundleIdentifier: bundleID) + .filter { $0.processIdentifier != pid && !$0.isTerminated } + .map { application in + InstanceInfo( + version: application.bundleURL.map { version(of: $0) } ?? "0", + launchDate: application.launchDate ?? .distantPast, + pid: application.processIdentifier + ) + } + } + + private static var isRunningTests: Bool { + ProcessInfo.processInfo.environment.keys.contains { $0.hasPrefix("XCTest") } + } + + private static func version(of bundleURL: URL) -> String { + Bundle(url: bundleURL)? + .object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0" + } +} diff --git a/RClick/Shared/Updater.swift b/RClick/Shared/Updater.swift index badbb0b3..af1285ca 100644 --- a/RClick/Shared/Updater.swift +++ b/RClick/Shared/Updater.swift @@ -165,7 +165,7 @@ class GitHubReleaseChecker { return .upToDate } - if compareVersions(currentVersion, latestRelease.version) == .orderedAscending { + if Version.compare(currentVersion, latestRelease.version) == .orderedAscending { return .updateAvailable(latestRelease) } @@ -174,30 +174,6 @@ class GitHubReleaseChecker { return .failed(error.localizedDescription) } } - - // 语义化版本比较 - private func compareVersions(_ version1: String, _ version2: String) -> ComparisonResult { - let components1 = version1.components(separatedBy: ".") - let components2 = version2.components(separatedBy: ".") - - for i in 0 ..< max(components1.count, components2.count) { - let part1 = i < components1.count ? components1[i] : "0" - let part2 = i < components2.count ? components2[i] : "0" - - if let num1 = Int(part1), let num2 = Int(part2) { - if num1 < num2 { return .orderedAscending } - if num1 > num2 { return .orderedDescending } - } else { - // 处理非数字部分(如beta、rc等) - let comparison = part1.compare(part2) - if comparison != .orderedSame { - return comparison - } - } - } - - return .orderedSame - } } // MARK: - 更新管理器 @@ -348,18 +324,22 @@ class UpdateManager: ObservableObject { // 2. 解压到临时目录 let appURL = try await extractAppZip(zipURL: downloadedURL) - // 3. 安装应用到应用程序目录 - try await installApplication(appURL: appURL) - + // 3. 安装应用到应用程序目录(失败会抛出来,不会再假装成功) + try await installApplication(appURL: appURL, expectedVersion: release.version) + // 4. 清理临时文件 try? FileManager.default.removeItem(at: downloadedURL) try? FileManager.default.removeItem(at: appURL.deletingLastPathComponent()) - + // 5. 提示用户安装完成 showInstallationCompleteAlert() - + } catch { - updateError = String(format: AppLocalization.localized("Installation failed: %@"), error.localizedDescription) + let message = String(format: AppLocalization.localized("Installation failed: %@"), error.localizedDescription) + updateError = message + // 更新弹窗在 availableUpdate 非空时仍显示「发现新版本」,错误只会 + // 写进 updateError 而用户看不到——所以失败必须单独弹出来。 + presentUpdateAlert(title: message, message: nil) } isDownloading = false @@ -478,36 +458,75 @@ class UpdateManager: ObservableObject { } } // MARK: - 安装应用到应用程序目录 - private func installApplication(appURL: URL) async throws { - let fileManager = FileManager.default - let applicationsURL = fileManager.urls(for: .applicationDirectory, in: .localDomainMask).first! + + /// 把下载的 app 装进 /Applications 并替换旧版本。 + /// + /// 三条约束: + /// - 失败必须抛出去。旧版本还在原处、界面却报「已更新」,比更新失败本身更糟。 + /// - 先写暂存副本再换位:任何一步失败都不会留下「/Applications 里没有 RClick」的空窗。 + /// - 沙盒写 /Applications 需要用户授权,而 `isWritableFile` 只检查 POSIX 权限、 + /// 看不到沙盒拒绝。所以第一次失败后再弹面板授权、重试一次。 + private func installApplication(appURL: URL, expectedVersion: String) async throws { + let applicationsURL = FileManager.default.urls(for: .applicationDirectory, in: .localDomainMask).first! let destinationAppURL = applicationsURL.appendingPathComponent(appURL.lastPathComponent) print("start install \(appURL.path) --- \(destinationAppURL.path)") - // 安装之前,先检查一下destinationAppURL 是否有权限读写,如果没有权限,请求权限 - // 检查对应用程序文件夹的写入权限 - if !fileManager.isWritableFile(atPath: applicationsURL.path) { - print("没有应用程序文件夹的写入权限,正在请求权限...") + + do { + try replaceApplication(at: destinationAppURL, with: appURL, expectedVersion: expectedVersion) + } catch { + print("首次安装失败,请求 /Applications 授权后重试:\(error)") try await requestApplicationsFolderAccess() + try replaceApplication(at: destinationAppURL, with: appURL, expectedVersion: expectedVersion) } + + removeOriginalCopyIfNeeded(installedAt: destinationAppURL) + } + + /// 暂存 → 校验版本 → 移走旧版本 → 换位。暂存副本放在同一目录,`moveItem` + /// 是同卷重命名,不会出现复制到一半的状态。 + private func replaceApplication(at destinationAppURL: URL, with appURL: URL, expectedVersion: String) throws { + let fileManager = FileManager.default + let stagingURL = destinationAppURL + .deletingLastPathComponent() + .appendingPathComponent(".\(destinationAppURL.lastPathComponent).update-\(UUID().uuidString).app") + + try fileManager.copyItem(at: appURL, to: stagingURL) do { - // 检查目标位置是否已存在应用 + guard let stagedBundle = Bundle(url: stagingURL), + let stagedVersion = stagedBundle.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String, + stagedVersion == expectedVersion + else { + throw InstallationError.invalidAppBundle(AppLocalization.localized("The application bundle is invalid or damaged.")) + } + if fileManager.fileExists(atPath: destinationAppURL.path) { - // 先尝试移动到废纸篓而不是直接删除 + // 正在运行的旧版本移进废纸篓后进程仍继续存活,重启才真正切到新版本 try fileManager.trashItem(at: destinationAppURL, resultingItemURL: nil) } - - // 复制应用到应用程序目录 - try fileManager.copyItem(at: appURL, to: destinationAppURL) - - // 验证应用程序是否有效 - guard Bundle(url: destinationAppURL) != nil else { -// try fileManager.removeItem(at: destinationAppURL) - throw InstallationError.invalidAppBundle(AppLocalization.localized("The application bundle is invalid or damaged.")) - } + try fileManager.moveItem(at: stagingURL, to: destinationAppURL) } catch { - print("❌ 安装失败: \(error)") + try? fileManager.removeItem(at: stagingURL) + throw error + } + } + + /// 从下载目录、挂载的 DMG 或改过名字的副本启动时,更新会装到 /Applications, + /// 原位置那份就留了下来——两份不同版本可以同时运行。安装成功后把正在运行的 + /// 旧副本移进废纸篓;沙盒不允许时只记录日志,单实例守护仍然兜底。 + private func removeOriginalCopyIfNeeded(installedAt destinationAppURL: URL) { + let fileManager = FileManager.default + let currentURL = Bundle.main.bundleURL.standardizedFileURL + let installedURL = destinationAppURL.standardizedFileURL + guard currentURL.path != installedURL.path, + fileManager.fileExists(atPath: currentURL.path) + else { return } + + do { + try fileManager.trashItem(at: currentURL, resultingItemURL: nil) + print("旧副本已移入废纸篓:\(currentURL.path)") + } catch { + print("旧副本无法移入废纸篓:\(error)") } - } // MARK: - App Store 更新引导 @@ -526,18 +545,20 @@ class UpdateManager: ObservableObject { // MARK: - 显示安装完成提示 + /// 安装成功后立即重启,不提供「稍后重启」。 + /// + /// 沙盒应用不能终止其他进程,已经发布的旧版本也没有「发现新实例就自我让位」 + /// 的逻辑。如果让旧进程继续运行,用户之后打开新版本就会变成两个实例同时 + /// 响应 Finder 的点击——这正是 #179 报告的现象。旧进程自己退出是唯一可靠的 + /// 收尾方式,所以这里直接重启。 private func showInstallationCompleteAlert() { let alert = NSAlert() alert.messageText = AppLocalization.localized("Update Installed") alert.informativeText = AppLocalization.localized("The application has been updated successfully. Restart the app to finish the update.") alert.addButton(withTitle: AppLocalization.localized("Restart Now")) - alert.addButton(withTitle: AppLocalization.localized("Restart Later")) - - let response = alert.runModal() - if response == .alertFirstButtonReturn { - // 启动新应用并退出当前应用 - launchNewApplicationAndExit() - } + + _ = alert.runModal() + launchNewApplicationAndExit() } // MARK: - 启动新应用并退出 @@ -547,19 +568,36 @@ class UpdateManager: ObservableObject { let applicationsURL = fileManager.urls(for: .applicationDirectory, in: .localDomainMask).first! let currentAppName = Bundle.main.object(forInfoDictionaryKey: "CFBundleName") as? String ?? "RClick" let newAppURL = applicationsURL.appendingPathComponent("\(currentAppName).app") - + let configuration = NSWorkspace.OpenConfiguration() NSWorkspace.shared.openApplication(at: newAppURL, configuration: configuration) { _, error in - if error != nil { - print("启动新应用失败,可能需要手动启动") - } - // 无论如何都退出当前应用(切回主线程) + // 切回主线程 Task { @MainActor in + if let error { + // 新版本启动失败时保留当前进程:直接退出会让用户以为程序崩了 + print("启动新应用失败:\(error)") + self.presentUpdateAlert( + title: AppLocalization.localized("Update Installed"), + message: AppLocalization.localized("The updated application could not be opened. Please start RClick manually.") + ) + return + } NSApp.terminate(nil) } } } + /// 更新流程里的错误提示。`updateError` 只在更新弹窗没有可用版本时才显示, + /// 安装失败、重启失败都要单独弹窗,否则用户看不到任何反馈。 + private func presentUpdateAlert(title: String, message: String?) { + let alert = NSAlert() + alert.messageText = title + alert.informativeText = message ?? "" + alert.alertStyle = .warning + alert.addButton(withTitle: AppLocalization.localized("OK")) + alert.runModal() + } + // 忽略当前可用更新 func ignoreCurrentUpdate() { if let version = availableUpdate?.version { diff --git a/RClick/Shared/Version.swift b/RClick/Shared/Version.swift new file mode 100644 index 00000000..e9862736 --- /dev/null +++ b/RClick/Shared/Version.swift @@ -0,0 +1,32 @@ +import Foundation + +/// 版本号比较。 +/// +/// 更新检查(判断有没有新版本)和单实例收敛(判断哪个副本该留下)用的是同一套 +/// 规则,不能各写一份——否则会出现「更新器认为 2.3.10 比 2.3.9 新,实例守护却 +/// 认为相反」这种自相矛盾的行为。 +enum Version { + /// 逐段比较,缺省的段按 "0" 处理("2.3" == "2.3.0");非数字段按字符串比较 + /// (足以处理 "2.3.3-beta" 这类标签)。 + nonisolated static func compare(_ version1: String, _ version2: String) -> ComparisonResult { + let components1 = version1.components(separatedBy: ".") + let components2 = version2.components(separatedBy: ".") + + for i in 0 ..< max(components1.count, components2.count) { + let part1 = i < components1.count ? components1[i] : "0" + let part2 = i < components2.count ? components2[i] : "0" + + if let num1 = Int(part1), let num2 = Int(part2) { + if num1 < num2 { return .orderedAscending } + if num1 > num2 { return .orderedDescending } + } else { + let comparison = part1.compare(part2) + if comparison != .orderedSame { + return comparison + } + } + } + + return .orderedSame + } +} diff --git a/RClickTests/ClipboardTests.swift b/RClickTests/ClipboardTests.swift new file mode 100644 index 00000000..d6fdcdfc --- /dev/null +++ b/RClickTests/ClipboardTests.swift @@ -0,0 +1,54 @@ +import AppKit +import Testing + +@testable import RClick + +/// Copy Path / Copy File Name 现在作用于全部选中项。这里钉住剪贴板的写入形状: +/// 文本是换行连接的完整列表,文件 URL 只给 Copy Path,且完整文本只挂在第一项上。 +@MainActor +struct ClipboardTests { + private func makePasteboard() -> NSPasteboard { + NSPasteboard(name: .init("RClickTests-\(UUID().uuidString)")) + } + + @Test func copyPathsWritesEveryPathAsTextAndFileURLs() { + let pasteboard = makePasteboard() + + Clipboard.copyPaths(["/tmp/a.txt", "/tmp/b.txt"], to: pasteboard) + + #expect(pasteboard.string(forType: .string) == "/tmp/a.txt\n/tmp/b.txt") + let items = pasteboard.pasteboardItems ?? [] + #expect(items.count == 2) + #expect(items[0].string(forType: .fileURL) == "file:///tmp/a.txt") + #expect(items[1].string(forType: .fileURL) == "file:///tmp/b.txt") + } + + @Test func copyPathsDecodesPercentEncoding() { + let pasteboard = makePasteboard() + + Clipboard.copyPaths(["/tmp/a%20b.txt"], to: pasteboard) + + #expect(pasteboard.string(forType: .string) == "/tmp/a b.txt") + #expect(pasteboard.pasteboardItems?.first?.string(forType: .fileURL) == "file:///tmp/a%20b.txt") + } + + @Test func copyFileNamesWritesOneNamePerLineAndNoFileURLs() { + let pasteboard = makePasteboard() + + Clipboard.copyFileNames(["/tmp/a.txt", "/tmp/folder/b%20c.md"], to: pasteboard) + + #expect(pasteboard.string(forType: .string) == "a.txt\nb c.md") + #expect(pasteboard.pasteboardItems?.contains { $0.string(forType: .fileURL) != nil } == false) + } + + @Test func emptySelectionLeavesThePasteboardUntouched() { + let pasteboard = makePasteboard() + pasteboard.clearContents() + pasteboard.setString("keep", forType: .string) + + Clipboard.copyPaths([], to: pasteboard) + Clipboard.copyFileNames([], to: pasteboard) + + #expect(pasteboard.string(forType: .string) == "keep") + } +} diff --git a/RClickTests/UpdateInstallationTests.swift b/RClickTests/UpdateInstallationTests.swift new file mode 100644 index 00000000..1d4dd708 --- /dev/null +++ b/RClickTests/UpdateInstallationTests.swift @@ -0,0 +1,75 @@ +import Foundation +import Testing + +@testable import RClick + +/// 更新检查和单实例收敛共用 `Version.compare`。两边规则一旦分叉,会出现 +/// 「更新器认为有新版本、实例守护认为旧副本更新」这种自相矛盾的行为,所以把 +/// 比较规则本身钉住。 +struct VersionTests { + @Test func comparesNumericSegments() { + #expect(Version.compare("2.3.3", "2.3.2") == .orderedDescending) + #expect(Version.compare("2.3.10", "2.3.9") == .orderedDescending) + #expect(Version.compare("2.4", "2.3.9") == .orderedDescending) + #expect(Version.compare("2.3.3", "2.4") == .orderedAscending) + } + + @Test func treatsMissingSegmentsAsZero() { + #expect(Version.compare("2.3", "2.3.0") == .orderedSame) + #expect(Version.compare("2.3", "2.3.1") == .orderedAscending) + } + + @Test func equalVersionsCompareSame() { + #expect(Version.compare("2.3.3", "2.3.3") == .orderedSame) + } +} + +/// 更新后旧副本可能还活着(废纸篓、下载目录、挂载的 DMG)。两个进程都会响应 +/// Finder 扩展的点击,必须收敛成一个。这里钉住"谁留下"的判定。 +@MainActor +struct SingleInstanceGuardTests { + private let earlier = Date(timeIntervalSince1970: 1_000) + private let later = Date(timeIntervalSince1970: 2_000) + + private func info(_ version: String, _ launchDate: Date, _ pid: pid_t) -> SingleInstanceGuard.InstanceInfo { + .init(version: version, launchDate: launchDate, pid: pid) + } + + @Test func newestVersionWins() { + #expect(SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.3", earlier, 200), + other: info("2.3.0", later, 100) + )) + } + + @Test func olderVersionQuits() { + #expect(!SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.0", later, 100), + other: info("2.3.3", earlier, 200) + )) + } + + @Test func sameVersionKeepsTheLaterLaunch() { + // 用户刚打开的副本才该留下:从 Xcode 跑 Debug 构建不该被正式版挤掉 + #expect(SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.3", later, 200), + other: info("2.3.3", earlier, 100) + )) + #expect(!SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.3", earlier, 100), + other: info("2.3.3", later, 200) + )) + } + + @Test func sameVersionAndLaunchTimeKeepsLowerPID() { + // 同时启动时用 PID 决胜,保证两个进程不会互相终止 + #expect(SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.3", earlier, 100), + other: info("2.3.3", earlier, 200) + )) + #expect(!SingleInstanceGuard.shouldKeepSelf( + current: info("2.3.3", earlier, 200), + other: info("2.3.3", earlier, 100) + )) + } +} diff --git a/README.md b/README.md index 2805e0ce..68847843 100644 --- a/README.md +++ b/README.md @@ -16,7 +16,7 @@ Enhance your macOS Finder context menu with custom actions. Built with Swift 6.2 ## 🚀 Features - [x] **Open with External App** — Open files or directories with any installed application, with support for custom arguments and environment variables. Ships with presets for popular editors, terminals and IDEs, per-app visibility for the toolbar and context menus, and none/simple/original icon styles. -- [x] **Copy Path / File Name** — Copy the full path or just the file name of the selected item to the clipboard. +- [x] **Copy Path / File Name** — Copy the full paths or just the file names of all selected items to the clipboard, one per line. - [x] **Delete Direct** — Delete files or folders directly, bypassing Trash. RClick asks for confirmation first; hold **Option** while choosing the action to skip it. - [x] **Hide / Unhide** — Toggle file visibility in Finder. - [x] **AirDrop** — Share files instantly via AirDrop. diff --git a/Shared/Clipboard.swift b/Shared/Clipboard.swift new file mode 100644 index 00000000..076821f5 --- /dev/null +++ b/Shared/Clipboard.swift @@ -0,0 +1,38 @@ +import AppKit + +/// 剪贴板写入。App 与 Finder Sync 扩展共用,保证在线/离线两条路径语义一致。 +enum Clipboard { + /// 复制多个路径:一行一个,同时写入文件 URL,粘到 Finder 里可以直接得到这些文件。 + /// + /// 只有第一个 pasteboard item 带 `.string`(整段多行文本)。文本编辑器读取的是 + /// first item 的字符串;如果每个 item 都带文本,部分应用会把内容重复粘贴。 + nonisolated static func copyPaths(_ paths: [String], to pasteboard: NSPasteboard = .general) { + guard !paths.isEmpty else { return } + let decoded = paths.map { $0.removingPercentEncoding ?? $0 } + let text = decoded.joined(separator: "\n") + + let items = decoded.enumerated().map { index, path -> NSPasteboardItem in + let item = NSPasteboardItem() + item.setString(URL(fileURLWithPath: path).absoluteString, forType: .fileURL) + if index == 0 { + item.setString(text, forType: .string) + } + return item + } + + pasteboard.clearContents() + pasteboard.writeObjects(items) + } + + /// 复制多个文件名(不含路径),一行一个。只写文本——写成文件 URL 会让 + /// 粘到 Finder 的行为变成复制文件,与「复制文件名」的语义不符。 + nonisolated static func copyFileNames(_ paths: [String], to pasteboard: NSPasteboard = .general) { + let names = paths + .map { URL(fileURLWithPath: $0.removingPercentEncoding ?? $0).lastPathComponent } + .filter { !$0.isEmpty } + guard !names.isEmpty else { return } + + pasteboard.clearContents() + pasteboard.setString(names.joined(separator: "\n"), forType: .string) + } +} diff --git a/specs/app-update-installation.md b/specs/app-update-installation.md new file mode 100644 index 00000000..bcb1ea21 --- /dev/null +++ b/specs/app-update-installation.md @@ -0,0 +1,67 @@ +# 应用更新与安装(#179) + +更新安装的职责边界:把新版本放到 `/Applications`、把旧副本清掉、保证同时只有一个 +RClick 进程在响应 Finder 扩展的点击。 + +## 症状 + +更新完成后旧版本仍在,两个版本可以同时打开(#179 的截图里 2.3.3 和 2.3.0 各开着一个 +设置窗口)。 + +## 根因 + +| # | 位置 | 问题 | +|---|---|---| +| 1 | `Updater.swift` `installApplication` | `trashItem` + `copyItem` 包在 `do/catch` 里,`catch` 只打印不抛出;`downloadAndInstallUpdate` 随后照常弹出「Update Installed」 | +| 2 | `Updater.swift` 授权判断 | 用 `isWritableFile(atPath:)` 判断能否写 `/Applications`。它只看 POSIX 权限,看不到沙盒拒绝,因此可能跳过 NSOpenPanel 授权,随后的写入被沙盒拒绝 | +| 3 | `Updater.swift` 安装目标 | 目标固定为 `/Applications/`,与正在运行的副本位置无关。从下载目录、DMG 或改名的副本启动时,更新只会新增一份,旧副本留在原地 | +| 4 | 全局 | 没有单实例保护。两个副本都能启动,并且都注册 `DistributedNotificationCenter`,同一个右键点击会被两个进程各处理一次 | +| 5 | `Updater.swift` `launchNewApplicationAndExit` | 无论新版本是否启动成功都 `NSApp.terminate` | + +```mermaid +flowchart TB + A[旧版本运行中] --> B{安装位置 ==
当前 bundle 位置?} + B -->|是| C[trash 旧包 → copy 新包] + B -->|否| D[copy 到 /Applications] + D --> E[旧副本原地保留] + C --> F{失败?} + F -->|是, 错误被吞| G[提示 Update Installed] + F -->|否| G + G --> H[Restart Later] + H --> I[旧进程继续运行] + E --> J[再打开 /Applications 副本] + I --> K[两个进程同时响应 Finder 点击] + J --> K +``` + +## 规则 + +1. **失败必须可见**:安装链路上的错误一路抛出,界面只在真正成功后提示完成。 +2. **先暂存再换位**:新副本先复制成同目录下的隐藏暂存包,校验 + `CFBundleShortVersionString` 等于 release 版本,再移走旧包、`moveItem` 换位。 + 任何一步失败都不会留下「/Applications 里没有 RClick」的空窗。 +3. **授权失败后重试一次**:第一次写入失败(沙盒拒绝)时弹出 NSOpenPanel 请求 + `/Applications` 授权,然后重试。不再依赖 `isWritableFile` 做前置判断。 +4. **清理旧副本**:安装成功后,如果正在运行的 bundle 不在安装目标位置(下载目录、 + DMG、改过名字的副本),把它移进废纸篓。沙盒不允许时只记录日志。 +5. **单实例(落败者自我退出)**:沙盒应用不能终止其他进程——`NSRunningApplication + .terminate()` / `forceTerminate()` 在 App Sandbox 里返回 `false`(Apple 文档明确 + 说明)。所以收敛由落败者自己完成:每个实例启动时枚举同 bundle id 的进程,版本 + 高者留下;版本相同时后启动的留下;启动时间相同按 PID 决胜。不该留下的实例直接 + `NSApp.terminate`。另一个副本可能在启动之后才出现,因此每 2 秒复查一次。 + 检查必须在注册 DNC 处理器之前完成。 +6. **更新后立即重启,不提供「稍后重启」**:已经发布的旧版本没有自我让位的逻辑, + 沙盒也不能替它退出。留一个「稍后重启」会让旧进程继续运行,之后打开新版本就 + 是两个实例同时响应 Finder 点击。旧进程自己退出是唯一可靠的收尾方式。 +7. **重启失败不退出**:新版本启动成功后才 `terminate`,失败时保留当前进程并提示 + 用户手动启动。 +8. **测试宿主跳过单实例收敛**:单元测试的宿主进程与 App 使用同一个 bundle id, + 但它不是用户打开的副本。 + +## 验证 + +- `xcodebuild build` / `xcodebuild test` / `scripts/check-localization.py` +- 单实例判定:`SingleInstanceGuardTests`(版本、启动时间、PID 三种决胜条件) +- 版本比较:`VersionTests` +- 手工验证:从 `/Applications` 更新后只保留一份;从 DMG 或下载目录运行时更新, + 旧副本进入废纸篓;新实例启动后 2 秒内,旧实例自行退出,设置窗口只剩一个。 diff --git a/specs/external-volumes-observation.md b/specs/external-volumes-observation.md index 6c843ebd..fe5cf7f5 100644 --- a/specs/external-volumes-observation.md +++ b/specs/external-volumes-observation.md @@ -24,14 +24,52 @@ extension; UI-framework interaction and observer cleanup use the main actor. ## The volume's sidebar icon (#155, #158) -Observing a volume root is what makes Finder redraw that volume's sidebar icon -with the extension's own icon. RClick ships no sidebar iconset — the documented -way to supply one — so Finder falls back to the app icon: every external disk and -mounted disk image appears in the sidebar wearing RClick's icon. Measured on this -machine against the installed 2.3.0: mounting a DMG volume produced a sidebar -entry carrying RClick's app icon, while `/` (`Macintosh HD`) and every favourite -folder kept theirs. Badges were blamed twice for this symptom (#128, #155) and -measured false both times; they are not involved. +Observing a root is also what makes Finder draw a sidebar icon for it. When the +observing extension declares no icon, Finder falls back to the containing app's +icon: every external disk and mounted disk image appeared in the sidebar wearing +RClick's icon. Measured on this machine against the installed 2.3.0: mounting a +DMG volume produced a sidebar entry carrying RClick's app icon, while `/` +(`Macintosh HD`) and every favourite folder kept theirs. Badges were blamed twice +for this symptom (#128, #155) and measured false both times; they are not +involved. + +`CFBundleSymbolName` — nested under `CFBundleIcons > CFBundlePrimaryIcon` — is +the documented way to override that fallback. It is declared in the **containing +app's** `Info.plist` (the same key File Provider extensions use for their sidebar +icon) and only affects the Finder sidebar, not the Dock or the app icon. RClick +now declares `externaldrive`. + +The key has to reach the bundle whose icon Finder would otherwise draw. The app +target generates its `Info.plist` (`GENERATE_INFOPLIST_FILE = YES`) and had no +`INFOPLIST_FILE`, so `RClick/Info.plist` was dead weight: the file-system +synchronized group copied it into `Contents/Resources/` and it never became +`Contents/Info.plist`. The target now sets `INFOPLIST_FILE = RClick/Info.plist` +— Xcode merges the generated keys into it, the same arrangement the extension +target already used — and excludes the file from the copy-resources membership. + +### Several extensions compete for the same volume + +Fixing RClick alone does not decide which icon a volume shows. Any Finder Sync +extension that registers the volume root is a candidate, and Finder does not +arbitrate between them: whichever one it picks paints *its* icon. Apps that do +not declare `CFBundleSymbolName` therefore reintroduce the problem even when +RClick is correct. + +This was measured on the same machine, which had FastZip, Sentinel and RClick +enabled at once. With FastZip's extension enabled the USB volume showed FastZip's +icon; disabling it made the same volume show RClick's icon; both apps enumerate +mounted volumes and neither declared a symbol. Declaring `externaldrive` keeps +RClick out of the competition, but it cannot stop another extension from winning. + +```mermaid +flowchart LR + A[RClick observes /Volumes/X] --> D{Finder picks one
extension's icon} + B[FastZip observes /Volumes/X] --> D + C[Sentinel observes /Volumes/X] --> D + D -->|no CFBundleSymbolName| E[that app's icon] + D -->|CFBundleSymbolName| F[externaldrive] + style F fill:#e8f4ff +``` **Observing the volumes' contents instead of their roots does not work.** That variant was implemented, and it removes the icon problem by never observing a @@ -42,13 +80,9 @@ bookmark for a user's volume, so its directory listing is denied and the volume contributes no observation roots at all. A sandboxed FinderSync extension cannot discover what is on a volume; it can only observe the volume. -So the extension observes volume roots and the sidebar icon is a known -consequence, accepted deliberately: a working menu on external disks is worth -more than their sidebar icon, and the alternative loses both. `#158` stays open -as a macOS limitation. If a future release wants the icon as well, the only route -seen so far is the documented sidebar iconset — an iconset in the containing app -with monochrome `sidebar_*.png` templates — which would have to be measured -before it is believed. +So the extension keeps observing volume roots; only the icon they contribute is +now correct. + ## Validation @@ -68,9 +102,19 @@ before it is believed. (mounted at `/Volumes/UPAN`, folders at its root): the volume kept its own sidebar icon — the intended effect — and had no RClick menu anywhere, root or subfolder, which is why it was abandoned. +- Extension competition was measured on this machine with FastZip, Sentinel and + RClick enabled together: the USB volume showed FastZip's icon, and disabling + FastZip's extension made the same volume show RClick's icon. This is what + identified the app icon as the winning extension's icon rather than an RClick + mistake alone. +- The merged bundle plist was checked after a build: `Contents/Info.plist` + contains `CFBundleSymbolName = externaldrive` alongside the generated keys + (`CFBundleIconName`, `LSUIElement`, ...), and `Contents/Resources/Info.plist` + no longer exists. - Normal signing remains blocked by missing upstream provisioning profiles. This - verifies observation-root management, not a signed Finder installation or - physical USB / SMB / NFS / AFP menu appearance and action execution. + verifies observation-root management and bundle metadata, not a signed Finder + installation or physical USB / SMB / NFS / AFP menu appearance and action + execution. After signing and enabling the extension, check a volume mounted before launch, a USB drive and NAS mounted while running, a mounted DMG, rename/eject/remount, @@ -78,7 +122,16 @@ and a normal local folder. Check menus inside each volume as well as on its root then verify an innocuous action such as Copy Path. File Provider-managed locations and sandbox permissions are separate concerns; this change does not bypass them. +For the sidebar icon specifically, insert a USB volume and confirm the sidebar +entry shows a drive icon rather than RClick's app icon. Then re-enable FastZip's +Finder extension and insert the volume again: if FastZip's icon comes back, the +remaining conflict is Finder's missing arbitration, not RClick, and FastZip needs +the same `CFBundleSymbolName` declaration. + Sources: +- https://developer.apple.com/documentation/bundleresources/information-property-list/cfbundleicons/cfbundleprimaryicon/cfbundlesymbolname +- https://developer.apple.com/documentation/fileprovider/setting-the-finder-sidebar-icon +- https://github.com/sarensw/MacPacker/pull/346 - https://developer.apple.com/documentation/findersync/fifindersynccontroller/directoryurls - https://developer.apple.com/documentation/foundation/filemanager/mountedvolumeurls(includingresourcevaluesforkeys:options:) - https://developer.apple.com/documentation/appkit/nsworkspace/didmountnotification