diff --git a/App/Sources/AppDelegate.swift b/App/Sources/AppDelegate.swift index 551ff1e1c..438b06075 100644 --- a/App/Sources/AppDelegate.swift +++ b/App/Sources/AppDelegate.swift @@ -394,7 +394,7 @@ struct CatalystWeiBeiApp: App { private var workspaceContent: some View { // Native size restrictions own the minimum; scrolling panes extend under the toolbar. CatalystWorkspaceRoot(store: AppDelegate.workspace, appDelegate: appDelegate) - .onOpenURL { AppDelegate.workspace.importFiles([$0]) } + .onOpenURL { AppDelegate.workspace.receiveExternalFileForConfirmedImport($0) } #if WEIBEI_ACCEPTANCE_CHECKS .task { if CommandLine.arguments.contains("--drag-profile"), diff --git a/App/Sources/CatalystBusinessCheck.swift b/App/Sources/CatalystBusinessCheck.swift index 969a40128..6f7f34975 100644 --- a/App/Sources/CatalystBusinessCheck.swift +++ b/App/Sources/CatalystBusinessCheck.swift @@ -381,6 +381,11 @@ enum CatalystBusinessCheck { store.continueLastWork() store.ensureAllStudySessionMessagesLoaded() try await until("reopened note editor") { !store.activeNoteIsLoading && store.noteText.contains(noteMarker) } + let renderedMarker = String(decoding: try JSONEncoder().encode(finalMarker), as: UTF8.self) + try await until("reopened note editor content") { + guard let webView = await editor(documentID: store.activeNoteEditorDocumentID) else { return false } + return (try? await webView.evaluateJavaScript("document.querySelector('.ProseMirror')?.textContent?.includes(\(renderedMarker)) === true") as? Bool) == true + } let history = store.studySessions.flatMap(\.messages) try check("reopen_original_note_and_session_files", store.noteText.contains(finalMarker) && history.contains { $0.text.contains(finalMarker) && $0.completionState == .completed } @@ -432,12 +437,45 @@ enum CatalystBusinessCheck { try "# 阅读位置\n\n候选独立合成资料:内容增长时保留同一处文字。材料标记 WB452_SOURCE。\n".write(to: materialURL, atomically: true, encoding: .utf8) let noteURL = inputs.appendingPathComponent("候选验证笔记.md") try "# 候选验证笔记\n\n这是独立测试资料,不是用户笔记。\n".write(to: noteURL, atomically: true, encoding: .utf8) - let materials: [StudyItem] = await withCheckedContinuation { done in - store.importFiles([materialURL]) { done.resume(returning: $0) } + var confirmedItems: [StudyItem] = [] + let importSheet = { + UIApplication.shared.connectedScenes.compactMap { $0 as? UIWindowScene } + .flatMap(\.windows).flatMap(descendants) + .compactMap { $0 as? CatalystIndependentSheetSizingProbe.Probe } + .first { $0.window != nil && !$0.isHidden && $0.contentSize != nil } } - let notes: [StudyItem] = await withCheckedContinuation { done in - store.importFiles([noteURL], markdownAsNotes: true) { done.resume(returning: $0) } + for (url, asNotes) in [(materialURL, false), (noteURL, true)] { + let previousIDs = Set(store.importedItems.map(\.id)) + store.prepareConfirmedFileImport([url], asNotes: asNotes) + try await until("confirmed import review and fitted native sheet") { + guard store.confirmedFileImport?.stage == .reviewing, + let sheet = importSheet(), let size = sheet.contentSize, + let window = sheet.window, !window.isHidden else { return false } + return abs(window.bounds.width - size.width) < 1 + && abs(window.bounds.height - size.height) < 1 + && size.width > 100 && size.height > 100 + } + if !asNotes, let window = importSheet()?.window { + let snapshot = UIGraphicsImageRenderer(bounds: window.bounds).image { _ in + window.drawHierarchy(in: window.bounds, afterScreenUpdates: true) + } + try snapshot.pngData()?.write(to: LabMetrics.directory.appendingPathComponent("confirmed-import.png")) + } + store.confirmFileImport() + try await until("confirmed import completes and dismisses") { + store.confirmedFileImport == nil && importSheet() == nil + } + let added = store.importedItems.filter { !previousIDs.contains($0.id) } + guard added.count == 1, let imported = added.first, + let copiedURL = store.resolvedLibraryURL(for: imported), + try Data(contentsOf: copiedURL) == Data(contentsOf: url) else { + throw Failure("confirmed import did not preserve the material/note") + } + confirmedItems.append(imported) } + let materials = Array(confirmedItems.prefix(1)) + let notes = Array(confirmedItems.suffix(1)) + try check("confirmed_import_review_copy_and_dismiss", confirmedItems.count == 2) guard let material = materials.first, let note = notes.first, let persistedNote = store.resolvedLibraryURL(for: note) else { throw Failure("original import returned no material/note") } store.openCourseNote(note.id) diff --git a/App/Sources/CatalystWorkspaceChrome.swift b/App/Sources/CatalystWorkspaceChrome.swift index 05ad2ad07..c38f82160 100644 --- a/App/Sources/CatalystWorkspaceChrome.swift +++ b/App/Sources/CatalystWorkspaceChrome.swift @@ -594,13 +594,49 @@ struct CatalystWindowChrome: UIViewRepresentable { } // SwiftUI's Mac Catalyst sheet is hosted in a separate UIKit window. -struct CatalystSheetBackground: UIViewRepresentable { +struct CatalystIndependentSheetFitting: ViewModifier { let color: UIColor + @State private var contentSize = CGSize.zero + + func body(content: Content) -> some View { + content + .onGeometryChange(for: CGSize.self) { proxy in + proxy.size + } action: { size in + contentSize = size + } + .background(CatalystIndependentSheetSizingProbe( + color: color, + contentSize: contentSize + )) + } +} + +struct CatalystIndependentSheetSizingProbe: UIViewRepresentable { + let color: UIColor + var contentSize: CGSize? + + init(color: UIColor, contentSize: CGSize? = nil) { + self.color = color + self.contentSize = contentSize + } + func makeUIView(context: Context) -> Probe { Probe() } - func updateUIView(_ view: Probe, context: Context) { view.color = color; view.configure() } + + func updateUIView(_ view: Probe, context: Context) { + view.color = color + view.contentSize = contentSize + view.configure() + } + final class Probe: UIView { var color = UIColor.clear + var contentSize: CGSize? + private var lastGeometryRequestSignature: String? + override func didMoveToWindow() { super.didMoveToWindow(); configure() } + override func layoutSubviews() { super.layoutSubviews(); configure() } + func configure() { guard let window else { return } window.backgroundColor = color @@ -611,6 +647,124 @@ struct CatalystSheetBackground: UIViewRepresentable { } responder = current.next } + guard let contentSize else { return } + resizeSheetIfNeeded(window: window, targetSize: contentSize) + } + + private func resizeSheetIfNeeded(window: UIWindow, targetSize: CGSize) { + guard targetSize.width.isFinite, targetSize.height.isFinite, + targetSize.width > 0, targetSize.height > 0, + !Self.sameSize(window.bounds.size, targetSize), + let scene = window.windowScene else { return } + let sourceFrame = scene.effectiveGeometry.systemFrame + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard Self.sameSize(sourceFrame.size, window.bounds.size), + rootedWindows.count == 1, + rootedWindows[0] === window else { return } + let targetFrame = Self.centeredFrame(size: targetSize, in: sourceFrame) + let signature = "\(sourceFrame)|\(targetFrame)" + guard signature != lastGeometryRequestSignature else { return } + lastGeometryRequestSignature = signature + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self else { return } + guard let window, let scene, window.windowScene === scene else { + self.clearGeometryRequest(signature) + return + } + self.requestGeometryUpdate( + window: window, + scene: scene, + targetSize: targetSize, + signature: signature + ) + } } + + private func requestGeometryUpdate( + window: UIWindow, + scene: UIWindowScene, + targetSize: CGSize, + signature: String + ) { + guard self.window === window, + let contentSize, + Self.sameSize(contentSize, targetSize) else { + clearGeometryRequest(signature) + return + } + let sourceFrame = scene.effectiveGeometry.systemFrame + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard !Self.sameSize(window.bounds.size, targetSize), + Self.sameSize(sourceFrame.size, window.bounds.size), + rootedWindows.count == 1, + rootedWindows[0] === window else { + clearGeometryRequest(signature) + return + } + let targetFrame = Self.centeredFrame(size: targetSize, in: sourceFrame) + scene.requestGeometryUpdate(.Mac(systemFrame: targetFrame)) { [weak self] _ in + self?.clearGeometryRequest(signature) + } + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self, let window, let scene else { return } + self.synchronizeWindowWithSceneIfNeeded( + window: window, + scene: scene, + targetSize: targetSize + ) + } + } + + private func synchronizeWindowWithSceneIfNeeded( + window: UIWindow, + scene: UIWindowScene, + targetSize: CGSize + ) { + let effectiveFrame = scene.effectiveGeometry.systemFrame + let rootedWindows = scene.windows.filter { $0.rootViewController != nil } + guard self.window === window, + window.windowScene === scene, + rootedWindows.count == 1, + rootedWindows[0] === window, + Self.sameSize(effectiveFrame.size, targetSize), + let rootViewController = window.rootViewController, + let presentationController = rootViewController.presentationController, + presentationController.presentedViewController === rootViewController, + let containerView = presentationController.containerView else { return } + rootViewController.preferredContentSize = targetSize + presentationController.preferredContentSizeDidChange( + forChildContentContainer: rootViewController + ) + containerView.setNeedsLayout() + containerView.layoutIfNeeded() + DispatchQueue.main.async { [weak self, weak window, weak scene] in + guard let self, let window, let scene, + self.window === window, + window.windowScene === scene else { return } + guard let contentSize, + !Self.sameSize(contentSize, targetSize) else { return } + self.configure() + } + } + + private func clearGeometryRequest(_ signature: String) { + if lastGeometryRequestSignature == signature { + lastGeometryRequestSignature = nil + } + } + + private static func sameSize(_ lhs: CGSize, _ rhs: CGSize) -> Bool { + abs(lhs.width - rhs.width) < 1 && abs(lhs.height - rhs.height) < 1 + } + + private static func centeredFrame(size: CGSize, in frame: CGRect) -> CGRect { + CGRect( + x: frame.midX - size.width / 2, + y: frame.midY - size.height / 2, + width: size.width, + height: size.height + ) + } + } } diff --git a/App/WeiBei.xcodeproj/project.pbxproj b/App/WeiBei.xcodeproj/project.pbxproj index af20be7f8..28237e653 100644 --- a/App/WeiBei.xcodeproj/project.pbxproj +++ b/App/WeiBei.xcodeproj/project.pbxproj @@ -156,6 +156,7 @@ 9E35B424552BEC714D64E69B /* HTMLResourceImport.swift in Sources */ = {isa = PBXBuildFile; fileRef = E587D2C74173406238893D89 /* HTMLResourceImport.swift */; }; 9E82B06347DF8AAD02442C3D /* WorkspaceStore+NativeAgent.swift in Sources */ = {isa = PBXBuildFile; fileRef = 74D3DDD62890E2095AE206E6 /* WorkspaceStore+NativeAgent.swift */; }; 9FB05F925099B527532D6EB2 /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 4C114483E09D9B95115B4EF5 /* ContentView.swift */; }; + CF1A00000000000000000001 /* ConfirmedFileImportView.swift in Sources */ = {isa = PBXBuildFile; fileRef = CF1A00000000000000000002 /* ConfirmedFileImportView.swift */; }; 9FD230DCC3C1CCEE79F5B1C1 /* EmptyWorkspaceInspiration.swift in Sources */ = {isa = PBXBuildFile; fileRef = FA378A62D30B6A6251AD9DA6 /* EmptyWorkspaceInspiration.swift */; }; 9FF041C038C5AB9C8A27287A /* PDFReaderOpenSafety.swift in Sources */ = {isa = PBXBuildFile; fileRef = 178A366B5659AC7A47E7AA30 /* PDFReaderOpenSafety.swift */; }; A29105E5484EFF5BE88B2979 /* PaneSeatMotion.swift in Sources */ = {isa = PBXBuildFile; fileRef = A434A3C22BC374DD87D0E041 /* PaneSeatMotion.swift */; }; @@ -348,6 +349,7 @@ 4639CC2F72655275FF9EF5C5 /* WorkspaceStore+GlobalSearch.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "WorkspaceStore+GlobalSearch.swift"; sourceTree = ""; }; 4787853DDB4CD028D2FABC51 /* ContentRailView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentRailView.swift; sourceTree = ""; }; 4C114483E09D9B95115B4EF5 /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = ""; }; + CF1A00000000000000000002 /* ConfirmedFileImportView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConfirmedFileImportView.swift; sourceTree = ""; }; 4CDF85F80AC46C5FE414E777 /* NativeAgentSSE.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NativeAgentSSE.swift; sourceTree = ""; }; 4D52600F1258F2C0DAB31B39 /* ConversationController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ConversationController.swift; sourceTree = ""; }; 50D90DFD2794222AD19D98DD /* WeiBeiUpdateService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = WeiBeiUpdateService.swift; sourceTree = ""; }; @@ -746,6 +748,7 @@ BCFA6009ED31791018CA93D2 /* ComposerView.swift */, 4787853DDB4CD028D2FABC51 /* ContentRailView.swift */, 4C114483E09D9B95115B4EF5 /* ContentView.swift */, + CF1A00000000000000000002 /* ConfirmedFileImportView.swift */, E51AB9EF50CCEDB319397D8C /* ContextualContentPicker.swift */, E59061F53CCAA6551A4ABABC /* ConversationWebClippingView.swift */, ED28080243B8A8B552763344 /* CourseDocNoteWorkspaceView.swift */, @@ -1271,6 +1274,7 @@ 90A2214DC79342A465A01D96 /* ComposerView.swift in Sources */, 186031B66D5FC7464EB6CB2C /* ContentRailView.swift in Sources */, 9FB05F925099B527532D6EB2 /* ContentView.swift in Sources */, + CF1A00000000000000000001 /* ConfirmedFileImportView.swift in Sources */, 24D17FE22AAD67D99C583D71 /* ContextualContentPicker.swift in Sources */, 82A9C07B68A5A0E9C1844E14 /* ConversationController.swift in Sources */, C2683F836E4926D9F60998FD /* ConversationData.swift in Sources */, diff --git a/App/WindowBridge/NativeWindowBridge.swift b/App/WindowBridge/NativeWindowBridge.swift index b70dff2a2..d94e5b78f 100644 --- a/App/WindowBridge/NativeWindowBridge.swift +++ b/App/WindowBridge/NativeWindowBridge.swift @@ -1,5 +1,6 @@ import AppKit import Combine +import UniformTypeIdentifiers /// Native window services and Sparkle use this bridge; content stays in Catalyst. @objc(WeiBeiCatalystWindowBridge) @@ -8,6 +9,7 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { private var intensity = 1.0 private let materials = NSMapTable.weakToStrongObjects() private var observers: [NSObjectProtocol] = [] + private var activeOpenPanel: NSOpenPanel? @MainActor private lazy var updateService = WeiBeiUpdateService() @MainActor private var updateObservation: AnyCancellable? @@ -115,6 +117,80 @@ final class NativeWindowBridge: NSObject, CatalystWindowBridge { func open(_ url: URL) -> Bool { NSWorkspace.shared.open(url) } func reveal(_ url: URL) { NSWorkspace.shared.activateFileViewerSelecting([url]) } func materialWindowCount() -> Int { materials.count } + @MainActor func presentOpenPanel( + title: String, + contentTypeIdentifiers: [String], + allowsMultipleSelection: Bool, + canChooseDirectories: Bool, + canChooseFiles: Bool, + presentationToolbar: NSObject?, + completion: @MainActor @escaping ([URL], NSError?) -> Void + ) { + guard activeOpenPanel == nil else { + completeOpenPanelFailure( + code: 1, + completion: completion + ) + return + } + let owner: NSWindow + if let toolbar = presentationToolbar as? NSToolbar { + let roots = NSApp.windows.filter { $0.toolbar === toolbar } + guard roots.count == 1, let root = roots.first, root.isVisible else { + completeOpenPanelFailure( + code: 2, + completion: completion + ) + return + } + var presentationWindow = root + while let sheet = presentationWindow.attachedSheet { presentationWindow = sheet } + owner = presentationWindow + } else { + guard let keyWindow = NSApp.keyWindow, + keyWindow.isVisible, + !keyWindow.isMiniaturized, + keyWindow.attachedSheet == nil else { + completeOpenPanelFailure( + code: 3, + completion: completion + ) + return + } + owner = keyWindow + } + guard !(owner is NSOpenPanel) else { + completeOpenPanelFailure( + code: 4, + completion: completion + ) + return + } + + let panel = NSOpenPanel() + panel.title = title + panel.canChooseDirectories = canChooseDirectories + panel.canChooseFiles = canChooseFiles + panel.allowsMultipleSelection = allowsMultipleSelection + panel.allowedContentTypes = contentTypeIdentifiers.map { UTType($0) ?? UTType(importedAs: $0) } + activeOpenPanel = panel + panel.beginSheetModal(for: owner) { [weak self] response in + let urls = response == .OK ? panel.urls : [] + self?.activeOpenPanel = nil + // Resume Catalyst on the next main-loop turn, after AppKit has detached the sheet. + DispatchQueue.main.async { completion(urls, nil) } + } + } + @MainActor private func completeOpenPanelFailure( + code: Int, + completion: @MainActor ([URL], NSError?) -> Void + ) { + WeiBeiLog.workspace.error("code=native_open_panel_failed reason=\(code, privacy: .public)") + completion([], NSError( + domain: "WeiBei.NativeOpenPanel", + code: code + )) + } @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) { updateObservation = updateService.$status.combineLatest(updateService.$availableUpdate) .sink { status, update in diff --git a/App/WindowBridge/WindowBridgeContract.swift b/App/WindowBridge/WindowBridgeContract.swift index da39141c2..0009609dd 100644 --- a/App/WindowBridge/WindowBridgeContract.swift +++ b/App/WindowBridge/WindowBridgeContract.swift @@ -10,6 +10,15 @@ import Foundation func open(_ url: URL) -> Bool func reveal(_ url: URL) func materialWindowCount() -> Int + @MainActor func presentOpenPanel( + title: String, + contentTypeIdentifiers: [String], + allowsMultipleSelection: Bool, + canChooseDirectories: Bool, + canChooseFiles: Bool, + presentationToolbar: NSObject?, + completion: @MainActor @escaping ([URL], NSError?) -> Void + ) @MainActor func observeUpdates(_ observer: @escaping (String, String?, [String], Bool, URL?) -> Void) @MainActor func checkForUpdates() @MainActor func installAvailableUpdate() diff --git a/App/script/check-ci.sh b/App/script/check-ci.sh index 71b670719..606a2cc93 100755 --- a/App/script/check-ci.sh +++ b/App/script/check-ci.sh @@ -17,6 +17,7 @@ save_evidence() { "${CHECK_SUPPORT:-$CHECK_DIR}/Workspace/business-failure.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-composers.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-discussion.png" \ + "${CHECK_SUPPORT:-$CHECK_DIR}/Results/confirmed-import.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/selection-rich-answer-11pt.png" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/floating-rich-diagnostic.json" \ "${CHECK_SUPPORT:-$CHECK_DIR}/Results/reasoning-composer.png" \ @@ -71,6 +72,7 @@ verify(business_path, 'source', 'awaiting_reopen') launch('--exit-after-check') business = verify(business_path, 'source', 'passed') required_business_checks = { + 'confirmed_import_review_copy_and_dismiss', 'reopen_original_note_and_session_files', 'mac_idiom_and_isolated_storage', 'original_update_service_through_native_bridge', 'native_workspace_toolbar_controls', 'signed_native_window_material', 'original_import_reader_and_editor', @@ -86,14 +88,14 @@ required_business_checks = { 'floating_11pt_math_diagram_and_layout', 'divider_interface_language_updates', } -# Require all baseline, floating, and interface-language gates; verify() above +# Require baseline, floating, interface-language, and confirmed-import gates; verify() above # rejects failures in additional gates as well. assert required_business_checks <= business['checks'].keys(), business assert business['floating_rich_answer']['body_font_size_pt'] == 11, business assert business['floating_rich_answer']['math_images'] == 2, business shutil.copy2(business_path, evidence / 'ci-business.json') shutil.copy2(support / 'Results/workspace.png', evidence / 'ci-business-window.png') -for filename in ['selection-composers.png', 'selection-discussion.png', 'selection-rich-answer-11pt.png', 'reasoning-composer.png']: +for filename in ['selection-composers.png', 'selection-discussion.png', 'confirmed-import.png', 'selection-rich-answer-11pt.png', 'reasoning-composer.png']: shutil.copy2(support / 'Results' / filename, evidence / ('ci-' + filename)) print(f"14 项会话检查与 {len(business['checks'])} 项原业务保存重开检查通过;含浮窗 11pt 公式与图示、原生工具栏、选区双输入框与引用定位,不替代鼠标、输入法及触控板体验验收。") diff --git "a/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" new file mode 100644 index 000000000..8235caa2b --- /dev/null +++ "b/Docs/plans/2026-09-29-\347\273\237\344\270\200\346\213\226\346\224\276\345\257\274\345\205\245\345\256\232\346\241\210.md" @@ -0,0 +1,45 @@ +# 统一拖放导入定案 + +日期:2026-09-29。状态:已按用户确认方案实施,等待组合构建与真实拖放验收。 + +## 用户流程 + +首页、普通工作台、课程内和从 Dock 打开文件都进入同一确认面板。文件选择器入口也复用该面板。普通入口默认“通用资料”,课程入口默认当前课程;明确的笔记入口只接受 Markdown,并默认导入为笔记。 + +课程创建页里预先选择的初始文件也只在课程创建完成后进入同一确认面板,不会直接复制。若当前批次正在导入时又从 Dock 打开文件,新文件会显示为下一批待处理项;用户可以在当前结果页继续核对,不会静默丢掉选择。 + +面板先列出实际可导入文件、不支持项、重复项和同名冲突,再选择归属。通用资料始终在首项,课程支持搜索和新建。新建课程沿用原有资料库目录与权限流程;取消新建只关闭新建面板,原批次和当前选择保留。 + +确认文案直接写目标,例如“加入《投资学》”。确认前只读取文件信息和比对内容,不创建目录、不复制文件。确认后仍在同一面板显示当前文件和进度,可停止剩余文件;已经完成的文件保留。 + +## 数据处理 + +| 情况 | 处理 | +| --- | --- | +| 支持的普通文件 | 调用现有通用资料复制或课程文件事务 | +| 内容完全相同且同名 | 标为“重复,跳过”,不再次复制 | +| 同名但内容不同 | 确认前显示新名称,确认后保留两份,不覆盖 | +| 不支持的文件 | 确认前列出并跳过;全部不支持时禁用确认 | +| 文件夹内不支持的文件 | 沿用既有安全遍历范围递归列出;隐藏项、应用包、符号链接和 `node_modules` 不越界展开 | +| 同批同名且内容相同 | 第二份标为重复并跳过,只登记一次成功 | +| 单个文件失败 | 保留本批已成功结果,显示失败原因 | +| 重试 | 只重新核对和导入失败文件 | +| 停止 | 当前正在处理的文件结束后停止剩余文件 | + +重复与冲突判断直接复用底层复制能力的同一份逐字节比较和命名规则,没有增加“内容去重”声明或另一套摘要数据库。课程写入继续使用现有可恢复事务;通用资料继续写入现有资料库目录。原文件始终保留。 + +## 完成后的去向 + +单个成功文件可直接打开。多个成功文件可进入对应的通用资料列表或课程文稿/笔记页,本批文件以朱砂浅底短暂突出三秒。结果面板分别显示成功、跳过和失败数量;停止状态另行说明未继续处理剩余文件。 + +## 验收边界 + +自动行为检查覆盖:确认前取消零写入、停止剩余任务、部分失败保留成功、只重试失败项、碰撞预检与真实复制使用同一规则。组合构建与测试由主任务统一执行,建议过滤器: + +```sh +swift test --filter ConfirmedFileImportTests +swift test --filter HTMLResourceImportTests +swift test --filter LibraryRelativeOnlyTests +``` + +真实 App 仍需在最终候选包验证:首页、工作台、课程文稿、课程笔记及 Dock 五个入口;Finder 多文件与文件夹拖入;新建课程取消/成功;停止按钮;部分失败重试;单个打开与批量定位高亮。静态代码和自动检查不能替代这些拖放体验证据。 diff --git a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift index d7904a28e..d4cc7bc92 100644 --- a/Sources/WeiBei/Stores/CourseProjectRootSupport.swift +++ b/Sources/WeiBei/Stores/CourseProjectRootSupport.swift @@ -1904,6 +1904,153 @@ actor CourseProjectFileWorker { return identity } + func copyImportedFilePreservingOriginal( + from rawSourceURL: URL, + into rawDestinationDirectory: URL, + libraryRoot rawLibraryRoot: URL, + expectedLibraryRootIdentity: ImportedFileIdentity + ) throws -> URL { + let source = try validatedRegularSource(rawSourceURL) + let sourceSnapshot = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity + ) + let rawLibraryRoot = rawLibraryRoot.standardizedFileURL + let libraryRoot = try CourseProjectPathPolicy.existingDirectory(rawLibraryRoot) + guard CourseProjectPathPolicy.isSame(rawLibraryRoot, libraryRoot), + Self.identity(at: libraryRoot) == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let destinationDirectory = try ensureRealDirectory( + rawDestinationDirectory, + inside: libraryRoot + ) + guard let destinationDirectoryIdentity = Self.identity(at: destinationDirectory), + Self.identity(at: libraryRoot) == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let preparedHTML = try prepareHTMLImport(at: source.url) + let payloadSnapshot = preparedHTML.map { snapshot(of: $0) } + ?? sourceSnapshot + let preferredURL = destinationDirectory.appendingPathComponent( + source.url.lastPathComponent + ) + let targetURL: URL + if !fileManager.fileExists(atPath: preferredURL.path) { + targetURL = preferredURL + } else { + let existingSource = try validatedRegularSource(preferredURL) + let existingSnapshot = try stableSnapshot( + at: preferredURL, + expectedIdentity: existingSource.identity + ) + let existing = try stableMetadata( + at: preferredURL, + expectedIdentity: existingSource.identity, + expectedSnapshot: existingSnapshot + ) + if existingSnapshot == payloadSnapshot { + _ = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity, + expectedSnapshot: sourceSnapshot + ) + let currentDirectory = try ensureRealDirectory( + rawDestinationDirectory, + inside: libraryRoot + ) + guard CourseProjectPathPolicy.isSame( + currentDirectory, + destinationDirectory + ), Self.identity(at: currentDirectory) + == destinationDirectoryIdentity, + Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + _ = try stableMetadata( + at: existing.url, + expectedIdentity: existing.identity, + expectedSnapshot: existingSnapshot + ) + return existing.url + } + targetURL = ImportFileCopy.uniqueCopyURL( + in: destinationDirectory, + preferred: preferredURL + ) + } + + let rawStagingDirectory = try fileManager.url( + for: .itemReplacementDirectory, + in: .userDomainMask, + appropriateFor: destinationDirectory, + create: true + ) + defer { try? fileManager.removeItem(at: rawStagingDirectory) } + let stagingValues = try rawStagingDirectory.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]) + let stagingDirectory = try CourseProjectPathPolicy.existingDirectory( + rawStagingDirectory + ) + guard stagingValues.isDirectory == true, + stagingValues.isSymbolicLink != true, + stagingValues.isAliasFile != true, + CourseProjectPathPolicy.isSame( + rawStagingDirectory, + stagingDirectory + ), + Self.identity(at: stagingDirectory)?.volumeID + == destinationDirectoryIdentity.volumeID else { + throw CourseProjectFileWorkerError.unsafePath + } + let payloadURL = stagingDirectory.appendingPathComponent("payload") + let stagedIdentity = try copyAndVerify( + from: preparedHTML == nil ? source.url : nil, + generatedData: preparedHTML, + to: payloadURL, + expectedSnapshot: payloadSnapshot + ) + _ = try stableMetadata( + at: payloadURL, + expectedIdentity: stagedIdentity, + expectedSnapshot: payloadSnapshot + ) + _ = try stableSnapshot( + at: source.url, + expectedIdentity: source.identity, + expectedSnapshot: sourceSnapshot + ) + guard Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + let placedIdentity = try placeWithoutReplacement( + from: payloadURL, + to: targetURL, + courseRoot: libraryRoot, + destinationDirectory: destinationDirectory, + expectedDestinationIdentity: destinationDirectoryIdentity, + expectedSnapshot: payloadSnapshot + ) + guard placedIdentity == stagedIdentity else { + throw CourseProjectFileWorkerError.verificationFailed + } + _ = try stableMetadata( + at: targetURL, + expectedIdentity: placedIdentity, + expectedSnapshot: payloadSnapshot + ) + guard Self.identity(at: libraryRoot) + == expectedLibraryRootIdentity else { + throw CourseProjectFileWorkerError.unsafePath + } + return targetURL + } + func write(_ data: Data, to url: URL) throws { try data.write(to: url, options: [.atomic]) } @@ -3147,41 +3294,124 @@ actor CourseProjectFileWorker { from urls: [URL], markdownOnly: Bool ) -> [URL] { + expandedImportSelection(from: urls, markdownOnly: markdownOnly).supported + } + + nonisolated static func expandedImportSelection( + from urls: [URL], + markdownOnly: Bool + ) -> ( + supported: [URL], + unsupportedNames: [String], + unavailableSourceURLs: [URL] + ) { let fileManager = FileManager.default - var seen = Set() - var result: [URL] = [] + var seenSupported = Set() + var seenUnsupported = Set() + var seenUnavailable = Set() + var supported: [URL] = [] + var unsupportedNames: [String] = [] + var unavailableSourceURLs: [URL] = [] + func recordUnavailable(_ url: URL) { + let standardized = url.standardizedFileURL + if seenUnavailable.insert(standardized.path).inserted { + unavailableSourceURLs.append(standardized) + } + } for rawURL in urls { - var isDirectory: ObjCBool = false - guard fileManager.fileExists(atPath: rawURL.path, isDirectory: &isDirectory) else { + guard let rootValues = try? rawURL.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]) else { + recordUnavailable(rawURL) continue } - if !isDirectory.boolValue { - appendSupported(rawURL, markdownOnly: markdownOnly, seen: &seen, result: &result) + guard rootValues.isSymbolicLink != true, + rootValues.isAliasFile != true else { + continue + } + if rootValues.isDirectory != true { + guard fileManager.isReadableFile(atPath: rawURL.path) else { + recordUnavailable(rawURL) + continue + } + appendImportSelection( + rawURL, + displayName: rawURL.lastPathComponent, + markdownOnly: markdownOnly, + seenSupported: &seenSupported, + seenUnsupported: &seenUnsupported, + supported: &supported, + unsupportedNames: &unsupportedNames + ) continue } guard !Self.ignoresImportDirectory(rawURL) else { continue } guard let enumerator = fileManager.enumerator( at: rawURL, includingPropertiesForKeys: [ + .isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey, .isAliasFileKey, ], options: [.skipsHiddenFiles, .skipsPackageDescendants], - errorHandler: { _, _ in false } + errorHandler: { failedURL, _ in + recordUnavailable(failedURL) + return true + } ) else { + recordUnavailable(rawURL) continue } for case let fileURL as URL in enumerator { + guard let values = try? fileURL.resourceValues(forKeys: [ + .isDirectoryKey, + .isSymbolicLinkKey, + .isAliasFileKey, + ]) else { + recordUnavailable(fileURL) + enumerator.skipDescendants() + continue + } + if values.isSymbolicLink == true || values.isAliasFile == true { + enumerator.skipDescendants() + continue + } if Self.ignoresImportDirectory(fileURL), - (try? fileURL.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true { + values.isDirectory == true { enumerator.skipDescendants() continue } - appendSupported(fileURL, markdownOnly: markdownOnly, seen: &seen, result: &result) + if values.isDirectory != true, + !fileManager.isReadableFile(atPath: fileURL.path) { + recordUnavailable(fileURL) + continue + } + let rootPath = rawURL.standardizedFileURL.path + let filePath = fileURL.standardizedFileURL.path + let relativePath = filePath.hasPrefix(rootPath + "/") + ? String(filePath.dropFirst(rootPath.count + 1)) + : fileURL.lastPathComponent + appendImportSelection( + fileURL, + displayName: "\(rawURL.lastPathComponent)/\(relativePath)", + markdownOnly: markdownOnly, + seenSupported: &seenSupported, + seenUnsupported: &seenUnsupported, + supported: &supported, + unsupportedNames: &unsupportedNames + ) } } - return result.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending } + return ( + supported.sorted { $0.path.localizedStandardCompare($1.path) == .orderedAscending }, + unsupportedNames.sorted { $0.localizedStandardCompare($1) == .orderedAscending }, + unavailableSourceURLs.sorted { + $0.path.localizedStandardCompare($1.path) == .orderedAscending + } + ) } private func copyVisibleCourseTree( @@ -3593,16 +3823,16 @@ actor CourseProjectFileWorker { } } - nonisolated private static func appendSupported( + nonisolated private static func appendImportSelection( _ rawURL: URL, + displayName: String, markdownOnly: Bool, - seen: inout Set, - result: inout [URL] + seenSupported: inout Set, + seenUnsupported: inout Set, + supported: inout [URL], + unsupportedNames: inout [String] ) { - let pathExtension = rawURL.pathExtension.lowercased() - guard Self.supportedExtensions.contains(pathExtension), - !markdownOnly || ["md", "markdown"].contains(pathExtension), - let values = try? rawURL.resourceValues(forKeys: [ + guard let values = try? rawURL.resourceValues(forKeys: [ .isRegularFileKey, .isSymbolicLinkKey, .isAliasFileKey, @@ -3613,8 +3843,14 @@ actor CourseProjectFileWorker { return } let url = rawURL.standardizedFileURL - guard seen.insert(url.path).inserted else { return } - result.append(url) + let pathExtension = rawURL.pathExtension.lowercased() + if Self.supportedExtensions.contains(pathExtension), + !markdownOnly || ["md", "markdown"].contains(pathExtension) { + guard seenSupported.insert(url.path).inserted else { return } + supported.append(url) + } else if seenUnsupported.insert(url.path).inserted { + unsupportedNames.append(displayName) + } } nonisolated static func identity(at url: URL) -> ImportedFileIdentity? { diff --git a/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift b/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift index 76988cb30..4193b6ec6 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+CourseLibrary.swift @@ -2914,7 +2914,7 @@ extension WorkspaceStore { urlPath: resolvedTarget.path, importedFileIdentity: targetIdentity, isSample: false, - isNotebookNote: role == .note || detectedKind == .markdown, + isNotebookNote: role == .note, appearsInMaterials: role == .material, storage: itemStorage, contentRevision: replacingItemIndex == nil diff --git a/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift b/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift index 98568f043..939187211 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+CourseMaintenance.swift @@ -420,7 +420,6 @@ extension WorkspaceStore { relativePath: "\(directoryName)/\(observation.relativePath)" ) - nextItem.isNotebookNote = isNote || nextItem.kind == .markdown nextItem.appearsInMaterials = nextItem.appearsInMaterials ?? !isNote nextItem.contentRevision = revision nextItem.contentDigest = digest @@ -452,7 +451,7 @@ extension WorkspaceStore { urlPath: observation.url.path, importedFileIdentity: observation.identity, isSample: false, - isNotebookNote: isNote || StudyItemKind.detect(from: observation.url) == .markdown, + isNotebookNote: isNote, appearsInMaterials: !isNote, storage: .common( relativePath: @@ -758,7 +757,6 @@ extension WorkspaceStore { nextItem.kind = StudyItemKind.detect(from: observation.url) nextItem.urlPath = observation.url.path nextItem.importedFileIdentity = observation.identity - nextItem.isNotebookNote = observation.isNote || nextItem.kind == .markdown nextItem.appearsInMaterials = nextItem.appearsInMaterials ?? !observation.isNote nextItem.contentRevision = nextRevision nextItem.contentDigest = nextDigest @@ -801,7 +799,7 @@ extension WorkspaceStore { urlPath: observation.url.path, importedFileIdentity: observation.identity, isSample: false, - isNotebookNote: observation.isNote || StudyItemKind.detect(from: observation.url) == .markdown, + isNotebookNote: observation.isNote, appearsInMaterials: !observation.isNote, storage: .courseOwned( ownerCourseID: courseID, diff --git a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift index b16cb7883..82f445af6 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+LibraryRoot.swift @@ -59,40 +59,17 @@ extension WorkspaceStore { bootstrapDefaultLibraryIfNeeded() } - func copyExternalFileIntoCourse( - _ sourceURL: URL, - courseID: UUID, - isNote: Bool - ) throws -> URL { - guard let courseRoot = courseRootURL(for: courseID) else { - throw CourseProjectRootError.unavailableLibrary - } - let directoryName = isNote - ? CourseLibraryLayout.courseNotesDirectoryName - : CourseLibraryLayout.courseMaterialsDirectoryName - let directory = courseRoot.appendingPathComponent( - directoryName, - isDirectory: true - ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) - return try Self.copyPreservingOriginal(from: sourceURL, into: directory) - } - - /// Kernel-side copy with the original dedupe semantics: identical content - /// resolves to the existing file, real conflicts get a unique name. Size is - /// compared before any byte read, so large imports never enter memory whole. - nonisolated static func copyPreservingOriginal(from sourceURL: URL, into directory: URL) throws -> URL { - try ImportFileCopy.copyPreservingOriginal(from: sourceURL, into: directory) - } - - nonisolated static func copyExternalFileIntoLibrary( + func copyExternalFileIntoLibrary( root: URL, sourceURL: URL, isNote: Bool - ) throws -> URL { + ) async throws -> URL { + guard let expectedLibraryRootIdentity = courseLibraryRootIdentity, + courseLibraryRootURL.map({ + CourseProjectPathPolicy.isSame($0, root) + }) == true else { + throw CourseProjectRootError.unavailableLibrary + } let directoryName = isNote ? CourseLibraryLayout.commonNotesDirectoryName : CourseLibraryLayout.commonMaterialsDirectoryName @@ -100,11 +77,13 @@ extension WorkspaceStore { directoryName, isDirectory: true ) - try FileManager.default.createDirectory( - at: directory, - withIntermediateDirectories: true - ) - return try ImportFileCopy.copyPreservingOriginal(from: sourceURL, into: directory) + return try await courseProjectFileWorker + .copyImportedFilePreservingOriginal( + from: sourceURL, + into: directory, + libraryRoot: root, + expectedLibraryRootIdentity: expectedLibraryRootIdentity + ) } func libraryRelativePath(of url: URL) -> String? { @@ -554,7 +533,7 @@ extension WorkspaceStore { let nextTitle = url.deletingPathExtension().lastPathComponent let nextSubtitle = url.lastPathComponent let nextKind = StudyItemKind.detect(from: url) - let nextRole = Self.isMarkdownFile(url) + let nextRole = importsIntoNotes let nextMaterialVisibility = !importsIntoNotes if importedItems[matchingIndex].isNotebookNote != nextRole { roleChanged = true @@ -583,7 +562,7 @@ extension WorkspaceStore { kind: StudyItemKind.detect(from: url), urlPath: url.path, isSample: false, - isNotebookNote: Self.isMarkdownFile(url), + isNotebookNote: importsIntoNotes, appearsInMaterials: !importsIntoNotes, storage: .common(relativePath: relativePath) ) diff --git a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift index 462b57a03..c974787a9 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore+NotesPersistence.swift @@ -837,7 +837,8 @@ extension WorkspaceStore { /// 全仓唯一笔记写盘闸门(计划 §5 阶段1):所有写路径必须经此函数。 /// 文件在场时写前重读磁盘 digest:重读失败或无基线 ⇒ 拒写并保留待写内容; - /// 摘要不符 ⇒ 待写内容先入备份环再抛采用磁盘;一致才落盘并刷新双 digest。 + /// 待写内容已与磁盘一致 ⇒ 幂等采用并刷新双 digest; + /// 摘要不符 ⇒ 待写内容先入备份环再抛采用磁盘;基线一致才落盘并刷新双 digest。 /// 禁止绕过本函数直接调用 notebookMarkdownWriter(SelfCheck SAFETY 断言白名单)。 func writeNotebookMarkdownThroughGate( _ markdown: String, @@ -845,6 +846,7 @@ extension WorkspaceStore { url: URL, expectedBaseline: String? ) throws { + let intendedDigest = Self.noteContentDigest(Data(markdown.utf8)) var operationError: Error? var coordinationError: NSError? NSFileCoordinator().coordinate( @@ -861,6 +863,11 @@ extension WorkspaceStore { ) throw NoteWriteGateError.writeRefusedKeepContent } + if diskDigest == intendedDigest { + noteBackingContentDigestsByItemID[itemID] = diskDigest + lastSelfWrittenNoteDigestsByItemID[itemID] = diskDigest + return + } if diskDigest != expectedBaseline { WeiBeiLog.noteRepair.error( "code=note_write_external_conflict path=\(coordinatedURL.path, privacy: .private) expected_digest=\(expectedBaseline, privacy: .private) actual_digest=\(diskDigest, privacy: .private)" @@ -869,7 +876,7 @@ extension WorkspaceStore { } } try notebookMarkdownWriter(markdown, coordinatedURL) - let writtenDigest = Self.noteContentDigest(Data(markdown.utf8)) + let writtenDigest = intendedDigest let verifiedDigest = Self.noteContentDigest(at: coordinatedURL) guard verifiedDigest == writtenDigest else { WeiBeiLog.noteRepair.error( diff --git a/Sources/WeiBei/Stores/WorkspaceStore.swift b/Sources/WeiBei/Stores/WorkspaceStore.swift index 548a2aa43..8c73b2c26 100644 --- a/Sources/WeiBei/Stores/WorkspaceStore.swift +++ b/Sources/WeiBei/Stores/WorkspaceStore.swift @@ -697,6 +697,13 @@ final class WorkspaceStore: ObservableObject { /// 展示兼容:界面与对话框仍按字符串消费保存失败文案。 var workspaceSaveError: String? { workspaceSaveFailure?.message } @Published private(set) var courseFileOperationProgress: CourseFileOperationProgress? + @Published var confirmedFileImport: ConfirmedFileImportBatch? + @Published var recentlyImportedItemIDs: Set = [] + var confirmedFileImportTask: Task? + var confirmedFileImportStopRequested = false + var confirmedFileImportSecurityScopes: [URL] = [] + var pendingConfirmedFileImports: [PendingConfirmedFileImport] = [] + var recentlyImportedClearTask: Task? @Published var notebookCreationDraft: NotebookCreationDraft? @Published var notebookRenameDraft: NotebookRenameDraft? var notebookRenameInFlight = false @@ -737,7 +744,7 @@ final class WorkspaceStore: ObservableObject { /// 先登记、不动文件。内存态即可:重启丢基线只少一次自动改名,方向安全。 var headingSyncedNoteStemByItemID: [String: String] = [:] var loadedCourseNoteTextByItemID: [String: String] = [:] - var courseNoteLoadTasksByItemID: [String: Task] = [:] + @Published var courseNoteLoadTasksByItemID: [String: Task] = [:] var courseNoteLoadGenerationByItemID: [String: UInt64] = [:] var courseNoteWritesInFlight = Set() var courseNoteWriteTasksByItemID: [String: Task] = [:] @@ -1140,7 +1147,7 @@ final class WorkspaceStore: ObservableObject { } } - deinit { + isolated deinit { courseReconciliationTask?.cancel() courseNoteLoadTasksByItemID.values.forEach { $0.cancel() } courseNoteWriteTasksByItemID.values.forEach { $0.cancel() } @@ -5880,7 +5887,7 @@ final class WorkspaceStore: ObservableObject { } func importFilesFromPanel() { - presentImportPanel(linkToActiveNote: false) + presentImportPanel() } @discardableResult @@ -5905,9 +5912,6 @@ final class WorkspaceStore: ObservableObject { func importCourseMaterialsFromPanel(courseID: UUID?) { presentImportPanel( - linkToActiveNote: false, - selectsFirstImportedItem: false, - reclassifiesExistingMarkdown: true, assigningToCourseID: courseID, panelTitle: ui("选择课程资料或文件夹", "Choose course materials or a folder") ) @@ -5919,52 +5923,34 @@ final class WorkspaceStore: ObservableObject { func importCourseNotesFromPanel(courseID: UUID?) { presentImportPanel( - linkToActiveNote: false, - selectsFirstImportedItem: false, markdownAsNotes: true, - markdownOnly: true, - reclassifiesExistingMarkdown: true, assigningToCourseID: courseID, panelTitle: ui("选择 Markdown 笔记或文件夹", "Choose Markdown notes or a folder") ) } private func presentImportPanel( - linkToActiveNote: Bool, - selectsFirstImportedItem: Bool = true, markdownAsNotes: Bool = false, - markdownOnly: Bool = false, - reclassifiesExistingMarkdown: Bool = false, assigningToCourseID: UUID? = nil, panelTitle: String? = nil ) { #if targetEnvironment(macCatalyst) Task { @MainActor in - let types: [UTType] = markdownOnly - ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText, .folder] + let types: [UTType] = markdownAsNotes + ? [WorkspaceFileDialog.markdownType, .folder] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, .folder] let urls = await WorkspaceFileDialog.pick( title: panelTitle ?? ui("选择学习资料或课程文件夹", "Choose study materials or a course folder"), types: types, multiple: true ) guard !urls.isEmpty else { return } - let scoped = urls.filter { $0.startAccessingSecurityScopedResource() } - let releaseScopes = { scoped.forEach { $0.stopAccessingSecurityScopedResource() } } - if let assigningToCourseID { - importCourseFilesFromURLs(urls, asNotes: markdownAsNotes, courseID: assigningToCourseID) { _ in releaseScopes() } - return - } - let targetNoteID = linkToActiveNote ? activeNotebookItemID : nil - importFiles(urls, selectsFirstImportedItem: selectsFirstImportedItem, - markdownAsNotes: markdownAsNotes, markdownOnly: markdownOnly, - reclassifiesExistingMarkdown: reclassifiesExistingMarkdown) { selectedItems in - defer { releaseScopes() } - if let targetNoteID, self.activeNotebookItemID == targetNoteID { - self.setLinkedSourceIDsForActiveNote( - Set(self.linkedSourceIDsForActiveNote).union(selectedItems.map(\.id)) - ) - } - } + let scoped = urls.filter(courseSecurityScopeStarter) + prepareConfirmedFileImport( + urls, + courseID: assigningToCourseID, + asNotes: markdownAsNotes, + securityScopedURLs: scoped + ) } #else let panel = NSOpenPanel() @@ -5972,33 +5958,16 @@ final class WorkspaceStore: ObservableObject { panel.allowsMultipleSelection = true panel.canChooseDirectories = true panel.canChooseFiles = true - panel.allowedContentTypes = markdownOnly - ? [UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] - : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText, UTType(filenameExtension: "md") ?? .plainText, UTType(filenameExtension: "markdown") ?? .plainText] + panel.allowedContentTypes = markdownAsNotes + ? [WorkspaceFileDialog.markdownType] + : [UTType(importedAs: "org.openxmlformats.wordprocessingml.document"), UTType(importedAs: "org.openxmlformats.presentationml.presentation"), .pdf, .html, .plainText] guard panel.runModal() == .OK else { return } - if let assigningToCourseID { - importCourseFilesFromURLs( - panel.urls, - asNotes: markdownAsNotes, - courseID: assigningToCourseID - ) - return - } - let targetNoteID = linkToActiveNote ? activeNotebookItemID : nil - importFiles( + prepareConfirmedFileImport( panel.urls, - selectsFirstImportedItem: selectsFirstImportedItem, - markdownAsNotes: markdownAsNotes, - markdownOnly: markdownOnly, - reclassifiesExistingMarkdown: reclassifiesExistingMarkdown - ) { selectedItems in - if let targetNoteID, self.activeNotebookItemID == targetNoteID { - self.setLinkedSourceIDsForActiveNote( - Set(self.linkedSourceIDsForActiveNote).union(selectedItems.map(\.id)) - ) - } - } + courseID: assigningToCourseID, + asNotes: markdownAsNotes + ) #endif } @@ -6039,7 +6008,10 @@ final class WorkspaceStore: ObservableObject { let importsIntoNotes = Self.isMarkdownFile(rawURL) && (markdownNotePaths?.contains(rawURL.path) ?? markdownAsNotes) do { - let url = try Self.copyExternalFileIntoLibrary( + guard let self else { + throw CancellationError() + } + let url = try await self.copyExternalFileIntoLibrary( root: libraryRoot, sourceURL: rawURL, isNote: importsIntoNotes @@ -11257,6 +11229,9 @@ final class WorkspaceStore: ObservableObject { defer { if courseNoteLoadGenerationByItemID[itemID] == generation { courseNoteLoadTasksByItemID[itemID] = nil + // @Published 在字典改动前发出通知;读盘结束后再发布一次, + // 让笔记栏按已经清空的任务状态退出载入分支并重新挂载编辑器。 + objectWillChange.send() } } do { diff --git a/Sources/WeiBei/Support/Theme.swift b/Sources/WeiBei/Support/Theme.swift index 8c19e21f7..bd1e7993f 100644 --- a/Sources/WeiBei/Support/Theme.swift +++ b/Sources/WeiBei/Support/Theme.swift @@ -2000,3 +2000,14 @@ extension Image { } extension WeiBeiMetric { static let courseDrawerWidth: CGFloat = 252 } + +struct WeiBeiFittedSheetPresentation: ViewModifier { + @ViewBuilder + func body(content: Content) -> some View { + if #available(iOS 18.0, macOS 15.0, *) { + content.presentationSizing(.fitted) + } else { + content + } + } +} diff --git a/Sources/WeiBei/Support/WorkspaceFileDialog.swift b/Sources/WeiBei/Support/WorkspaceFileDialog.swift index ec89ca286..dfa3b1c89 100644 --- a/Sources/WeiBei/Support/WorkspaceFileDialog.swift +++ b/Sources/WeiBei/Support/WorkspaceFileDialog.swift @@ -9,6 +9,11 @@ import AppKit /// The same file-operation choices on both hosts. A dismissed dialog cancels. @MainActor enum WorkspaceFileDialog { + static let markdownType = UTType( + importedAs: "net.daringfireball.markdown", + conformingTo: .plainText + ) + struct Choice { let index: Int let text: String? @@ -52,6 +57,36 @@ enum WorkspaceFileDialog { #if targetEnvironment(macCatalyst) static func pick(title: String, types: [UTType], multiple: Bool) async -> [URL] { guard let presenter else { return [] } + let canChooseDirectories = types.contains(.folder) + let fileTypes = types.filter { $0 != .folder } + if canChooseDirectories, !fileTypes.isEmpty { + let sourceWindow = presenter.view.window + let toolbar = sourceWindow?.windowScene?.titlebar?.toolbar + if toolbar == nil, sourceWindow?.isKeyWindow != true { + await showNativeOpenPanelFailure(NSError( + domain: "WeiBei.NativeOpenPanel", + code: 5 + ), from: presenter) + return [] + } + let result: ([URL], NSError?) = await withCheckedContinuation { continuation in + CatalystDesktopWindow.shared.presentOpenPanel( + title: title, + contentTypeIdentifiers: fileTypes.map(\.identifier), + allowsMultipleSelection: multiple, + canChooseDirectories: true, + canChooseFiles: true, + presentationToolbar: toolbar + ) { urls, error in + continuation.resume(returning: (urls, error)) + } + } + if let error = result.1 { + await showNativeOpenPanelFailure(error, from: presenter) + return [] + } + return result.0 + } let picker = Picker(forOpeningContentTypes: types, asCopy: false) picker.title = title picker.allowsMultipleSelection = multiple @@ -89,6 +124,33 @@ enum WorkspaceFileDialog { return controller } + private static func showNativeOpenPanelFailure( + _ error: NSError, + from presenter: UIViewController + ) async { + let store = AppDelegate.workspace + let busy = error.code == 1 || error.code == 4 + let alert = UIAlertController( + title: store.ui("无法打开文件选择器", "File Picker Unavailable"), + message: busy + ? store.ui( + "当前窗口正在显示另一个文件选择器,请先关闭后重试。", + "Another file picker is already open. Close it and try again." + ) + : store.ui( + "当前窗口暂时无法打开文件选择器,请关闭其他弹窗后重试。", + "The file picker cannot open in this window right now. Close other dialogs and try again." + ), + preferredStyle: .alert + ) + await withCheckedContinuation { continuation in + alert.addAction(UIAlertAction(title: store.ui("好", "OK"), style: .default) { _ in + continuation.resume() + }) + presenter.present(alert, animated: true) + } + } + final class Picker: UIDocumentPickerViewController, UIDocumentPickerDelegate, UIAdaptivePresentationControllerDelegate { var completion: CheckedContinuation<[URL], Never>? func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) { finish(urls) } diff --git a/Sources/WeiBei/Views/ConfirmedFileImportView.swift b/Sources/WeiBei/Views/ConfirmedFileImportView.swift new file mode 100644 index 000000000..76be97a9b --- /dev/null +++ b/Sources/WeiBei/Views/ConfirmedFileImportView.swift @@ -0,0 +1,1271 @@ +import Foundation +import SwiftUI +import WeiBeiCore + +enum ConfirmedFileImportStage: Equatable, Sendable { + case preparing + case reviewing + case importing + case finished +} + +enum ConfirmedFileImportDisposition: Equatable, Sendable { + case ready + case duplicate + case conflict(suggestedFileName: String) +} + +struct ConfirmedFileImportCandidate: Identifiable, Equatable, Sendable { + let sourceURL: URL + var disposition: ConfirmedFileImportDisposition + var id: String { sourceURL.path } +} + +struct ConfirmedFileImportFailure: Identifiable, Equatable, Sendable { + let sourceURL: URL + let message: String + var id: String { sourceURL.path } +} + +struct PendingConfirmedFileImport: Sendable { + var sourceURLs: [URL] + var courseID: UUID? + var importsMarkdownAsNotes: Bool + var securityScopedURLs: [URL] +} + +struct ConfirmedFileImportBatch: Identifiable, Equatable, Sendable { + let id: UUID + var sourceURLs: [URL] + var sourceFolderNames: [String] + var courseID: UUID? + var importsMarkdownAsNotes: Bool + var stage: ConfirmedFileImportStage = .preparing + var candidates: [ConfirmedFileImportCandidate] = [] + var unsupportedNames: [String] = [] + var importedItems: [StudyItem] = [] + var successfulCopiesByOriginalName: [String: [URL]] = [:] + var failures: [ConfirmedFileImportFailure] = [] + var previousDuplicateCount = 0 + var previousUnsupportedCount = 0 + var completed = 0 + var total = 0 + var currentFileName: String? + var stopped = false + var destinationError: String? + var pendingSourceURLs: [URL] = [] + + var confirmableCount: Int { + candidates.count + } + + var skippedCount: Int { + duplicateCount + unsupportedCount + } + + var duplicateCount: Int { + previousDuplicateCount + + candidates.filter { $0.disposition == .duplicate }.count + } + + var unsupportedCount: Int { + previousUnsupportedCount + unsupportedNames.count + } +} + +extension WorkspaceStore { + func prepareConfirmedFileImport( + _ urls: [URL], + courseID: UUID? = nil, + asNotes: Bool = false, + securityScopedURLs: [URL] = [] + ) { + guard !urls.isEmpty else { + releaseConfirmedFileImportSecurityScopes(securityScopedURLs) + return + } + if confirmedFileImport?.stage == .importing { + enqueuePendingConfirmedFileImport( + urls, + courseID: courseID, + asNotes: asNotes, + securityScopedURLs: securityScopedURLs + ) + return + } + dismissConfirmedFileImport() + confirmedFileImportSecurityScopes = securityScopedURLs + let folders = urls.filter { + (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + }.map(\.lastPathComponent) + confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: urls, + sourceFolderNames: folders, + courseID: courseID, + importsMarkdownAsNotes: asNotes + ) + refreshConfirmedFileImportPlan() + } + + func receiveExternalFileForConfirmedImport(_ url: URL) { + if confirmedFileImport?.stage == .importing { + enqueuePendingConfirmedFileImport([url]) + return + } + if var batch = confirmedFileImport, + batch.courseID == nil, + !batch.importsMarkdownAsNotes, + (batch.stage == .preparing || batch.stage == .reviewing) { + if !batch.sourceURLs.contains(where: { + $0.standardizedFileURL == url.standardizedFileURL + }) { + batch.sourceURLs.append(url) + confirmedFileImport = batch + refreshConfirmedFileImportPlan() + } + return + } + prepareConfirmedFileImport([url]) + } + + func setConfirmedFileImportDestination(courseID: UUID?) { + guard var batch = confirmedFileImport, + batch.stage == .reviewing || batch.stage == .preparing else { return } + batch.courseID = courseID + confirmedFileImport = batch + refreshConfirmedFileImportPlan() + } + + func selectNewCourseForConfirmedFileImport(_ courseID: UUID) { + setConfirmedFileImportDestination(courseID: courseID) + } + + func dismissConfirmedFileImport() { + confirmedFileImportTask?.cancel() + confirmedFileImportTask = nil + releaseConfirmedFileImportSecurityScopes(confirmedFileImportSecurityScopes) + for request in pendingConfirmedFileImports { + releaseConfirmedFileImportSecurityScopes(request.securityScopedURLs) + } + confirmedFileImportSecurityScopes = [] + pendingConfirmedFileImports = [] + confirmedFileImportStopRequested = false + confirmedFileImport = nil + } + + func stopConfirmedFileImport() { + guard confirmedFileImport?.stage == .importing else { return } + confirmedFileImportStopRequested = true + } + + func continuePendingConfirmedFileImport(abandoningFailures: Bool = false) { + guard let batch = confirmedFileImport, + batch.stage == .finished, + !pendingConfirmedFileImports.isEmpty, + batch.failures.isEmpty || abandoningFailures else { return } + let request = pendingConfirmedFileImports.removeFirst() + releaseConfirmedFileImportSecurityScopes(confirmedFileImportSecurityScopes) + confirmedFileImportSecurityScopes = request.securityScopedURLs + let remainingURLs = pendingConfirmedFileImports.flatMap(\.sourceURLs) + let folders = request.sourceURLs.filter { + (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true + }.map(\.lastPathComponent) + confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: request.sourceURLs, + sourceFolderNames: folders, + courseID: request.courseID, + importsMarkdownAsNotes: request.importsMarkdownAsNotes, + pendingSourceURLs: remainingURLs + ) + refreshConfirmedFileImportPlan() + } + + private func enqueuePendingConfirmedFileImport( + _ urls: [URL], + courseID: UUID? = nil, + asNotes: Bool = false, + securityScopedURLs: [URL] = [] + ) { + guard var batch = confirmedFileImport, batch.stage == .importing else { + releaseConfirmedFileImportSecurityScopes(securityScopedURLs) + return + } + var knownPaths = Set() + if batch.courseID == courseID, batch.importsMarkdownAsNotes == asNotes { + knownPaths.formUnion(batch.sourceURLs.map { $0.standardizedFileURL.path }) + } + for request in pendingConfirmedFileImports + where request.courseID == courseID + && request.importsMarkdownAsNotes == asNotes { + knownPaths.formUnion(request.sourceURLs.map { $0.standardizedFileURL.path }) + } + let acceptedURLs = urls.filter { + knownPaths.insert($0.standardizedFileURL.path).inserted + } + let acceptedPaths = Set(acceptedURLs.map { $0.standardizedFileURL.path }) + let acceptedScopes = securityScopedURLs.filter { + acceptedPaths.contains($0.standardizedFileURL.path) + } + releaseConfirmedFileImportSecurityScopes( + securityScopedURLs.filter { + !acceptedPaths.contains($0.standardizedFileURL.path) + } + ) + guard !acceptedURLs.isEmpty else { return } + pendingConfirmedFileImports.append(PendingConfirmedFileImport( + sourceURLs: acceptedURLs, + courseID: courseID, + importsMarkdownAsNotes: asNotes, + securityScopedURLs: acceptedScopes + )) + batch.pendingSourceURLs = pendingConfirmedFileImports.flatMap(\.sourceURLs) + confirmedFileImport = batch + } + + private func releaseConfirmedFileImportSecurityScopes(_ urls: [URL]) { + urls.forEach(courseSecurityScopeStopper) + } + + func prepareInitialCourseImportAfterEntryDismissal( + _ urls: [URL], + courseID: UUID + ) { + guard !urls.isEmpty else { return } + Task { @MainActor [weak self] in + await Task.yield() + self?.prepareConfirmedFileImport(urls, courseID: courseID) + } + } + + func retryFailedConfirmedFileImport() { + guard let batch = confirmedFileImport, + batch.stage == .finished, + !batch.failures.isEmpty else { return } + let failedURLs = batch.failures.map(\.sourceURL) + confirmedFileImport = ConfirmedFileImportBatch( + id: batch.id, + sourceURLs: failedURLs, + sourceFolderNames: batch.sourceFolderNames, + courseID: batch.courseID, + importsMarkdownAsNotes: batch.importsMarkdownAsNotes, + importedItems: batch.importedItems, + successfulCopiesByOriginalName: batch.successfulCopiesByOriginalName, + previousDuplicateCount: batch.duplicateCount, + previousUnsupportedCount: batch.unsupportedCount, + pendingSourceURLs: batch.pendingSourceURLs + ) + refreshConfirmedFileImportPlan() + } + + func confirmFileImport() { + guard var batch = confirmedFileImport, + batch.stage == .reviewing, + batch.confirmableCount > 0, + batch.destinationError == nil else { return } + batch.stage = .importing + let preflightFailures = batch.failures + batch.failures = [] + batch.completed = 0 + batch.total = batch.candidates.count + batch.unsupportedNames.count + batch.currentFileName = nil + batch.stopped = false + confirmedFileImportStopRequested = false + confirmedFileImport = batch + + let initialBatch = batch + confirmedFileImportTask = Task { @MainActor [weak self] in + guard let self else { return } + var batch = initialBatch + var imported = batch.importedItems + var failures = preflightFailures + var completed = batch.unsupportedNames.count + for (candidateIndex, plannedCandidate) in batch.candidates.enumerated() { + var candidate = plannedCandidate + if confirmedFileImportStopRequested { + batch.stopped = true + break + } + batch.currentFileName = candidate.sourceURL.lastPathComponent + batch.completed = completed + publishConfirmedFileImportProgress(batch) + defer { + completed += 1 + batch.completed = completed + publishConfirmedFileImportProgress(batch) + } + do { + let successfulCopies = batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ] + if candidate.disposition == .duplicate || !successfulCopies.isEmpty { + // A preview may refer to an earlier source whose copy failed, + // or to destination content that changed before confirmation. + candidate.disposition = .ready + batch.candidates[candidateIndex] = candidate + candidate.disposition = try await revalidatedDuplicateDisposition( + candidate.sourceURL, + batch: batch, + successfulCopies: successfulCopies + ) + batch.candidates[candidateIndex] = candidate + if candidate.disposition == .duplicate { continue } + } + let item = try await importConfirmedFile(candidate, batch: batch) + if !imported.contains(where: { $0.id == item.id }) { + imported.append(item) + } + if let copiedURL = resolvedLibraryURL(for: item) { + batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ].append(copiedURL) + } + } catch { + if let recovered = await recoverConfirmedCourseImport( + candidate, + batch: batch + ) { + if !imported.contains(where: { $0.id == recovered.id }) { + imported.append(recovered) + } + if let copiedURL = resolvedLibraryURL(for: recovered) { + batch.successfulCopiesByOriginalName[ + candidate.sourceURL.lastPathComponent, + default: [] + ].append(copiedURL) + } + continue + } + WeiBeiLog.workspace.error( + "code=confirmed_import_failed underlying=\(WeiBeiLog.code(error), privacy: .public) path=\(candidate.sourceURL.path, privacy: .private) detail=\(WeiBeiLog.truncated(error.localizedDescription), privacy: .private)" + ) + failures.append(ConfirmedFileImportFailure( + sourceURL: candidate.sourceURL, + message: confirmedImportFailureMessage(error) + )) + } + } + batch.stage = .finished + batch.currentFileName = nil + batch.importedItems = imported + batch.failures = failures + batch.completed = completed + batch.stopped = batch.stopped || confirmedFileImportStopRequested + confirmedFileImportStopRequested = false + confirmedFileImportTask = nil + settleConfirmedFileImport(batch) + } + } + + private func publishConfirmedFileImportProgress(_ batch: ConfirmedFileImportBatch) { + var next = batch + if let current = confirmedFileImport, current.id == batch.id { + for url in current.pendingSourceURLs where !next.pendingSourceURLs.contains(where: { + $0.standardizedFileURL == url.standardizedFileURL + }) { + next.pendingSourceURLs.append(url) + } + } + confirmedFileImport = next + } + + private func settleConfirmedFileImport(_ batch: ConfirmedFileImportBatch) { + guard confirmedFileImport?.id == batch.id else { return } + publishConfirmedFileImportProgress(batch) + guard let settled = confirmedFileImport, settled.id == batch.id else { return } + if settled.stopped, + settled.failures.isEmpty, + settled.pendingSourceURLs.isEmpty { + let remaining = max(0, settled.total - settled.completed) + dismissConfirmedFileImport() + showTransientNoteStatus( + remaining > 0 + ? ui( + "导入已停止;\(remaining) 份未导入。", + "Import stopped; \(remaining) item(s) were not imported." + ) + : ui( + "导入已停止;已完成的导入仍然保留。", + "Import stopped. Completed imports were kept." + ) + ) + return + } + guard settled.failures.isEmpty, + !settled.stopped, + settled.pendingSourceURLs.isEmpty else { return } + + let feedback = confirmedImportCompletionFeedback(settled) + if settled.importedItems.count == 1 { + openSingleConfirmedImport() + } else if !settled.importedItems.isEmpty { + showConfirmedImportBatch() + } else { + dismissConfirmedFileImport() + } + if let feedback { + showTransientNoteStatus(feedback) + } + } + + private func confirmedImportCompletionFeedback(_ batch: ConfirmedFileImportBatch) -> String? { + let imported = batch.importedItems.count + let duplicates = batch.duplicateCount + let unsupported = batch.unsupportedCount + let chineseRole = batch.importsMarkdownAsNotes ? "笔记" : "资料" + let englishRole = batch.importsMarkdownAsNotes ? "notes" : "materials" + if imported == 0 { + if duplicates > 0, unsupported > 0 { + return ui( + "没有新增内容;\(duplicates) 个已存在,\(unsupported) 个格式不支持。", + "Nothing new was imported. \(duplicates) already existed and \(unsupported) had unsupported formats." + ) + } + if duplicates > 0 { + return ui( + "这 \(duplicates) 份\(chineseRole)已存在,未重复导入。", + "These \(duplicates) \(englishRole) already exist and were not imported again." + ) + } + if unsupported > 0 { + return ui( + "没有可导入的文件;\(unsupported) 个格式不支持。", + "No files could be imported; \(unsupported) had unsupported formats." + ) + } + return ui( + "所选内容没有可导入的文件。", + "The selected content has no importable files." + ) + } + if duplicates > 0, unsupported > 0 { + return ui( + "\(duplicates) 个已存在未重复导入,\(unsupported) 个格式不支持。", + "\(duplicates) already existed and were not imported again; \(unsupported) had unsupported formats." + ) + } + if duplicates > 0 { + return ui( + "\(duplicates) 个已存在,未重复导入。", + "\(duplicates) already existed and were not imported again." + ) + } + if unsupported > 0 { + return ui( + "\(unsupported) 个格式不支持,未导入。", + "\(unsupported) had unsupported formats and were not imported." + ) + } + return nil + } + + func openSingleConfirmedImport() { + guard let batch = confirmedFileImport, batch.importedItems.count == 1, + let item = batch.importedItems.first else { return } + if let courseID = batch.courseID { + if batch.importsMarkdownAsNotes { + _ = openCourseNote(item.id, in: courseID) + } else { + _ = openCourseMaterial(item.id, in: courseID) + } + } else { + if courseWorkspacePresented { dismissCourseWorkspace() } + selectMeasured(itemID: item.id, opensNotebook: batch.importsMarkdownAsNotes) + } + dismissConfirmedFileImport() + } + + func showConfirmedImportBatch() { + guard let batch = confirmedFileImport, !batch.importedItems.isEmpty else { return } + librarySearch = "" + if let courseID = batch.courseID { + activateCourse(courseID) + } + recentlyImportedItemIDs = Set(batch.importedItems.map(\.id)) + recentlyImportedClearTask?.cancel() + recentlyImportedClearTask = Task { @MainActor [weak self] in + try? await Task.sleep(for: .seconds(3)) + guard !Task.isCancelled else { return } + self?.recentlyImportedItemIDs = [] + } + if courseWorkspacePresented { dismissCourseWorkspace(restoringFocus: false) } + revealLibrary() + dismissConfirmedFileImport() + } + + private func refreshConfirmedFileImportPlan() { + guard var batch = confirmedFileImport else { return } + confirmedFileImportTask?.cancel() + batch.stage = .preparing + batch.candidates = [] + batch.unsupportedNames = [] + batch.destinationError = nil + confirmedFileImport = batch + + let batchID = batch.id + let urls = batch.sourceURLs + let asNotes = batch.importsMarkdownAsNotes + let courseID = batch.courseID + let successfulCopies = batch.successfulCopiesByOriginalName + let destination: URL? + if let courseID { + destination = courseRootURL(for: courseID)?.appendingPathComponent( + asNotes ? CourseOwnedFileRole.note.directoryName : CourseOwnedFileRole.material.directoryName, + isDirectory: true + ) + } else { + destination = courseLibraryRootURL?.appendingPathComponent( + asNotes ? CourseOwnedFileRole.note.commonDirectoryName : CourseOwnedFileRole.material.commonDirectoryName, + isDirectory: true + ) + } + guard let destination else { + batch.stage = .reviewing + batch.destinationError = ui( + "目标文件夹当前不可用,请先重新连接资料库或课程文件夹。", + "The destination folder is unavailable. Reconnect the library or course folder first." + ) + confirmedFileImport = batch + return + } + + confirmedFileImportTask = Task { @MainActor [weak self] in + let plan = await Task.detached(priority: .userInitiated) { + Self.makeConfirmedFileImportPlan( + urls: urls, + destination: destination, + markdownOnly: asNotes, + successfulCopiesByOriginalName: successfulCopies + ) + }.value + guard let self, !Task.isCancelled, + var current = confirmedFileImport, + current.id == batchID else { return } + current.stage = .reviewing + current.candidates = plan.candidates + current.unsupportedNames = plan.unsupportedNames + current.failures = plan.unavailableSourceURLs.map { + ConfirmedFileImportFailure( + sourceURL: $0, + message: self.ui( + "文件已移动、删除或暂时无法访问。请恢复文件后重试。", + "The file was moved, deleted, or is temporarily unavailable. Restore it, then retry." + ) + ) + } + confirmedFileImportTask = nil + if current.candidates.isEmpty { + confirmedFileImport = current + if current.failures.isEmpty, current.pendingSourceURLs.isEmpty { + let feedback = confirmedImportCompletionFeedback(current) + dismissConfirmedFileImport() + if let feedback { showTransientNoteStatus(feedback) } + } else { + current.stage = .finished + confirmedFileImport = current + } + } else { + confirmedFileImport = current + } + } + } + + nonisolated static func makeConfirmedFileImportPlan( + urls: [URL], destination: URL, markdownOnly: Bool, + successfulCopiesByOriginalName: [String: [URL]] = [:] + ) -> ( + candidates: [ConfirmedFileImportCandidate], + unsupportedNames: [String], + unavailableSourceURLs: [URL] + ) { + let expansion = CourseProjectFileWorker.expandedImportSelection( + from: urls, + markdownOnly: markdownOnly + ) + let expanded = expansion.supported + let unsupported = expansion.unsupportedNames + var candidates: [ConfirmedFileImportCandidate] = [] + var reservedTargetNames = Set() + var reservedSourcesByOriginalName: [String: [URL]] = [:] + for url in expanded { + do { + switch try ImportFileCopy.collision(from: url, into: destination) { + case .available, .conflict: + break + case .duplicate: + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) + continue + } + } catch {} + let originalName = url.lastPathComponent + let duplicatesSuccessfulCopy = successfulCopiesByOriginalName[originalName, default: []] + .contains { copiedURL in + guard CourseProjectPathPolicy.isSame( + copiedURL.deletingLastPathComponent().resolvingSymlinksInPath(), + destination.resolvingSymlinksInPath() + ) else { return false } + return (try? ImportFileCopy.sourceHasIdenticalImportedContents(url, at: copiedURL)) == true + } + let duplicatesReservedSource = reservedSourcesByOriginalName[originalName, default: []] + .contains { reservedSource in + (try? ImportFileCopy.sourcesHaveIdenticalImportedContents( + reservedSource, + url + )) == true + } + if duplicatesSuccessfulCopy || duplicatesReservedSource { + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: .duplicate)) + continue + } + let targetName = nextConfirmedImportTargetName( + for: url, + in: destination, + reserved: reservedTargetNames + ) + let disposition: ConfirmedFileImportDisposition = targetName == url.lastPathComponent + ? .ready + : .conflict(suggestedFileName: targetName) + reservedTargetNames.insert(targetName) + reservedSourcesByOriginalName[originalName, default: []].append(url) + candidates.append(ConfirmedFileImportCandidate(sourceURL: url, disposition: disposition)) + } + return (candidates, unsupported.sorted(), expansion.unavailableSourceURLs) + } + + nonisolated private static func nextConfirmedImportTargetName( + for sourceURL: URL, + in directory: URL, + reserved: Set + ) -> String { + let preferred = sourceURL.lastPathComponent + if !reserved.contains(preferred), + !FileManager.default.fileExists(atPath: directory.appendingPathComponent(preferred).path) { + return preferred + } + let stem = sourceURL.deletingPathExtension().lastPathComponent + let pathExtension = sourceURL.pathExtension + for suffix in 2...9_999 { + let name = pathExtension.isEmpty + ? "\(stem) \(suffix)" + : "\(stem) \(suffix).\(pathExtension)" + if !reserved.contains(name), + !FileManager.default.fileExists(atPath: directory.appendingPathComponent(name).path) { + return name + } + } + return pathExtension.isEmpty + ? "\(stem) \(UUID().uuidString.lowercased())" + : "\(stem) \(UUID().uuidString.lowercased()).\(pathExtension)" + } + + private func revalidatedDuplicateDisposition( + _ sourceURL: URL, + batch: ConfirmedFileImportBatch, + successfulCopies: [URL] + ) async throws -> ConfirmedFileImportDisposition { + let destination: URL + if let courseID = batch.courseID { + guard let root = courseRootURL(for: courseID) else { + throw CocoaError(.fileNoSuchFile) + } + destination = root.appendingPathComponent( + batch.importsMarkdownAsNotes + ? CourseOwnedFileRole.note.directoryName + : CourseOwnedFileRole.material.directoryName, + isDirectory: true + ) + } else { + guard let root = courseLibraryRootURL else { + throw CocoaError(.fileNoSuchFile) + } + destination = root.appendingPathComponent( + batch.importsMarkdownAsNotes + ? CourseOwnedFileRole.note.commonDirectoryName + : CourseOwnedFileRole.material.commonDirectoryName, + isDirectory: true + ) + } + return try await Task.detached(priority: .userInitiated) { + () throws -> ConfirmedFileImportDisposition in + // A same-name representative may have been safely renamed by an + // earlier conflict. Compare its actual copy, never just its source. + for copiedURL in successfulCopies { + guard CourseProjectPathPolicy.isSame( + copiedURL.deletingLastPathComponent().resolvingSymlinksInPath(), + destination.resolvingSymlinksInPath() + ) else { continue } + if (try? ImportFileCopy.sourceHasIdenticalImportedContents( + sourceURL, + at: copiedURL + )) == true { + return .duplicate + } + } + let collision = try ImportFileCopy.collision(from: sourceURL, into: destination) + switch collision { + case .available: return .ready + case .duplicate: return .duplicate + case .conflict(let suggested): return .conflict(suggestedFileName: suggested) + } + }.value + } + + private func importConfirmedFile( + _ candidate: ConfirmedFileImportCandidate, + batch: ConfirmedFileImportBatch + ) async throws -> StudyItem { + if let courseID = batch.courseID { + let resolution: CourseFileConflictResolution + switch candidate.disposition { + case .conflict(let suggested): + resolution = .keepBoth(preferredFileName: suggested) + case .ready, .duplicate: + resolution = .cancel + } + return try await importFileIntoCourse( + candidate.sourceURL, + courseID: courseID, + role: batch.importsMarkdownAsNotes ? .note : .material, + conflictResolution: resolution + ).item + } + + guard let root = courseLibraryRootURL else { + throw CocoaError(.fileNoSuchFile) + } + let copiedURL = try await copyExternalFileIntoLibrary( + root: root, + sourceURL: candidate.sourceURL, + isNote: batch.importsMarkdownAsNotes + ) + guard let item = applyImportedCommonFiles( + [(copiedURL, batch.importsMarkdownAsNotes)], + selectsFirstImportedItem: false, + reclassifiesExistingMarkdown: false + ).first else { + throw CocoaError(.fileWriteUnknown) + } + return item + } + + private func confirmedImportFailureMessage(_ error: Error) -> String { + let cocoaCode = (error as? CocoaError)?.code + if cocoaCode == .fileNoSuchFile || cocoaCode == .fileReadNoSuchFile { + return ui( + "文件已移动、删除或暂时无法访问。请恢复文件后重试。", + "The file was moved, deleted, or is temporarily unavailable. Restore it, then retry." + ) + } + if cocoaCode == .fileReadNoPermission || cocoaCode == .fileWriteNoPermission { + return ui( + "没有读取来源或写入目标的权限。请重新选择可访问的文件夹后重试。", + "WeiBei cannot read the source or write to the destination. Re-select an accessible folder, then retry." + ) + } + return ui( + "复制或登记没有完成,原文件仍保留。请检查文件与目标文件夹后重试。", + "Copying or registration did not finish. The original is still kept. Check the file and destination, then retry." + ) + } + + private func recoverConfirmedCourseImport( + _ candidate: ConfirmedFileImportCandidate, + batch: ConfirmedFileImportBatch + ) async -> StudyItem? { + guard case .ready = candidate.disposition, + let courseID = batch.courseID, + let root = courseRootURL(for: courseID) else { return nil } + let role: CourseOwnedFileRole = batch.importsMarkdownAsNotes ? .note : .material + let directory = root.appendingPathComponent(role.directoryName, isDirectory: true) + guard (try? ImportFileCopy.collision( + from: candidate.sourceURL, + into: directory + )) == .duplicate else { return nil } + _ = await reconcileCourseFilesNow(courseID: courseID) + let expectedStorage = StudyItemStorage.courseOwned( + ownerCourseID: courseID, + relativePath: "\(role.directoryName)/\(candidate.sourceURL.lastPathComponent)" + ) + return importedItems.first { $0.storage == expectedStorage } + } +} + +struct ConfirmedFileImportView: View { + @EnvironmentObject private var store: WorkspaceStore + @State private var creatingCourse = false + + private static let bodyWidth: CGFloat = 396 + private static let maximumBodyHeight: CGFloat = 300 + + private var batch: ConfirmedFileImportBatch? { store.confirmedFileImport } + + var body: some View { + VStack(alignment: .leading, spacing: 0) { + if let batch { + ConfirmedImportCappedBodyLayout( + width: Self.bodyWidth, + maximumHeight: Self.maximumBodyHeight + ) { + stageContent(batch) + .frame(width: Self.bodyWidth, alignment: .leading) + .fixedSize(horizontal: false, vertical: true) + .hidden() + .allowsHitTesting(false) + .accessibilityHidden(true) + ScrollView { + stageContent(batch) + .frame(width: Self.bodyWidth, alignment: .leading) + } + .scrollBounceBehavior(.basedOnSize) + } + .clipped() + .padding(.horizontal, 22) + .padding(.top, 22) + footer(batch) + .padding(.horizontal, 22) + .padding(.top, 12) + .padding(.bottom, 22) + } + } + .frame(width: 440, alignment: .topLeading) + .fixedSize(horizontal: false, vertical: true) +#if targetEnvironment(macCatalyst) + .modifier(CatalystIndependentSheetFitting(color: WeiBeiNativePalette.paper())) +#endif + .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) + .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) + .foregroundStyle(WeiBeiTheme.ink) + .preferredColorScheme(store.appearanceMode.colorScheme) + .modifier(WeiBeiFittedSheetPresentation()) + .interactiveDismissDisabled(batch?.stage == .importing) + .sheet(isPresented: $creatingCourse) { + CourseProjectEntrySheet( + cancel: { creatingCourse = false }, + openCourse: { courseID in + creatingCourse = false + store.selectNewCourseForConfirmedFileImport(courseID) + }, + allowsInitialImport: false + ) + .environmentObject(store) + } + } + + @ViewBuilder + private func stageContent(_ batch: ConfirmedFileImportBatch) -> some View { + switch batch.stage { + case .preparing: + HStack(spacing: 10) { + ProgressView().controlSize(.small) + Text(store.ui("正在核对文件与目标…", "Checking files and destination…")) + .weiBeiText(13) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + .frame(maxWidth: .infinity, alignment: .leading) + case .reviewing: + review(batch) + case .importing: + progress(batch) + case .finished: + result(batch) + } + } + + @ViewBuilder + private func footer(_ batch: ConfirmedFileImportBatch) -> some View { + HStack(spacing: 8) { + Spacer(minLength: 0) + switch batch.stage { + case .preparing: + Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + .keyboardShortcut(.cancelAction) + case .reviewing: + Button(store.ui("取消", "Cancel")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + .keyboardShortcut(.cancelAction) + Button(store.ui("导入", "Import")) { store.confirmFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + .disabled(batch.confirmableCount == 0 || batch.destinationError != nil) + case .importing: + Button(store.ui("停止剩余导入", "Stop Remaining")) { + store.stopConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + case .finished: + ViewThatFits(in: .horizontal) { + HStack(spacing: 8) { resultButtons(batch) } + VStack(alignment: .trailing, spacing: 8) { resultButtons(batch) } + } + } + } + } + + private func review(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 14) { + fileSummary(batch) + destinationPicker(batch) + if let error = batch.destinationError { + Label(error, systemImage: "exclamationmark.triangle") + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.cinnabar) + .fixedSize(horizontal: false, vertical: true) + } + } + } + + private func fileSummary(_ batch: ConfirmedFileImportBatch) -> some View { + let fileCount = batch.candidates.count + batch.unsupportedNames.count + batch.failures.count + return VStack(alignment: .leading, spacing: 8) { + if !batch.sourceFolderNames.isEmpty { + Text(store.ui( + "可导入文稿 · \(batch.candidates.count)个", + "Importable documents · \(batch.candidates.count)" + )) + .weiBeiText(12, weight: .semibold) + } else if fileCount > 1 { + Text(store.ui("\(fileCount)个文件", "\(fileCount) files")) + .weiBeiText(12, weight: .semibold) + } + VStack(alignment: .leading, spacing: 0) { + ForEach(Array(batch.candidates.enumerated()), id: \.element.id) { index, candidate in + if index > 0 { Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) } + candidateRow(candidate) + } + ForEach(Array(batch.unsupportedNames.enumerated()), id: \.offset) { index, name in + if !batch.candidates.isEmpty || index > 0 { + Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) + } + unsupportedRow(name, asNotes: batch.importsMarkdownAsNotes) + } + ForEach(Array(batch.failures.enumerated()), id: \.element.id) { index, failure in + if !batch.candidates.isEmpty || !batch.unsupportedNames.isEmpty || index > 0 { + Divider().overlay(WeiBeiTheme.hairline.opacity(0.30)) + } + unavailableSourceRow(failure) + } + } + } + } + + private func candidateRow(_ candidate: ConfirmedFileImportCandidate) -> some View { + let kind = StudyItemKind.detect(from: candidate.sourceURL) + return HStack(alignment: .top, spacing: 10) { + Image(systemName: kind.systemImage) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .frame(width: 16) + .padding(.top, 2) + VStack(alignment: .leading, spacing: 3) { + Text(candidate.sourceURL.lastPathComponent) + .weiBeiText(13) + .lineLimit(2) + .truncationMode(.middle) + if candidate.disposition != .ready { + Text(candidateLabel(candidate)) + .weiBeiText(12, weight: .medium) + .foregroundStyle(candidateColor(candidate)) + .fixedSize(horizontal: false, vertical: true) + } + } + } + .padding(.vertical, 6) + .help(candidate.sourceURL.lastPathComponent) + } + + private func unsupportedRow(_ name: String, asNotes: Bool) -> some View { + HStack(alignment: .top, spacing: 10) { + Image(systemName: "nosign") + .frame(width: 16) + VStack(alignment: .leading, spacing: 3) { + Text(name) + .weiBeiText(13) + .lineLimit(2) + .truncationMode(.middle) + Text( + asNotes + ? store.ui("仅支持 Markdown", "Markdown only") + : store.ui("格式不支持", "Unsupported format") + ) + .weiBeiText(12, weight: .medium) + } + } + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.vertical, 6) + .help(name) + } + + private func unavailableSourceRow(_ failure: ConfirmedFileImportFailure) -> some View { + HStack(alignment: .top, spacing: 10) { + Image(systemName: "exclamationmark.triangle") + .frame(width: 16) + VStack(alignment: .leading, spacing: 3) { + Text(failure.sourceURL.lastPathComponent) + .weiBeiText(13) + .lineLimit(2) + .truncationMode(.middle) + Text(failure.message) + .weiBeiText(12, weight: .medium) + .fixedSize(horizontal: false, vertical: true) + } + } + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.vertical, 6) + .help(failure.sourceURL.lastPathComponent) + } + + private func destinationPicker(_ batch: ConfirmedFileImportBatch) -> some View { + HStack(spacing: 12) { + Text(store.ui("导入到", "Import to")) + .weiBeiText(12, weight: .semibold) + Spacer(minLength: 0) + Menu { + Button { + store.setConfirmedFileImportDestination(courseID: nil) + } label: { + if batch.courseID == nil { + Label(commonDestinationTitle(batch), systemImage: "checkmark") + } else { + Text(commonDestinationTitle(batch)) + } + } + ForEach(store.courses) { course in + Button { + store.setConfirmedFileImportDestination(courseID: course.id) + } label: { + if batch.courseID == course.id { + Label(course.title, systemImage: "checkmark") + } else { + Text(course.title) + } + } + } + Divider() + Button(store.ui("新建课程…", "Create Course…")) { creatingCourse = true } + } label: { + HStack(spacing: 6) { + Text(destinationTitle(batch)) + .weiBeiText(13) + .lineLimit(1) + .truncationMode(.tail) + Image(systemName: "chevron.down") + .weiBeiText(12, weight: .semibold) + } + .foregroundStyle(WeiBeiTheme.ink) + .padding(.horizontal, 10) + .frame(height: 30) + .weibeiEtchedBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.52), + stroke: WeiBeiTheme.hairline.opacity(0.3), + cornerRadius: 8 + ) + } + .menuStyle(.borderlessButton) + .menuIndicator(.hidden) + } + } + + private func progress(_ batch: ConfirmedFileImportBatch) -> some View { + VStack(alignment: .leading, spacing: 12) { + if let current = batch.currentFileName { + Text(current).weiBeiText(13).lineLimit(2) + } + ProgressView(value: Double(batch.completed), total: Double(max(1, batch.total))) + .tint(WeiBeiTheme.cinnabar) + Text("\(batch.completed) / \(batch.total)") + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + } + } + + private func result(_ batch: ConfirmedFileImportBatch) -> some View { + let commonFailureMessage = sharedFailureMessage(batch) + return VStack(alignment: .leading, spacing: 14) { + Text(resultSummary(batch)) + .weiBeiText(13, weight: .semibold) + if batch.stopped, !batch.pendingSourceURLs.isEmpty { + Text(store.ui( + "已停止;\(batch.pendingSourceURLs.count) 个文件未处理。已完成的导入已保留,原文件未变。", + "Stopped with \(batch.pendingSourceURLs.count) file(s) unprocessed. Completed imports were kept and originals are unchanged." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } else if batch.stopped { + Text(store.ui( + "已停止;已完成的导入仍然保留。", + "Stopped. Completed imports were kept." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } else if !batch.pendingSourceURLs.isEmpty { + Text(store.ui( + "另有 \(batch.pendingSourceURLs.count) 个文件尚未处理,原文件仍保留。", + "\(batch.pendingSourceURLs.count) file(s) are still waiting; their originals are unchanged." + )) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } + if !batch.failures.isEmpty { + VStack(alignment: .leading, spacing: 8) { + if let message = commonFailureMessage { + Text(message) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } + ForEach(batch.failures) { failure in + VStack(alignment: .leading, spacing: 3) { + Text(failure.sourceURL.lastPathComponent) + .weiBeiText(13, weight: .semibold) + .lineLimit(2) + .truncationMode(.middle) + if commonFailureMessage == nil { + Text(failure.message) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } + } + } + } + } + } + } + + @ViewBuilder + private func resultButtons(_ batch: ConfirmedFileImportBatch) -> some View { + if !batch.pendingSourceURLs.isEmpty { + Button(store.ui("结束", "End")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + if batch.failures.isEmpty { + Button(store.ui( + "继续处理(\(batch.pendingSourceURLs.count))", + "Continue (\(batch.pendingSourceURLs.count))" + )) { + store.continuePendingConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else { + Button(store.ui( + "放弃失败项,继续(\(batch.pendingSourceURLs.count))", + "Leave Failures, Continue (\(batch.pendingSourceURLs.count))" + )) { + store.continuePendingConfirmedFileImport(abandoningFailures: true) + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("重试失败项", "Retry Failed")) { + store.retryFailedConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } + } else if !batch.failures.isEmpty { + Button(store.ui("关闭", "Close")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) + Button(store.ui("重试失败项", "Retry Failed")) { + store.retryFailedConfirmedFileImport() + } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } else { + Button(store.ui("关闭", "Close")) { store.dismissConfirmedFileImport() } + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) + .keyboardShortcut(.defaultAction) + } + } + + private func resultSummary(_ batch: ConfirmedFileImportBatch) -> String { + var chinese: [String] = [] + var english: [String] = [] + if !batch.importedItems.isEmpty { + chinese.append("\(batch.importedItems.count)个已导入") + english.append("\(batch.importedItems.count) imported") + } + if batch.duplicateCount > 0 { + chinese.append("\(batch.duplicateCount)个已存在") + english.append("\(batch.duplicateCount) already existed") + } + if batch.unsupportedCount > 0 { + chinese.append("\(batch.unsupportedCount)个格式不支持") + english.append("\(batch.unsupportedCount) unsupported") + } + if !batch.failures.isEmpty { + chinese.append("\(batch.failures.count)个失败") + english.append("\(batch.failures.count) failed") + } + if chinese.isEmpty { + return store.ui("没有导入文件", "No files imported") + } + return store.ui(chinese.joined(separator: " · "), english.joined(separator: " · ")) + } + + private func sharedFailureMessage(_ batch: ConfirmedFileImportBatch) -> String? { + guard let message = batch.failures.first?.message, + batch.failures.allSatisfy({ $0.message == message }) else { return nil } + return message + } + + private func commonDestinationTitle(_ batch: ConfirmedFileImportBatch) -> String { + batch.importsMarkdownAsNotes + ? store.ui("通用笔记", "Common Notes") + : store.ui("通用资料", "Common Materials") + } + + private func destinationTitle(_ batch: ConfirmedFileImportBatch) -> String { + guard let courseID = batch.courseID else { return commonDestinationTitle(batch) } + return store.courses.first(where: { $0.id == courseID })?.title + ?? store.ui("选择课程", "Choose Course") + } + + private func candidateLabel(_ candidate: ConfirmedFileImportCandidate) -> String { + switch candidate.disposition { + case .ready: return store.ui("可导入", "Ready") + case .duplicate: return store.ui("已存在", "Already exists") + case .conflict(let name): return store.ui("同名,另存为 \(name)", "Name conflict, save as \(name)") + } + } + + private func candidateColor(_ candidate: ConfirmedFileImportCandidate) -> Color { + switch candidate.disposition { + case .ready: WeiBeiTheme.secondaryInk + case .duplicate: WeiBeiTheme.tertiaryInk + case .conflict: WeiBeiTheme.cinnabar + } + } + +} + +private struct ConfirmedImportCappedBodyLayout: Layout { + let width: CGFloat + let maximumHeight: CGFloat + + func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize { + guard let measurement = subviews.first else { return .zero } + let contentHeight = measurement.sizeThatFits( + ProposedViewSize(width: width, height: nil) + ).height + return CGSize(width: width, height: min(maximumHeight, max(1, ceil(contentHeight)))) + } + + func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) { + guard subviews.count == 2 else { return } + subviews[0].place( + at: bounds.origin, + anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: nil) + ) + subviews[1].place( + at: bounds.origin, + anchor: .topLeading, + proposal: ProposedViewSize(width: width, height: bounds.height) + ) + } +} diff --git a/Sources/WeiBei/Views/ContentView.swift b/Sources/WeiBei/Views/ContentView.swift index 1801c04b3..ceafa5c5d 100644 --- a/Sources/WeiBei/Views/ContentView.swift +++ b/Sources/WeiBei/Views/ContentView.swift @@ -16,6 +16,7 @@ struct ContentView: View { @FocusState private var topSearchFocused: Bool @State private var floatingAgentExpanded = false @State private var windowIsFullScreen = false + @State private var isFileDropTargeted = false /// Size of the document area under the top bar. The float uses it for placement /// and must not measure that area with a GeometryReader laid over the reader. @State private var documentCanvas = CGSize.zero @@ -99,9 +100,14 @@ struct ContentView: View { } } } - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + .onDrop(of: [.fileURL], isTargeted: $isFileDropTargeted) { providers in WeiBeiDroppedFileURLs.load(providers) { urls in - store.importFiles(urls) + store.prepareConfirmedFileImport(urls) + } + } + .overlay { + if isFileDropTargeted { + WeiBeiFileDropPrompt() } } .allowsHitTesting(!store.courseWorkspacePresented) @@ -174,6 +180,12 @@ struct ContentView: View { ExcerptBookView(courseID: store.excerptBookCourseID) .environmentObject(store) } + .sheet(isPresented: Binding( + get: { store.confirmedFileImport != nil }, + set: { if !$0 { store.dismissConfirmedFileImport() } } + )) { + ConfirmedFileImportView().environmentObject(store) + } .background(WindowFullScreenReader(isFullScreen: $windowIsFullScreen)) .background { // Focus / reader-search sync observes paneState so ContentView does not. @@ -200,6 +212,24 @@ struct ContentView: View { } } +private struct WeiBeiFileDropPrompt: View { + @EnvironmentObject private var store: WorkspaceStore + + var body: some View { + Label(store.ui("松开以导入资料", "Drop to import"), systemImage: "tray.and.arrow.down") + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) + } +} + #if !targetEnvironment(macCatalyst) private struct WindowFullScreenReader: NSViewRepresentable { @Binding var isFullScreen: Bool diff --git a/Sources/WeiBei/Views/ContextualContentPicker.swift b/Sources/WeiBei/Views/ContextualContentPicker.swift index ceb50eaf0..8e000c5d1 100644 --- a/Sources/WeiBei/Views/ContextualContentPicker.swift +++ b/Sources/WeiBei/Views/ContextualContentPicker.swift @@ -6,8 +6,6 @@ struct ContextualContentPicker: View { @Environment(\.weibeiReduceMotion) private var reduceMotion let kind: ContextualContentKind @State private var courseEntry: CourseProjectEntryPresentation? - @State private var choosingImportTarget = false - @State private var pendingImport: (() -> Void)? @State private var search = "" @State private var searchFocused = false @@ -83,38 +81,6 @@ struct ContextualContentPicker: View { openCourse: { _ in courseEntry = nil } ).environmentObject(store) } - .sheet(isPresented: $choosingImportTarget, onDismiss: { - let action = pendingImport - pendingImport = nil - action?() - }) { - VStack(alignment: .leading, spacing: 16) { - Text(store.ui("导入到哪里?", "Import into…")).weiBeiText(17, weight: .semibold) - ScrollView { - VStack(alignment: .leading, spacing: 4) { - importTargetButton(commonTitle, symbol: "tray", courseID: nil) - ForEach(store.courses) { course in - importTargetButton(course.title, symbol: "folder", courseID: course.id) - } - }.frame(maxWidth: .infinity, alignment: .leading) - }.frame(maxHeight: 300) - HStack { - Spacer() - Button(store.ui("取消", "Cancel")) { choosingImportTarget = false } - .buttonStyle(WeiBeiDialogButtonStyle()) - .keyboardShortcut(.cancelAction) - } - } - .padding(24) - .frame(minWidth: 320, idealWidth: 400, maxWidth: .infinity) -#if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) -#endif - .background(WeiBeiGlassForegroundSheet(mode: store.appearanceMode)) - .background(WeiBeiThemeBackdrop(mode: store.appearanceMode)) - .foregroundStyle(WeiBeiTheme.ink) - .preferredColorScheme(store.appearanceMode.colorScheme) - } .accessibilityIdentifier(kind == .note ? "contextual-note-picker" : "contextual-material-picker") } @@ -122,21 +88,6 @@ struct ContextualContentPicker: View { kind == .note ? store.ui("通用笔记", "Common Notes") : store.ui("通用资料", "Common Materials") } - private func importTargetButton(_ title: String, symbol: String, courseID: UUID?) -> some View { - Button { importFiles(into: courseID) } label: { - HStack(spacing: 10) { - Label(title, systemImage: symbol) - .lineLimit(2) - .multilineTextAlignment(.leading) - Spacer(minLength: 8) - Image(systemName: "chevron.right").weiBeiText(10) - } - .frame(maxWidth: .infinity, alignment: .leading) - } - .buttonStyle(WeiBeiTextActionButtonStyle(fontSize: 13, height: 36)) - .help(title) - } - private func courseBlock(_ group: Group) -> some View { VStack(alignment: .leading, spacing: 12) { HStack(alignment: .firstTextBaseline, spacing: 8) { @@ -206,11 +157,7 @@ struct ContextualContentPicker: View { } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) Button(kind == .note ? store.ui("导入笔记…", "Import Notes…") : store.ui("导入资料…", "Import Materials…")) { - if store.courses.isEmpty { - importFiles(into: nil) - } else { - choosingImportTarget = true - } + importFiles(into: nil) } .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) } @@ -219,16 +166,8 @@ struct ContextualContentPicker: View { } private func importFiles(into courseID: UUID?) { - let action = { [store, kind] in - if kind == .note { store.importCourseNotesFromPanel(courseID: courseID) } - else { store.importCourseMaterialsFromPanel(courseID: courseID) } - } - if choosingImportTarget { - pendingImport = action - choosingImportTarget = false - } else { - action() - } + if kind == .note { store.importCourseNotesFromPanel(courseID: courseID) } + else { store.importCourseMaterialsFromPanel(courseID: courseID) } } } diff --git a/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift b/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift index 05c5d4304..b4fe71d55 100644 --- a/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift +++ b/Sources/WeiBei/Views/CourseDocNoteWorkspaceView.swift @@ -306,6 +306,11 @@ struct CourseDocNoteWorkspaceView: View { select(item, kind: kind) } } + .background( + store.recentlyImportedItemIDs.contains(item.id) + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : Color.clear + ) } @ViewBuilder diff --git a/Sources/WeiBei/Views/CourseHubView.swift b/Sources/WeiBei/Views/CourseHubView.swift index 3f1365479..b76506bc7 100644 --- a/Sources/WeiBei/Views/CourseHubView.swift +++ b/Sources/WeiBei/Views/CourseHubView.swift @@ -1,6 +1,5 @@ import Foundation import SwiftUI -import UniformTypeIdentifiers import WeiBeiCore /// A quiet course landing page: resume reading first, then browse recent course content. @@ -326,6 +325,26 @@ struct CourseHubView: View { .onDrop(of: [.fileURL], isTargeted: $isMaterialDropTargeted) { providers in handleDrop(providers, asNotes: false) } + .overlay { + if isMaterialDropTargeted || isNoteDropTargeted { + Label( + isNoteDropTargeted + ? store.ui("松开以导入笔记", "Drop to import notes") + : store.ui("松开以导入资料", "Drop to import"), + systemImage: "tray.and.arrow.down" + ) + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) + } + } } @ViewBuilder @@ -506,6 +525,7 @@ struct CourseHubView: View { noteID: selectedNoteID, sessionID: selectedSessionID ), + highlighted: entry.itemID.map(store.recentlyImportedItemIDs.contains) ?? false, action: { open(entry) } ) @@ -757,50 +777,10 @@ struct CourseHubView: View { private func handleDrop(_ providers: [NSItemProvider], asNotes: Bool) -> Bool { guard let courseID else { return false } - var urls: [URL] = [] - let urlsLock = NSLock() - let group = DispatchGroup() - - for provider in providers { - group.enter() - provider.loadItem( - forTypeIdentifier: UTType.fileURL.identifier, - options: nil - ) { item, _ in - defer { group.leave() } - let url: URL? - if let data = item as? Data { - url = URL(dataRepresentation: data, relativeTo: nil) - } else { - url = item as? URL - } - guard let url else { return } - urlsLock.lock() - urls.append(url) - urlsLock.unlock() - } - } - - group.notify(queue: .main) { - guard !urls.isEmpty, - store.courseWorkspaceCourseID == courseID else { - return - } - store.importCourseFilesFromURLs( - urls, - asNotes: asNotes, - courseID: courseID - ) { imported in - if asNotes { - selectedNoteID = selectedNoteID - ?? imported.first(where: \.isNotebookNote)?.id - } else { - selectedMaterialID = selectedMaterialID - ?? imported.first(where: \.isCourseMaterial)?.id - } - } + return WeiBeiDroppedFileURLs.load(providers) { urls in + guard store.courseWorkspaceCourseID == courseID else { return } + store.prepareConfirmedFileImport(urls, courseID: courseID, asNotes: asNotes) } - return true } // MARK: - Display helpers @@ -916,6 +896,13 @@ private struct CourseHomeEntry: Identifiable { let detail: String let date: Date + var itemID: String? { + switch kind { + case .material(let item), .note(let item): item.id + case .chat: nil + } + } + func isSelected( materialID: String?, noteID: String?, @@ -1066,6 +1053,7 @@ private struct CourseHubContentRow: View { var snippet: String? = nil var courseBadge: String? = nil let selected: Bool + var highlighted = false let action: () -> Void @State private var hovering = false @@ -1124,7 +1112,9 @@ private struct CourseHubContentRow: View { .frame(minHeight: snippet == nil ? 58 : 72) .contentShape(Rectangle()) .background( - selected + highlighted + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : selected ? WeiBeiTheme.paperInset.opacity(0.34) : (hovering ? WeiBeiTheme.paperInset.opacity(0.16) : .clear) ) diff --git a/Sources/WeiBei/Views/CourseSidebarModel.swift b/Sources/WeiBei/Views/CourseSidebarModel.swift index ea171fbca..09ddc5c31 100644 --- a/Sources/WeiBei/Views/CourseSidebarModel.swift +++ b/Sources/WeiBei/Views/CourseSidebarModel.swift @@ -94,6 +94,9 @@ final class CourseSidebarModel: ObservableObject { var unassignedMaterials: [CourseSidebarItemRow] { projection.unassignedMaterials } var unassignedNotes: [CourseSidebarItemRow] { projection.unassignedNotes } var searchTagTaskID: String { "\(tagInputGeneration):\(query)" } + var recentlyImportedItemIDs: Set { + store?.recentlyImportedItemIDs ?? [] + } init(store: WorkspaceStore) { interfaceLanguage = store.interfaceLanguage @@ -155,6 +158,15 @@ final class CourseSidebarModel: ObservableObject { store.$notebookRenameDraft.dropFirst().sink { [weak self] draft in self?.notebookRenameDraft = draft }.store(in: &subscriptions) + store.$recentlyImportedItemIDs.dropFirst().sink { [weak self] itemIDs in + guard let self else { return } + if !itemIDs.isEmpty, + !self.query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { + self.updateQuery("") + } else { + self.objectWillChange.send() + } + }.store(in: &subscriptions) store.$interfaceLanguage.dropFirst().sink { [weak self] language in self?.interfaceLanguage = language self?.scheduleRebuild() @@ -265,6 +277,23 @@ final class CourseSidebarModel: ObservableObject { scheduleRebuild() } + func firstVisibleItemID(in itemIDs: Set) -> String? { + guard !itemIDs.isEmpty else { return nil } + if let activeCourseID, + let activeCourse = projection.courses.first(where: { $0.id == activeCourseID }) { + if let material = activeCourse.materials.first(where: { itemIDs.contains($0.id) }) { + return material.id + } + if let note = activeCourse.notes.first(where: { itemIDs.contains($0.id) }) { + return note.id + } + } + if let material = projection.unassignedMaterials.first(where: { itemIDs.contains($0.id) }) { + return material.id + } + return projection.unassignedNotes.first(where: { itemIDs.contains($0.id) })?.id + } + func handleEscape(dismiss: () -> Void) { guard !query.isEmpty else { dismiss() diff --git a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift index 2b6a2c41e..00162c08e 100644 --- a/Sources/WeiBei/Views/CourseWorkspaceComponents.swift +++ b/Sources/WeiBei/Views/CourseWorkspaceComponents.swift @@ -190,7 +190,7 @@ struct CourseManagementSheet: View { .padding(22) .frame(width: 460) #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) + .background(CatalystIndependentSheetSizingProbe(color: WeiBeiNativePalette.paper())) #endif .background(WeiBeiTheme.paper) .foregroundStyle(WeiBeiTheme.ink) @@ -300,6 +300,7 @@ struct CourseProjectEntrySheet: View { @EnvironmentObject private var store: WorkspaceStore let cancel: () -> Void let openCourse: (UUID) -> Void + let allowsInitialImport: Bool @State private var intent: CourseProjectEntryIntent @State private var title = "" @@ -314,11 +315,13 @@ struct CourseProjectEntrySheet: View { init( initialIntent: CourseProjectEntryIntent = .create, cancel: @escaping () -> Void, - openCourse: @escaping (UUID) -> Void + openCourse: @escaping (UUID) -> Void, + allowsInitialImport: Bool = true ) { _intent = State(initialValue: initialIntent) self.cancel = cancel self.openCourse = openCourse + self.allowsInitialImport = allowsInitialImport } private var needsLibrary: Bool { @@ -335,28 +338,34 @@ struct CourseProjectEntrySheet: View { title.trimmingCharacters(in: .whitespacesAndNewlines) } + private var selectedImportIncludesMarkdown: Bool { + selectedImportURLs.contains { StudyItemKind.detect(from: $0) == .markdown } + } + var body: some View { - VStack(alignment: .leading, spacing: 18) { - VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 14) { + VStack(alignment: .leading, spacing: 5) { Text(heading) - .weiBeiBrandFont(language: store.interfaceLanguage, size: 22, weight: .semibold) - Text(detail) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) + .weiBeiBrandFont(language: store.interfaceLanguage, size: 20, weight: .semibold) + if let detail { + Text(detail) + .weiBeiText(12) + .foregroundStyle(WeiBeiTheme.secondaryInk) + .fixedSize(horizontal: false, vertical: true) + } } if needsLibrary { libraryPicker } else { courseTitleField - if let libraryPath = store.courseLibraryRootURL?.path { + if intent == .adopt, let libraryPath = store.courseLibraryRootURL?.path { pathLine( label: store.ui("魏碑资料库", "WeiBei Library"), path: libraryPath ) } - if intent == .create { + if intent == .create && allowsInitialImport { importPicker } } @@ -375,9 +384,11 @@ struct CourseProjectEntrySheet: View { actionBar } .padding(22) - .frame(width: 460) + .frame(width: 440) + .fixedSize(horizontal: false, vertical: true) + .modifier(WeiBeiFittedSheetPresentation()) #if targetEnvironment(macCatalyst) - .background(CatalystSheetBackground(color: WeiBeiNativePalette.paper())) + .modifier(CatalystIndependentSheetFitting(color: WeiBeiNativePalette.paper())) #endif .background(WeiBeiTheme.paper) .foregroundStyle(WeiBeiTheme.ink) @@ -407,7 +418,7 @@ struct CourseProjectEntrySheet: View { } } - private var detail: String { + private var detail: String? { if rebindProposal != nil { return store.ui( "魏碑认出了同一门课程,原文件夹当前无法访问。确认后会重新连接所选文件夹,读取其中的课程状态并扫描实际资料;本机未落盘草稿会保留。", @@ -417,8 +428,8 @@ struct CourseProjectEntrySheet: View { if needsLibrary { if libraryNeedsReauthorization { return store.ui( - "魏碑记得原资料库,但当前无法访问。重新选择后魏碑会改用所选文件夹,课程文件不会被移动;要找回原课程,请选回原来的资料库。", - "WeiBei remembers the library but cannot access it. Re-selecting switches WeiBei to the chosen folder without moving any course files; to find your original courses, pick the original library." + "原资料库无法访问。选回原文件夹可恢复课程;选择其他文件夹会切换资料库,不移动文件。", + "The original library is unavailable. Choose it again to restore courses, or choose another folder to switch libraries without moving files." ) } return store.ui( @@ -428,10 +439,7 @@ struct CourseProjectEntrySheet: View { } switch intent { case .create: - return store.ui( - "魏碑会为这门课创建文稿、笔记和课程记录。对话始终是全局的,进入这门课只会把它设为当前课程。", - "WeiBei will create documents, notes, and a course record. Chats stay global; entering this course only makes it the current course." - ) + return nil case .adopt: return store.ui( "原地登记一个已有文件夹为课程;不会复制、移动或重排其中的可见内容。", @@ -449,23 +457,6 @@ struct CourseProjectEntrySheet: View { path: path ) } - Label( - store.ui( - "原资料库当前无法访问,课程记录仍保留。选择别的文件夹会改用那个文件夹,课程文件不会被移动。", - "The original library is currently unavailable, but course records are preserved. Choosing another folder switches to that folder; course files are not moved." - ), - systemImage: "exclamationmark.triangle" - ) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) - .fixedSize(horizontal: false, vertical: true) - } else { - Label( - store.ui("建议选择或新建一个名为“魏碑”的总文件夹。", "Choose or create a top-level WeiBei folder."), - systemImage: "folder" - ) - .weiBeiText(12) - .foregroundStyle(WeiBeiTheme.secondaryInk) } Button( @@ -537,7 +528,7 @@ struct CourseProjectEntrySheet: View { VStack(alignment: .leading, spacing: 8) { Button( selectedImportURLs.isEmpty - ? store.ui("同时选择现有文稿或文件夹…", "Choose Existing Files or Folder…") + ? store.ui("添加初始资料…", "Add Initial Materials…") : store.ui("重新选择导入内容…", "Choose Different Content…"), action: chooseImportContent ) @@ -545,10 +536,15 @@ struct CourseProjectEntrySheet: View { .disabled(isWorking) if !selectedImportURLs.isEmpty { - Text(store.ui( - "已选择 \(selectedImportURLs.count) 项;课程创建后会直接导入。Markdown 会同时出现在文稿与笔记中。", - "Selected \(selectedImportURLs.count) item(s). Markdown will appear in both Materials and Notes." - )) + Text(selectedImportIncludesMarkdown + ? store.ui( + "已选 \(selectedImportURLs.count) 项;Markdown 作为课程文稿导入。", + "\(selectedImportURLs.count) selected; Markdown will be imported as course materials." + ) + : store.ui( + "已选 \(selectedImportURLs.count) 项", + "\(selectedImportURLs.count) selected" + )) .weiBeiText(12) .foregroundStyle(WeiBeiTheme.secondaryInk) .fixedSize(horizontal: false, vertical: true) @@ -566,7 +562,7 @@ struct CourseProjectEntrySheet: View { private func pathLine(label: String, path: String) -> some View { VStack(alignment: .leading, spacing: 4) { Text(label) - .weiBeiText(10.5, weight: .semibold) + .weiBeiText(12, weight: .semibold) .foregroundStyle(WeiBeiTheme.tertiaryInk) Text(path) .weiBeiText(12) @@ -594,7 +590,7 @@ struct CourseProjectEntrySheet: View { selectedFolder = nil errorMessage = nil } - .buttonStyle(WeiBeiTextActionButtonStyle()) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) .disabled(isWorking) } @@ -607,7 +603,7 @@ struct CourseProjectEntrySheet: View { } Button(store.ui("取消", "Cancel"), action: cancel) - .buttonStyle(WeiBeiTextActionButtonStyle()) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .secondary)) .keyboardShortcut(.cancelAction) .disabled(isWorking) @@ -619,9 +615,7 @@ struct CourseProjectEntrySheet: View { ), action: confirmRebind ) - .buttonStyle( - WeiBeiTextActionButtonStyle(active: true) - ) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) .disabled(isWorking) } else if !needsLibrary { @@ -631,7 +625,7 @@ struct CourseProjectEntrySheet: View { : store.ui("创建并导入", "Create and Import"), action: createCourse ) - .buttonStyle(WeiBeiTextActionButtonStyle(active: true)) + .buttonStyle(WeiBeiDialogButtonStyle(prominence: .primary)) .keyboardShortcut(.defaultAction) .disabled(cleanedTitle.isEmpty || isWorking) } @@ -722,8 +716,8 @@ struct CourseProjectEntrySheet: View { let panel = NSOpenPanel() panel.title = store.ui("选择课程内容", "Choose Course Content") panel.message = store.ui( - "可以选择多个文件或一个文件夹。Markdown 会作为同一个文件同时用于阅读和笔记。", - "Choose files or a folder. Markdown stays one file and appears in both reading and notes." + "可以选择多个文件或一个文件夹。Markdown 作为课程文稿导入。", + "Choose files or a folder. Markdown will be imported as course materials." ) panel.prompt = store.ui("选择", "Choose") panel.allowsMultipleSelection = true @@ -735,8 +729,6 @@ struct CourseProjectEntrySheet: View { .pdf, .html, .plainText, - UTType(filenameExtension: "md") ?? .plainText, - UTType(filenameExtension: "markdown") ?? .plainText, ] guard panel.runModal() == .OK else { return } let urls = panel.urls @@ -778,15 +770,13 @@ struct CourseProjectEntrySheet: View { let courseID = try await store.createCourseInLibraryAsync( title: cleanedTitle ) - if selectedImportURLs.isEmpty { - openCourse(courseID) - } else { - store.importCourseFilesFromURLs( - selectedImportURLs, + let initialImportURLs = selectedImportURLs + openCourse(courseID) + if !initialImportURLs.isEmpty { + store.prepareInitialCourseImportAfterEntryDismissal( + initialImportURLs, courseID: courseID - ) { _ in - openCourse(courseID) - } + ) } } } diff --git a/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift b/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift index a5d7177f4..f869f56b1 100644 --- a/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift +++ b/Sources/WeiBei/Views/EmptyWorkspaceLauncherView.swift @@ -22,6 +22,7 @@ struct EmptyWorkspaceLauncherView: View { @AppStorage("weibei.libraryPlacementConfirmed") private var libraryPlacementConfirmed = false @State private var selectedInspirationID: String? + @State private var isFileDropTargeted = false /// Bumped on theme change so a long-lived NSHostingView cannot keep a stale paper snapshot. @State private var appearanceEpoch = 0 @@ -105,9 +106,24 @@ struct EmptyWorkspaceLauncherView: View { } .accessibilityElement(children: .contain) .accessibilityIdentifier("empty-workspace-launcher") - .onDrop(of: [.fileURL], isTargeted: nil) { providers in + .onDrop(of: [.fileURL], isTargeted: $isFileDropTargeted) { providers in WeiBeiDroppedFileURLs.load(providers) { urls in - store.importFiles(urls) + store.prepareConfirmedFileImport(urls) + } + } + .overlay { + if isFileDropTargeted { + Label(store.ui("松开以导入资料", "Drop to import"), systemImage: "tray.and.arrow.down") + .weiBeiText(14, weight: .semibold) + .foregroundStyle(WeiBeiTheme.cinnabar) + .padding(.horizontal, 18) + .padding(.vertical, 12) + .weibeiEtchedCapsuleBackground( + fill: WeiBeiTheme.paperRaised.opacity(0.94), + stroke: WeiBeiTheme.cinnabar.opacity(0.32), + contactShadow: true + ) + .allowsHitTesting(false) } } } diff --git a/Sources/WeiBei/Views/SidebarView.swift b/Sources/WeiBei/Views/SidebarView.swift index d7aab288a..b60597260 100644 --- a/Sources/WeiBei/Views/SidebarView.swift +++ b/Sources/WeiBei/Views/SidebarView.swift @@ -158,46 +158,58 @@ struct CourseSidebarList: View { let onManageCourse: (UUID) -> Void var body: some View { - List { - Section { - if model.courses.isEmpty { - if store.courses.isEmpty { - SidebarEmptyRow( - title: ui("还没有课程", "No courses yet") - ) + ScrollViewReader { scrollProxy in + List { + Section { + if model.courses.isEmpty { + if store.courses.isEmpty { + SidebarEmptyRow( + title: ui("还没有课程", "No courses yet") + ) + } else { + SidebarEmptyRow(title: ui("还没有匹配课程", "No matching courses")) + } } else { - SidebarEmptyRow(title: ui("还没有匹配课程", "No matching courses")) - } - } else { - ForEach(model.courses) { row in - courseRow(row) + ForEach(model.courses) { row in + courseRow(row) + } } } - } - if !model.unassignedMaterials.isEmpty { - Section { - ForEach(model.unassignedMaterials) { row in - itemRow(row, compact: false, accent: nil, opensNotebook: false) + if !model.unassignedMaterials.isEmpty { + Section { + ForEach(model.unassignedMaterials) { row in + itemRow(row, compact: false, accent: nil, opensNotebook: false) + } + } header: { + SidebarSectionHeader(title: ui("通用资料", "General materials")) } - } header: { - SidebarSectionHeader(title: ui("通用资料", "General materials")) } - } - if !model.unassignedNotes.isEmpty { - Section { - ForEach(model.unassignedNotes) { row in - itemRow(row, compact: false, accent: nil, opensNotebook: true) + if !model.unassignedNotes.isEmpty { + Section { + ForEach(model.unassignedNotes) { row in + itemRow(row, compact: false, accent: nil, opensNotebook: true) + } + } header: { + SidebarSectionHeader(title: ui("独立笔记", "Unassigned Notes")) } - } header: { - SidebarSectionHeader(title: ui("独立笔记", "Unassigned Notes")) } } + .listStyle(.plain) + .scrollContentBackground(.hidden) + .background(WeiBeiTheme.paper) + .onAppear { + scrollToRecentlyImported(using: scrollProxy) + } + .onChange(of: model.recentlyImportedItemIDs) { _, _ in + scrollToRecentlyImported(using: scrollProxy) + } + .onChange(of: recentlyImportedScrollTarget) { _, target in + guard let target else { return } + scrollProxy.scrollTo(target, anchor: .center) + } } - .listStyle(.plain) - .scrollContentBackground(.hidden) - .background(WeiBeiTheme.paper) .task(id: model.searchTagTaskID) { [weak store = store, weak model = model] in guard let requests = model?.missingTagRequestsForSearch(), !requests.isEmpty else { return } @@ -218,6 +230,15 @@ struct CourseSidebarList: View { } } + private var recentlyImportedScrollTarget: String? { + model.firstVisibleItemID(in: model.recentlyImportedItemIDs) + } + + private func scrollToRecentlyImported(using proxy: ScrollViewProxy) { + guard let target = recentlyImportedScrollTarget else { return } + proxy.scrollTo(target, anchor: .center) + } + @ViewBuilder private func courseRow(_ row: CourseSidebarCourseRow) -> some View { let course = row.course @@ -369,8 +390,13 @@ struct CourseSidebarList: View { bottom: 1, trailing: 2 )) - .listRowBackground(Color.clear) + .listRowBackground( + store.recentlyImportedItemIDs.contains(item.id) + ? WeiBeiTheme.cinnabarSoft.opacity(0.24) + : Color.clear + ) .listRowSeparator(.hidden) + .id(item.id) // 显示名与标签共用同一条异步正文管线:compact 行(课程分组内)不展示标签, // 但展示解析后的笔记名,所以笔记行无论 compact 与否都要加载。 .task(id: row.tagRequest) { [weak store = store, weak model = model] in diff --git a/Sources/WeiBeiCore/ImportFileCopy.swift b/Sources/WeiBeiCore/ImportFileCopy.swift index ce304a026..483a9be77 100644 --- a/Sources/WeiBeiCore/ImportFileCopy.swift +++ b/Sources/WeiBeiCore/ImportFileCopy.swift @@ -1,5 +1,11 @@ import Foundation +public enum ImportFileCollision: Equatable, Sendable { + case available + case duplicate + case conflict(suggestedFileName: String) +} + /// Kernel-side import copying for the course library. /// /// Dedupe semantics: byte-identical content resolves to the existing library @@ -11,30 +17,99 @@ public enum ImportFileCopy { static let comparisonChunkSize = 1 << 20 public static func copyPreservingOriginal(from sourceURL: URL, into directory: URL) throws -> URL { - if let html = try HTMLResourceImport.dataIfHTML(at: sourceURL) { - let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) - var target = preferred - if FileManager.default.fileExists(atPath: preferred.path) { - if try preferred.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count, - try Data(contentsOf: preferred) == html { return preferred } - target = uniqueCopyURL(in: directory, preferred: preferred) + let html = try HTMLResourceImport.dataIfHTML(at: sourceURL) + switch try collision(from: sourceURL, into: directory, preparedHTML: html) { + case .available: + break + case .duplicate: + return directory.appendingPathComponent(sourceURL.lastPathComponent) + case .conflict(let suggestedFileName): + let target = directory.appendingPathComponent(suggestedFileName) + if let html { + try html.write(to: target, options: .withoutOverwriting) + } else { + try FileManager.default.copyItem(at: sourceURL, to: target) } - try html.write(to: target, options: .withoutOverwriting) return target } let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) - if FileManager.default.fileExists(atPath: preferred.path) { - if try filesHaveIdenticalContents(sourceURL, preferred) { - return preferred - } - let unique = uniqueCopyURL(in: directory, preferred: preferred) - try FileManager.default.copyItem(at: sourceURL, to: unique) - return unique + if let html { + try html.write(to: preferred, options: .withoutOverwriting) + return preferred } try FileManager.default.copyItem(at: sourceURL, to: preferred) return preferred } + /// Read-only counterpart of `copyPreservingOriginal`. The confirmation UI + /// uses the same comparison and naming rules without creating directories + /// or copying bytes before the user confirms. + public static func collision(from sourceURL: URL, into directory: URL) throws -> ImportFileCollision { + try collision( + from: sourceURL, + into: directory, + preparedHTML: HTMLResourceImport.dataIfHTML(at: sourceURL) + ) + } + + public static func sourcesHaveIdenticalImportedContents( + _ lhs: URL, + _ rhs: URL + ) throws -> Bool { + let lhsHTML = try HTMLResourceImport.dataIfHTML(at: lhs) + let rhsHTML = try HTMLResourceImport.dataIfHTML(at: rhs) + switch (lhsHTML, rhsHTML) { + case let (.some(lhsData), .some(rhsData)): + return lhsData == rhsData + case (.none, .none): + return try filesHaveIdenticalContents(lhs, rhs) + default: + return false + } + } + + /// Compare the bytes a source would import with an already imported file. + /// Do not re-embed HTML resources relative to the copy's new directory. + public static func sourceHasIdenticalImportedContents( + _ sourceURL: URL, + at importedURL: URL + ) throws -> Bool { + try importedContentsMatch( + from: sourceURL, + at: importedURL, + preparedHTML: HTMLResourceImport.dataIfHTML(at: sourceURL) + ) + } + + private static func collision( + from sourceURL: URL, + into directory: URL, + preparedHTML: Data? + ) throws -> ImportFileCollision { + let preferred = directory.appendingPathComponent(sourceURL.lastPathComponent) + guard FileManager.default.fileExists(atPath: preferred.path) else { + return .available + } + if try importedContentsMatch(from: sourceURL, at: preferred, preparedHTML: preparedHTML) { + return .duplicate + } + return .conflict(suggestedFileName: uniqueCopyURL(in: directory, preferred: preferred).lastPathComponent) + } + + private static func importedContentsMatch( + from sourceURL: URL, + at importedURL: URL, + preparedHTML: Data? + ) throws -> Bool { + if let html = preparedHTML { + guard try importedURL.resourceValues(forKeys: [.fileSizeKey]).fileSize == html.count else { + return false + } + return try Data(contentsOf: importedURL) == html + } + return try filesHaveIdenticalContents(sourceURL, importedURL) + } + static func filesHaveIdenticalContents(_ lhs: URL, _ rhs: URL) throws -> Bool { let lhsSize = try lhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 let rhsSize = try rhs.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? -1 @@ -55,7 +130,7 @@ public enum ImportFileCopy { } } - static func uniqueCopyURL(in directory: URL, preferred: URL) -> URL { + public static func uniqueCopyURL(in directory: URL, preferred: URL) -> URL { let stem = preferred.deletingPathExtension().lastPathComponent let ext = preferred.pathExtension var index = 2 diff --git a/Sources/WeiBeiWebEditorCheck/main.swift b/Sources/WeiBeiWebEditorCheck/main.swift index 0d2302dea..d01e9b5ad 100644 --- a/Sources/WeiBeiWebEditorCheck/main.swift +++ b/Sources/WeiBeiWebEditorCheck/main.swift @@ -1585,7 +1585,7 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { let imageMarkdown = "![failed alt](missing.png)\n\n![success alt](data:image/svg+xml;base64,PHN2Zy8+)" let mermaidMarkdown = "```mermaid\ngraph TD\nA --> B\n```\n\nafter" let script = """ - (() => { + return await (async () => { const editor = window.WeiBeiEditor; editor.setDocumentID('work-package-e-metrics'); editor.setMarkdown(\(json(ordinaryMarkdown))); @@ -1626,7 +1626,13 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { document.querySelector('.ProseMirror')?.dispatchEvent(new FocusEvent('focus')); if (!editor.selectFirstCodeBlockEndForCheck()) throw new Error('Mermaid selection helper unavailable'); window.WeiBeiMermaidPreviewForE = document.querySelector('.weibei-mermaid-render'); - window.WeiBeiMermaidHTMLForE = window.WeiBeiMermaidPreviewForE?.innerHTML || ''; + // Isolate the debounce contract from lazy engine loading and the initial SVG render. + const initialDeadline = performance.now() + 5000; + while (window.WeiBeiMermaidPreviewForE?.dataset.rendered !== 'true' && performance.now() < initialDeadline) { + await new Promise(resolve => window.setTimeout(resolve, 25)); + } + if (window.WeiBeiMermaidPreviewForE?.dataset.rendered !== 'true') throw new Error('initial Mermaid preview did not become ready'); + window.WeiBeiMermaidHTMLForE = window.WeiBeiMermaidPreviewForE.innerHTML; editor.resetCheckMetrics(); if (!editor.typeTextForCheck('x')) throw new Error('Mermaid typing helper unavailable'); window.WeiBeiMermaidBeforeForE = new Promise((resolve) => window.setTimeout(() => resolve({ @@ -1648,9 +1654,9 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { }; })(); """ - webView.evaluateJavaScript(script) { [weak self] value, error in + webView.callAsyncJavaScript(script, arguments: [:], in: nil, in: .page) { [weak self] outcome in guard let self else { return } - guard error == nil, + guard case let .success(value) = outcome, let result = value as? [String: Any], result["selectionDecorationNodes"] as? Int == 0, result["inputImageScans"] as? Int == 0, @@ -1662,7 +1668,7 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { result["successSelectable"] as? Bool == true, result["mermaidPreviewExists"] as? Bool == true, result["mermaidDOMReused"] as? Bool == true else { - self.fail("work package E structural metrics or image identity failed: \(String(describing: error)); \(String(describing: value))") + self.fail("work package E structural metrics or image identity failed: \(String(describing: outcome))") return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.15) { @@ -1688,12 +1694,12 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { return } DispatchQueue.main.asyncAfter(deadline: .now() + 0.35) { - self.validateMermaidDebounceAfterDeadline() + self.validateMermaidDebounceAfterDeadline(deadline: Date().addingTimeInterval(5)) } } } - private func validateMermaidDebounceAfterDeadline() { + private func validateMermaidDebounceAfterDeadline(deadline: Date) { webView.evaluateJavaScript(""" ({ sameDOM: document.querySelector('.weibei-mermaid-render') === window.WeiBeiMermaidPreviewForE, @@ -1702,15 +1708,22 @@ final class EditorHarness: NSObject, WKScriptMessageHandler { }) """) { [weak self] value, error in guard let self else { return } - guard error == nil, - let result = value as? [String: Any], - result["sameDOM"] as? Bool == true, - result["changedHTML"] as? Bool == true, - (result["renders"] as? Int ?? 0) >= 1 else { + guard error == nil, let result = value as? [String: Any], + result["sameDOM"] as? Bool == true else { + self.fail("focused Mermaid preview replaced its DOM or failed: \(String(describing: error)); \(String(describing: value))") + return + } + if result["changedHTML"] as? Bool == true && (result["renders"] as? Int ?? 0) >= 1 { + self.validateOutlineInitialEvent() + return + } + guard Date() < deadline else { self.fail("focused Mermaid preview did not update in place after its 300ms debounce: \(String(describing: value))") return } - self.validateOutlineInitialEvent() + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { + self.validateMermaidDebounceAfterDeadline(deadline: deadline) + } } } diff --git a/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift new file mode 100644 index 000000000..d11a6e8ac --- /dev/null +++ b/Tests/WeiBeiSafetyTests/ConfirmedFileImportTests.swift @@ -0,0 +1,1242 @@ +import Foundation +@testable import WeiBei +import WeiBeiCore +import XCTest + +@MainActor +final class ConfirmedFileImportTests: XCTestCase { + override class func setUp() { + super.setUp() + setenv("WEIBEI_SAFETY_TEST_MODE", "1", 1) + } + + func testCancelBeforeConfirmationWritesNothing() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + try Data("source".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library + .appendingPathComponent("通用资料/讲义.txt") + .path + )) + fixture.store.dismissConfirmedFileImport() + XCTAssertTrue(FileManager.default.fileExists(atPath: source.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library + .appendingPathComponent("通用资料/讲义.txt") + .path + )) + } + + func testPartialFailureKeepsSuccessAndRetriesOnlyFailure() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: second) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.map(\.subtitle), ["一.txt"]) + XCTAssertEqual(batch.failures.map(\.sourceURL.lastPathComponent), ["二.txt"]) + XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) + XCTAssertTrue(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/一.txt").path + )) + + try Data("two".utf8).write(to: second) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [second]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual( + Set(fixture.store.importedItems.map(\.subtitle)), + Set(["一.txt", "二.txt"]) + ) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + XCTAssertEqual( + try String(contentsOf: fixture.library.appendingPathComponent("通用资料/一.txt")), + "one" + ) + } + + func testStopBeforeNextTaskLeavesSourcesUntouched() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + let baseline = fixture.outside.appendingPathComponent("当前阅读.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + try Data("baseline".utf8).write(to: baseline) + + fixture.store.prepareConfirmedFileImport([baseline]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + fixture.store.readerPageIndex = 9 + fixture.store.readerLocationID = "停止前位置" + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + fixture.store.stopConfirmedFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.importedItems.map(\.subtitle), ["当前阅读.txt"]) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.readerPageIndex, 9) + XCTAssertEqual(fixture.store.readerLocationID, "停止前位置") + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("导入已停止") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("2 份未导入") == true) + XCTAssertTrue(FileManager.default.fileExists(atPath: first.path)) + XCTAssertTrue(FileManager.default.fileExists(atPath: second.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/一.txt").path + )) + } + + func testDockFilesJoinOneCommonBatchBeforeConfirmation() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("一.txt") + let second = fixture.outside.appendingPathComponent("二.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + + fixture.store.receiveExternalFileForConfirmedImport(first) + fixture.store.receiveExternalFileForConfirmedImport(second) + waitForStage(.reviewing, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertNil(batch.courseID) + XCTAssertEqual(Set(batch.sourceURLs), Set([first, second])) + XCTAssertEqual(batch.candidates.count, 2) + XCTAssertTrue(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ).isEmpty) + } + + func testCommonMarkdownStaysMaterialAfterConfirmationOpenAndMaintenance() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("阅读材料.md") + try Data("# 阅读材料\n\n正文".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "阅读材料.md" } + ) + XCTAssertEqual(imported.kind, .markdown) + XCTAssertFalse(imported.isNotebookNote) + XCTAssertTrue(imported.isCourseMaterial) + XCTAssertEqual( + imported.storage, + .common(relativePath: "通用资料/阅读材料.md") + ) + + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + XCTAssertNotEqual(fixture.store.activeNoteItemID, imported.id) + + try fixture.store.waitForCourseFileOperation { + await fixture.store.reconcileCourseFilesNow() + } + let maintained = try XCTUnwrap( + fixture.store.importedItems.first { $0.id == imported.id } + ) + XCTAssertFalse(maintained.isNotebookNote) + XCTAssertTrue(maintained.isCourseMaterial) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + } + + func testSingleNoteSuccessOpensNoteWithoutResultModal() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("课堂笔记.md") + try Data("# 课堂笔记\n\n正文".utf8).write(to: source) + + fixture.store.prepareConfirmedFileImport([source], asNotes: true) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "课堂笔记.md" } + ) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertTrue(imported.isNotebookNote) + XCTAssertFalse(imported.isCourseMaterial) + XCTAssertEqual(imported.storage, .common(relativePath: "通用笔记/课堂笔记.md")) + XCTAssertEqual(fixture.store.activeNoteItemID, imported.id) + XCTAssertNil(fixture.store.transientNoteStatus) + } + + func testAllDuplicateImportPreservesReadingSelectionAndExplainsNoChange() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let existingSource = fixture.outside.appendingPathComponent("已存在资料.txt") + let currentSource = fixture.outside.appendingPathComponent("当前阅读资料.txt") + try Data("same".utf8).write(to: existingSource) + try Data("current".utf8).write(to: currentSource) + + fixture.store.prepareConfirmedFileImport([existingSource]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + fixture.store.prepareConfirmedFileImport([currentSource]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + fixture.store.readerPageIndex = 7 + fixture.store.readerLocationID = "保持这里" + + fixture.store.prepareConfirmedFileImport([existingSource]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.selectedMaterialItem?.subtitle, "当前阅读资料.txt") + XCTAssertEqual(fixture.store.readerPageIndex, 7) + XCTAssertEqual(fixture.store.readerLocationID, "保持这里") + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "已存在资料.txt" }.count, 1) + XCTAssertEqual( + Set(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + )), + Set(["已存在资料.txt", "当前阅读资料.txt"]) + ) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("已存在") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("未重复导入") == true) + } + + func testMixedSuccessAndUnsupportedAutoOpensAndExplainsUnsupportedFile() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let supported = fixture.outside.appendingPathComponent("可读.txt") + let unsupported = fixture.outside.appendingPathComponent("原件.zip") + try Data("text".utf8).write(to: supported) + try Data("zip".utf8).write(to: unsupported) + + fixture.store.prepareConfirmedFileImport([supported, unsupported]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "可读.txt" } + ) + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, imported.id) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个格式不支持") == true) + XCTAssertFalse(fixture.store.transientNoteStatus?.contains("已导入") == true) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/原件.zip").path + )) + XCTAssertTrue(FileManager.default.fileExists(atPath: unsupported.path)) + } + + func testUnsupportedOnlySelectionClosesWithoutWritingOrChangingReadingSelection() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let baseline = fixture.outside.appendingPathComponent("当前资料.txt") + let unsupported = fixture.outside.appendingPathComponent("原件.zip") + try Data("baseline".utf8).write(to: baseline) + try Data("zip".utf8).write(to: unsupported) + + fixture.store.prepareConfirmedFileImport([baseline]) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let selectedID = try XCTUnwrap(fixture.store.selectedMaterialItem?.id) + + fixture.store.prepareConfirmedFileImport([unsupported]) + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.selectedMaterialItem?.id, selectedID) + XCTAssertEqual(fixture.store.importedItems.count, 1) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("没有可导入的文件") == true) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个格式不支持") == true) + XCTAssertTrue(FileManager.default.fileExists(atPath: unsupported.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/原件.zip").path + )) + } + + func testEmptyFolderClosesWithLightFeedbackAndNoWrite() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let emptyFolder = fixture.outside.appendingPathComponent("空资料夹", isDirectory: true) + try FileManager.default.createDirectory(at: emptyFolder, withIntermediateDirectories: true) + + fixture.store.prepareConfirmedFileImport([emptyFolder]) + waitForImportIdle(in: fixture.store) + + XCTAssertTrue(fixture.store.importedItems.isEmpty) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("没有可导入的文件") == true) + XCTAssertTrue(try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ).isEmpty) + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: emptyFolder.path).isEmpty) + } + + func testUnavailableDestinationKeepsReviewErrorEvenWithNoCandidates() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("无法导入.txt") + try Data("source".utf8).write(to: source) + fixture.store.courseLibraryRootURL = nil + + fixture.store.prepareConfirmedFileImport([source]) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.stage, .reviewing) + XCTAssertNotNil(batch.destinationError) + XCTAssertTrue(batch.candidates.isEmpty) + XCTAssertNil(fixture.store.transientNoteStatus) + XCTAssertTrue(FileManager.default.fileExists(atPath: source.path)) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/无法导入.txt").path + )) + } + + func testMissingSourceStaysVisibleAsRetryableFailure() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let missing = fixture.outside.appendingPathComponent("已移走.txt") + + fixture.store.prepareConfirmedFileImport([missing]) + waitForStage(.finished, in: fixture.store) + + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertTrue(batch.candidates.isEmpty) + XCTAssertEqual(batch.failures.map(\.sourceURL), [missing]) + XCTAssertTrue(batch.failures.first?.message.contains("无法访问") == true) + XCTAssertNil(fixture.store.transientNoteStatus) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.finished, in: fixture.store) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.failures.map(\.sourceURL), [missing]) + XCTAssertNil(fixture.store.transientNoteStatus) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/已移走.txt").path + )) + } + + func testUnreadableFileIsOnlyAVisibleFailureAndNeverACandidate() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let unreadable = fixture.outside.appendingPathComponent("暂不可读.txt") + try Data("source".utf8).write(to: unreadable) + try FileManager.default.setAttributes( + [.posixPermissions: 0], + ofItemAtPath: unreadable.path + ) + defer { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o600], + ofItemAtPath: unreadable.path + ) + } + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [unreadable], + destination: fixture.library.appendingPathComponent("通用资料", isDirectory: true), + markdownOnly: false + ) + + XCTAssertTrue(plan.candidates.isEmpty) + XCTAssertEqual(plan.unavailableSourceURLs, [unreadable.standardizedFileURL]) + XCTAssertTrue(plan.unsupportedNames.isEmpty) + } + + func testNestedEnumerationFailureRetriesOnlyFailedSubtreeWithoutDuplicatePollution() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let folder = fixture.outside.appendingPathComponent("混合资料", isDirectory: true) + let locked = folder.appendingPathComponent("暂不可读", isDirectory: true) + try FileManager.default.createDirectory(at: locked, withIntermediateDirectories: true) + let readable = folder.appendingPathComponent("可读.txt") + try Data("readable".utf8).write(to: readable) + try Data("locked".utf8).write(to: locked.appendingPathComponent("内部.txt")) + try FileManager.default.setAttributes( + [.posixPermissions: 0], + ofItemAtPath: locked.path + ) + defer { + try? FileManager.default.setAttributes( + [.posixPermissions: 0o700], + ofItemAtPath: locked.path + ) + } + + fixture.store.prepareConfirmedFileImport([folder]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.sourceURL), + [readable.standardizedFileURL] + ) + XCTAssertEqual( + fixture.store.confirmedFileImport?.failures.map(\.sourceURL), + [locked.standardizedFileURL] + ) + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.map(\.subtitle), ["可读.txt"]) + XCTAssertEqual(batch.failures.map(\.sourceURL), [locked.standardizedFileURL]) + XCTAssertEqual(batch.duplicateCount, 0) + + try FileManager.default.setAttributes( + [.posixPermissions: 0o700], + ofItemAtPath: locked.path + ) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.candidates.map(\.sourceURL), [ + locked.appendingPathComponent("内部.txt").standardizedFileURL, + ]) + XCTAssertEqual(batch.duplicateCount, 0) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual( + Set(fixture.store.importedItems.map(\.subtitle)), + Set(["可读.txt", "内部.txt"]) + ) + XCTAssertNil(fixture.store.transientNoteStatus) + } + + func testDockFileOpenedDuringImportWaitsForNextBatch() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let current = fixture.outside.appendingPathComponent("当前.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("current".utf8).write(to: current) + try Data("waiting".utf8).write(to: waiting) + + fixture.store.prepareConfirmedFileImport([current]) + waitForStage(.reviewing, in: fixture.store) + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + batch.stage = .importing + fixture.store.confirmedFileImport = batch + + fixture.store.receiveExternalFileForConfirmedImport(waiting) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.sourceURLs, [current]) + XCTAssertEqual(batch.pendingSourceURLs, [waiting]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/稍后.txt").path + )) + + batch.stage = .finished + fixture.store.confirmedFileImport = batch + fixture.store.continuePendingConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + } + + func testPendingBatchCannotSilentlyDiscardFailures() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let failed = fixture.outside.appendingPathComponent("失败.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("failed".utf8).write(to: failed) + try Data("waiting".utf8).write(to: waiting) + let failure = ConfirmedFileImportFailure(sourceURL: failed, message: "失败") + fixture.store.confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: [failed], + sourceFolderNames: [], + courseID: nil, + importsMarkdownAsNotes: false, + stage: .importing, + failures: [failure] + ) + fixture.store.prepareConfirmedFileImport([waiting]) + fixture.store.confirmedFileImport?.stage = .finished + + fixture.store.continuePendingConfirmedFileImport() + XCTAssertEqual(fixture.store.confirmedFileImport?.failures, [failure]) + XCTAssertEqual(fixture.store.confirmedFileImport?.pendingSourceURLs, [waiting]) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [failed]) + XCTAssertEqual(fixture.store.confirmedFileImport?.pendingSourceURLs, [waiting]) + } + + func testPendingBatchContinuesAfterExplicitlyAbandoningFailures() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let failed = fixture.outside.appendingPathComponent("失败.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.txt") + try Data("failed".utf8).write(to: failed) + try Data("waiting".utf8).write(to: waiting) + fixture.store.confirmedFileImport = ConfirmedFileImportBatch( + id: UUID(), + sourceURLs: [failed], + sourceFolderNames: [], + courseID: nil, + importsMarkdownAsNotes: false, + stage: .importing, + failures: [ConfirmedFileImportFailure(sourceURL: failed, message: "失败")] + ) + fixture.store.prepareConfirmedFileImport([waiting]) + fixture.store.confirmedFileImport?.stage = .finished + + fixture.store.continuePendingConfirmedFileImport(abandoningFailures: true) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + XCTAssertTrue(fixture.store.confirmedFileImport?.failures.isEmpty == true) + } + + func testFilePickerBatchDuringImportKeepsDestinationAndSecurityScope() throws { + var stoppedScopes: [URL] = [] + let fixture = try makeFixture( + securityScopeStopper: { stoppedScopes.append($0.standardizedFileURL) } + ) + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "稍后导入") + let current = fixture.outside.appendingPathComponent("当前.txt") + let waiting = fixture.outside.appendingPathComponent("稍后.md") + try Data("current".utf8).write(to: current) + try Data("waiting".utf8).write(to: waiting) + + fixture.store.prepareConfirmedFileImport([current]) + waitForStage(.reviewing, in: fixture.store) + var batch = try XCTUnwrap(fixture.store.confirmedFileImport) + batch.stage = .importing + fixture.store.confirmedFileImport = batch + + fixture.store.prepareConfirmedFileImport( + [waiting], + courseID: courseID, + asNotes: true, + securityScopedURLs: [waiting] + ) + + batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.pendingSourceURLs, [waiting]) + XCTAssertTrue(stoppedScopes.isEmpty) + + batch.stage = .finished + fixture.store.confirmedFileImport = batch + fixture.store.continuePendingConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [waiting]) + XCTAssertEqual(fixture.store.confirmedFileImport?.courseID, courseID) + XCTAssertEqual(fixture.store.confirmedFileImport?.importsMarkdownAsNotes, true) + XCTAssertTrue(stoppedScopes.isEmpty) + + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + let imported = try XCTUnwrap( + fixture.store.importedItems.first { $0.subtitle == "稍后.md" } + ) + XCTAssertEqual( + imported.storage, + .courseOwned(ownerCourseID: courseID, relativePath: "笔记/稍后.md") + ) + XCTAssertEqual(stoppedScopes, [waiting.standardizedFileURL]) + } + + func testInitialCourseFilesWaitForUnifiedConfirmation() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("课程讲义.pdf") + try Data("pdf".utf8).write(to: source) + let courseID = try fixture.store.createCourseInLibrary(title: "确认课") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + + fixture.store.prepareInitialCourseImportAfterEntryDismissal([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.courseID, courseID) + XCTAssertFalse(FileManager.default.fileExists( + atPath: courseRoot.appendingPathComponent("文稿/课程讲义.pdf").path + )) + } + + func testCourseBatchRevealsItsExpandedSidebarGroup() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let first = fixture.outside.appendingPathComponent("第一讲.txt") + let second = fixture.outside.appendingPathComponent("第二讲.txt") + try Data("one".utf8).write(to: first) + try Data("two".utf8).write(to: second) + let courseID = try fixture.store.createCourseInLibrary(title: "批量课") + fixture.store.activateCourse(nil) + fixture.store.librarySearch = "旧搜索" + fixture.store.showLibrary = false + fixture.store.courseWorkspacePresented = true + + fixture.store.prepareConfirmedFileImport([first, second], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.activeCourseID, courseID) + XCTAssertEqual(fixture.store.librarySearch, "") + XCTAssertTrue(fixture.store.showLibrary) + XCTAssertFalse(fixture.store.courseWorkspacePresented) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + } + + func testCollisionPlanUsesCopyKernelWithoutWriting() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-collision-\(UUID().uuidString)", isDirectory: true) + let sourceDirectory = root.appendingPathComponent("source", isDirectory: true) + let destination = root.appendingPathComponent("destination", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + try FileManager.default.createDirectory(at: sourceDirectory, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) + let source = sourceDirectory.appendingPathComponent("同名.txt") + let existing = destination.appendingPathComponent("同名.txt") + try Data("new".utf8).write(to: source) + try Data("old".utf8).write(to: existing) + + XCTAssertEqual( + try ImportFileCopy.collision(from: source, into: destination), + .conflict(suggestedFileName: "同名 2.txt") + ) + XCTAssertEqual(try FileManager.default.contentsOfDirectory(atPath: destination.path), ["同名.txt"]) + try Data("old".utf8).write(to: source) + XCTAssertEqual(try ImportFileCopy.collision(from: source, into: destination), .duplicate) + } + + func testMarkdownOnlyPlanKeepsUnsupportedFilenameUnlocalized() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let unsupported = fixture.outside.appendingPathComponent("讲义.pdf") + try Data("pdf".utf8).write(to: unsupported) + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [unsupported], + destination: fixture.library.appendingPathComponent("通用笔记", isDirectory: true), + markdownOnly: true + ) + + XCTAssertTrue(plan.candidates.isEmpty) + XCTAssertEqual(plan.unsupportedNames, ["讲义.pdf"]) + } + + func testSameNameInsideBatchIsShownAsConflictBeforeConfirmation() throws { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-batch-collision-\(UUID().uuidString)", isDirectory: true) + let firstDirectory = root.appendingPathComponent("a", isDirectory: true) + let secondDirectory = root.appendingPathComponent("b", isDirectory: true) + let destination = root.appendingPathComponent("destination", isDirectory: true) + defer { try? FileManager.default.removeItem(at: root) } + for directory in [firstDirectory, secondDirectory, destination] { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = firstDirectory.appendingPathComponent("同名.txt") + let second = secondDirectory.appendingPathComponent("同名.txt") + try Data("first".utf8).write(to: first) + try Data("second".utf8).write(to: second) + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [first, second], + destination: destination, + markdownOnly: false + ) + + XCTAssertEqual(plan.candidates.count, 2) + XCTAssertEqual(plan.candidates[0].disposition, .ready) + XCTAssertEqual(plan.candidates[1].disposition, .conflict(suggestedFileName: "同名 2.txt")) + XCTAssertTrue(try FileManager.default.contentsOfDirectory(atPath: destination.path).isEmpty) + } + + func testSameNameAndContentInsideBatchSkipsSecondCopy() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let firstDirectory = fixture.outside.appendingPathComponent("a", isDirectory: true) + let secondDirectory = fixture.outside.appendingPathComponent("b", isDirectory: true) + try FileManager.default.createDirectory(at: firstDirectory, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: secondDirectory, withIntermediateDirectories: true) + let first = firstDirectory.appendingPathComponent("同名.txt") + let second = secondDirectory.appendingPathComponent("同名.txt") + try Data("same".utf8).write(to: first) + try Data("same".utf8).write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.disposition), + [.ready, .duplicate] + ) + + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "同名.txt" }.count, 1) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个已存在") == true) + XCTAssertEqual( + try FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + ), + ["同名.txt"] + ) + } + + func testDuplicateSourceImportsWhenEarlierSourceDisappearsAfterReview() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = directories[0].appendingPathComponent("同名.txt") + let second = directories[1].appendingPathComponent("同名.txt") + let content = Data("same".utf8) + try content.write(to: first) + try content.write(to: second) + + fixture.store.prepareConfirmedFileImport([first, second]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready, .duplicate]) + try FileManager.default.removeItem(at: first) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.importedItems.count, 1) + XCTAssertEqual(batch.failures.map(\.sourceURL), [first]) + XCTAssertEqual(batch.duplicateCount, 0) + XCTAssertEqual(batch.candidates[1].disposition, .ready) + XCTAssertEqual(try Data(contentsOf: fixture.library.appendingPathComponent("通用资料/同名.txt")), content) + XCTAssertEqual(try Data(contentsOf: second), content) + + try content.write(to: first) + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [first]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "同名.txt" }.count, 1) + } + + func testCourseDuplicateSourceImportsAfterRepresentativeTransactionFails() throws { + var failNextStaging = false + let fixture = try makeFixture { stage in + if failNextStaging, stage == .beforeCourseFileStagingCopy { + failNextStaging = false + throw CocoaError(.fileWriteUnknown) + } + } + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "重复项恢复") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let existing = courseRoot.appendingPathComponent("文稿/同名.txt") + let existingContent = Data("different existing content".utf8) + try existingContent.write(to: existing) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "同名 2.txt"), .duplicate + ]) + failNextStaging = true + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertFalse(failNextStaging) + XCTAssertEqual(batch.importedItems.count, 1) + XCTAssertEqual(batch.failures.map(\.sourceURL), [files[0]]) + XCTAssertEqual(batch.duplicateCount, 0) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) + XCTAssertEqual(fixture.store.courseMaterials(in: courseID).count, 1) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.sourceURLs, [files[0]]) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertEqual(fixture.store.courseMaterials(in: courseID).count, 1) + XCTAssertFalse(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent("文稿/同名 3.txt").path)) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) + } + + func testRetryInAnotherCourseDoesNotSkipCopyFromPreviousDestination() throws { + var failNextStaging = false + let fixture = try makeFixture { stage in + if failNextStaging, stage == .beforeCourseFileStagingCopy { + failNextStaging = false + throw CocoaError(.fileWriteUnknown) + } + } + defer { try? FileManager.default.removeItem(at: fixture.root) } + let firstCourseID = try fixture.store.createCourseInLibrary(title: "第一目标") + let nextCourseID = try fixture.store.createCourseInLibrary(title: "第二目标") + let firstRoot = try XCTUnwrap(fixture.store.courseRootURL(for: firstCourseID)) + let nextRoot = try XCTUnwrap(fixture.store.courseRootURL(for: nextCourseID)) + let existing = firstRoot.appendingPathComponent("文稿/同名.txt") + let existingContent = Data("different existing content".utf8) + try existingContent.write(to: existing) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: firstCourseID) + waitForStage(.reviewing, in: fixture.store) + failNextStaging = true + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [files[0]]) + XCTAssertEqual(try Data(contentsOf: firstRoot.appendingPathComponent("文稿/同名 2.txt")), content) + + fixture.store.retryFailedConfirmedFileImport() + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + fixture.store.setConfirmedFileImportDestination(courseID: nextCourseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.ready]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: nextRoot.appendingPathComponent("文稿/同名.txt")), content) + XCTAssertEqual(try Data(contentsOf: firstRoot.appendingPathComponent("文稿/同名 2.txt")), content) + XCTAssertEqual(try Data(contentsOf: existing), existingContent) + XCTAssertEqual(fixture.store.courseMaterials(in: nextCourseID).count, 1) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + + func testReviewedDuplicateImportsWhenDestinationDisappears() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("已存在.txt") + let destination = fixture.library.appendingPathComponent("通用资料/已存在.txt") + let content = Data("same".utf8) + try content.write(to: source) + try content.write(to: destination) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + try FileManager.default.removeItem(at: destination) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(fixture.store.importedItems.filter { $0.subtitle == "已存在.txt" }.count, 1) + XCTAssertEqual(try Data(contentsOf: destination), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + + func testReviewedCourseDuplicateKeepsBothWhenDestinationChanges() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "确认后变更") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let source = fixture.outside.appendingPathComponent("讲义.txt") + let destination = courseRoot.appendingPathComponent("文稿/讲义.txt") + let content = Data("original".utf8) + let changed = Data("external edit".utf8) + try content.write(to: source) + try content.write(to: destination) + + fixture.store.prepareConfirmedFileImport([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [.duplicate]) + try changed.write(to: destination) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: destination), changed) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/讲义 2.txt")), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + + func testCourseDuplicateUsesSuccessfulRenamedRepresentative() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let courseID = try fixture.store.createCourseInLibrary(title: "同名另存恢复") + let courseRoot = try XCTUnwrap(fixture.store.courseRootURL(for: courseID)) + let original = courseRoot.appendingPathComponent("文稿/同名.txt") + let originalContent = Data("existing".utf8) + try originalContent.write(to: original) + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + let content = Data("same new content".utf8) + for file in files { try content.write(to: file) } + + fixture.store.prepareConfirmedFileImport(files, courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "同名 2.txt"), .duplicate + ]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + XCTAssertEqual(try Data(contentsOf: original), originalContent) + XCTAssertEqual(try Data(contentsOf: courseRoot.appendingPathComponent("文稿/同名 2.txt")), content) + XCTAssertFalse(FileManager.default.fileExists(atPath: courseRoot.appendingPathComponent("文稿/同名 3.txt").path)) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + + func testHTMLDuplicateUsesStoredRenamedCopyWithoutReembeddingLibraryResources() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("页面.html") } + let content = Data("".utf8) + for file in files { try content.write(to: file) } + let destination = fixture.library.appendingPathComponent("通用资料", isDirectory: true) + let original = destination.appendingPathComponent("页面.html") + let originalContent = Data("different existing page".utf8) + try originalContent.write(to: original) + let neighboringFrame = destination.appendingPathComponent("frame.html") + let frameContent = Data("unrelated library frame".utf8) + try frameContent.write(to: neighboringFrame) + let expectedImportedBytes = try XCTUnwrap(HTMLResourceImport.dataIfHTML(at: files[0])) + + fixture.store.prepareConfirmedFileImport(files) + waitForStage(.reviewing, in: fixture.store) + XCTAssertEqual(fixture.store.confirmedFileImport?.candidates.map(\.disposition), [ + .conflict(suggestedFileName: "页面 2.html"), .duplicate + ]) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let copied = destination.appendingPathComponent("页面 2.html") + XCTAssertEqual(try Data(contentsOf: copied), expectedImportedBytes) + XCTAssertNotEqual(try HTMLResourceImport.dataIfHTML(at: copied), expectedImportedBytes) + XCTAssertFalse(FileManager.default.fileExists(atPath: destination.appendingPathComponent("页面 3.html").path)) + XCTAssertEqual(try Data(contentsOf: original), originalContent) + XCTAssertEqual(try Data(contentsOf: neighboringFrame), frameContent) + for file in files { XCTAssertEqual(try Data(contentsOf: file), content) } + } + + func testInitialCourseMarkdownImportsAsMaterialOnly() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("初始文稿.md") + let content = Data("# 初始文稿\n\n正文".utf8) + try content.write(to: source) + let courseID = try fixture.store.createCourseInLibrary(title: "初始资料") + + fixture.store.prepareInitialCourseImportAfterEntryDismissal([source], courseID: courseID) + waitForStage(.reviewing, in: fixture.store) + XCTAssertFalse(try XCTUnwrap(fixture.store.confirmedFileImport).importsMarkdownAsNotes) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + + let item = try XCTUnwrap(fixture.store.courseMaterials(in: courseID).first) + XCTAssertFalse(item.isNotebookNote) + XCTAssertTrue(item.isCourseMaterial) + XCTAssertEqual(item.storage, .courseOwned(ownerCourseID: courseID, relativePath: "文稿/初始文稿.md")) + XCTAssertTrue(fixture.store.courseNotes(in: courseID).isEmpty) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(fixture.store.resolvedLibraryURL(for: item))), content) + XCTAssertEqual(try Data(contentsOf: source), content) + } + + func testSameNameCollisionGroupComparesEveryEarlierContent() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b", "c"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let files = directories.map { $0.appendingPathComponent("同名.txt") } + try Data("A".utf8).write(to: files[0]) + try Data("B".utf8).write(to: files[1]) + try Data("B".utf8).write(to: files[2]) + + fixture.store.librarySearch = "旧搜索" + fixture.store.showLibrary = false + fixture.store.prepareConfirmedFileImport(files) + waitForStage(.reviewing, in: fixture.store) + + XCTAssertEqual( + fixture.store.confirmedFileImport?.candidates.map(\.disposition), + [.ready, .conflict(suggestedFileName: "同名 2.txt"), .duplicate] + ) + fixture.store.confirmFileImport() + waitForImportIdle(in: fixture.store) + XCTAssertNil(fixture.store.confirmedFileImport) + XCTAssertEqual(fixture.store.recentlyImportedItemIDs.count, 2) + XCTAssertEqual(fixture.store.librarySearch, "") + XCTAssertTrue(fixture.store.showLibrary) + XCTAssertTrue(fixture.store.transientNoteStatus?.contains("1 个已存在") == true) + XCTAssertEqual( + try Set(FileManager.default.contentsOfDirectory( + atPath: fixture.library.appendingPathComponent("通用资料").path + )), + Set(["同名.txt", "同名 2.txt"]) + ) + } + + func testSameNameHTMLUsesNormalizedImportedContentsForDuplicates() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let directories = ["a", "b"].map { + fixture.outside.appendingPathComponent($0, isDirectory: true) + } + for directory in directories { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + } + let first = directories[0].appendingPathComponent("同名.html") + let second = directories[1].appendingPathComponent("同名.html") + try Data("".utf8).write(to: first) + try Data("".utf8).write(to: second) + let image = Data([0x89, 0x50, 0x4e, 0x47]) + try image.write(to: directories[0].appendingPathComponent("甲.png")) + try image.write(to: directories[1].appendingPathComponent("乙.png")) + XCTAssertNotEqual(try Data(contentsOf: first), try Data(contentsOf: second)) + + let plan = WorkspaceStore.makeConfirmedFileImportPlan( + urls: [first, second], + destination: fixture.library.appendingPathComponent("通用资料", isDirectory: true), + markdownOnly: false + ) + + XCTAssertEqual(plan.candidates.map(\.disposition), [.ready, .duplicate]) + } + + func testMixedFolderListsRecursiveUnsupportedFilesWithoutFollowingSymlinks() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let folder = fixture.outside.appendingPathComponent("资料包", isDirectory: true) + let nested = folder.appendingPathComponent("附件", isDirectory: true) + try FileManager.default.createDirectory(at: nested, withIntermediateDirectories: true) + try Data("pdf".utf8).write(to: folder.appendingPathComponent("讲义.pdf")) + try Data("zip".utf8).write(to: nested.appendingPathComponent("原件.zip")) + let outsideSecret = fixture.root.appendingPathComponent("边界外.zip") + try Data("secret".utf8).write(to: outsideSecret) + try FileManager.default.createSymbolicLink( + at: nested.appendingPathComponent("边界外.zip"), + withDestinationURL: outsideSecret + ) + + fixture.store.prepareConfirmedFileImport([folder]) + waitForStage(.reviewing, in: fixture.store) + + let batch = try XCTUnwrap(fixture.store.confirmedFileImport) + XCTAssertEqual(batch.candidates.map { $0.sourceURL.lastPathComponent }, ["讲义.pdf"]) + XCTAssertEqual(batch.unsupportedNames, ["资料包/附件/原件.zip"]) + XCTAssertEqual(batch.skippedCount, 1) + } + + func testSelectedRootDirectorySymlinkIsNotTraversed() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + try Data("outside".utf8).write(to: outsideDirectory.appendingPathComponent("边界外.pdf")) + let linkedRoot = fixture.outside.appendingPathComponent("链接资料包", isDirectory: true) + try FileManager.default.createSymbolicLink( + at: linkedRoot, + withDestinationURL: outsideDirectory + ) + + let expansion = CourseProjectFileWorker.expandedImportSelection( + from: [linkedRoot], + markdownOnly: false + ) + + XCTAssertTrue(expansion.supported.isEmpty) + XCTAssertTrue(expansion.unsupportedNames.isEmpty) + XCTAssertTrue(expansion.unavailableSourceURLs.isEmpty) + } + + func testNestedDirectorySymlinkIsNotTraversed() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let selectedRoot = fixture.outside.appendingPathComponent("资料包", isDirectory: true) + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try FileManager.default.createDirectory(at: selectedRoot, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + let safe = selectedRoot.appendingPathComponent("安全.pdf") + try Data("safe".utf8).write(to: safe) + try Data("outside".utf8).write(to: outsideDirectory.appendingPathComponent("边界外.pdf")) + try FileManager.default.createSymbolicLink( + at: selectedRoot.appendingPathComponent("链接目录", isDirectory: true), + withDestinationURL: outsideDirectory + ) + + let expansion = CourseProjectFileWorker.expandedImportSelection( + from: [selectedRoot], + markdownOnly: false + ) + + XCTAssertEqual(expansion.supported, [safe.standardizedFileURL]) + XCTAssertTrue(expansion.unsupportedNames.isEmpty) + XCTAssertTrue(expansion.unavailableSourceURLs.isEmpty) + } + + func testConfirmationRejectsSourceReplacedBySymbolicLink() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + let outside = fixture.root.appendingPathComponent("边界外.txt") + try Data("preview".utf8).write(to: source) + try Data("outside".utf8).write(to: outside) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: source) + try FileManager.default.createSymbolicLink(at: source, withDestinationURL: outside) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [source]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: fixture.library.appendingPathComponent("通用资料/讲义.txt").path + )) + } + + func testConfirmationRejectsCommonDirectoryReplacedBySymbolicLink() throws { + let fixture = try makeFixture() + defer { try? FileManager.default.removeItem(at: fixture.root) } + let source = fixture.outside.appendingPathComponent("讲义.txt") + let commonMaterials = fixture.library.appendingPathComponent("通用资料", isDirectory: true) + let outsideDirectory = fixture.root.appendingPathComponent("边界外目录", isDirectory: true) + try Data("source".utf8).write(to: source) + try FileManager.default.createDirectory(at: outsideDirectory, withIntermediateDirectories: true) + + fixture.store.prepareConfirmedFileImport([source]) + waitForStage(.reviewing, in: fixture.store) + try FileManager.default.removeItem(at: commonMaterials) + try FileManager.default.createSymbolicLink( + at: commonMaterials, + withDestinationURL: outsideDirectory + ) + + fixture.store.confirmFileImport() + waitForStage(.finished, in: fixture.store) + + XCTAssertEqual(fixture.store.confirmedFileImport?.failures.map(\.sourceURL), [source]) + XCTAssertFalse(FileManager.default.fileExists( + atPath: outsideDirectory.appendingPathComponent("讲义.txt").path + )) + } + + private func waitForStage( + _ stage: ConfirmedFileImportStage, + in store: WorkspaceStore, + file: StaticString = #filePath, + line: UInt = #line + ) { + let deadline = Date().addingTimeInterval(10) + while store.confirmedFileImport?.stage != stage, Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.02)) + } + XCTAssertEqual(store.confirmedFileImport?.stage, stage, file: file, line: line) + } + + private func waitForImportIdle( + in store: WorkspaceStore, + file: StaticString = #filePath, + line: UInt = #line + ) { + let deadline = Date().addingTimeInterval(10) + while (store.confirmedFileImport != nil || store.confirmedFileImportTask != nil), + Date() < deadline { + RunLoop.main.run(until: Date().addingTimeInterval(0.02)) + } + XCTAssertNil(store.confirmedFileImport, file: file, line: line) + XCTAssertNil(store.confirmedFileImportTask, file: file, line: line) + } + + private func makeFixture( + mutationHook: @escaping (CourseProjectMutationStage) throws -> Void = { _ in }, + securityScopeStopper: @escaping (URL) -> Void = { _ in } + ) throws -> ( + root: URL, + library: URL, + outside: URL, + store: WorkspaceStore + ) { + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("weibei-confirmed-import-\(UUID().uuidString)", isDirectory: true) + let workspace = root.appendingPathComponent("workspace", isDirectory: true) + let library = root.appendingPathComponent("library", isDirectory: true) + let outside = root.appendingPathComponent("outside", isDirectory: true) + try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: library, withIntermediateDirectories: true) + try FileManager.default.createDirectory(at: outside, withIntermediateDirectories: true) + let store = WorkspaceStore( + workspaceDirectory: workspace, + courseRootBookmarkMaker: { Data($0.standardizedFileURL.path.utf8) }, + courseRootBookmarkResolver: { data in + guard let path = String(data: data, encoding: .utf8) else { return nil } + return CourseProjectResolvedBookmark( + url: URL(fileURLWithPath: path), + isStale: false + ) + }, + courseSecurityScopeStarter: { _ in true }, + courseSecurityScopeStopper: securityScopeStopper, + courseProjectMutationHook: mutationHook, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + // These fixture assertions deliberately inspect Chinese localized feedback. + store.interfaceLanguage = .chinese + try store.configureCourseLibrary(at: library) + return (root, library, outside, store) + } +} diff --git a/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift b/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift index 27e5455b2..3ed5a92c2 100644 --- a/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift +++ b/Tests/WeiBeiSafetyTests/ContextualListReturnTests.swift @@ -1,4 +1,5 @@ import AppKit +import Combine import SwiftUI import XCTest @testable import WeiBei @@ -384,4 +385,56 @@ final class ContextualListReturnTests: XCTestCase { store.setNoteCustomDisplayTitle("", for: noteID) XCTAssertEqual(store.agentNoteTitle, "普通首行也作为标题") } + + /// 课程笔记读盘结束必须再次发布状态,否则笔记栏会一直停在载入动画, + /// 直到用户另开一份文稿才被无关刷新带回正文。 + @MainActor + func testCourseNoteLoadPublishesCompletionWithoutOpeningAnotherDocument() throws { + let fixture = try Fixture(name: "course-note-load-publish") + defer { fixture.remove() } + let store = WorkspaceStore( + workspaceDirectory: fixture.workspaceDirectory, + selectionAskThreadDefaults: fixture.selectionAskThreadDefaults, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + try store.configureCourseLibrary(at: fixture.importsDirectory) + let courseID = try store.createCourseInLibrary(title: "直接打开课程笔记") + let expected = "# 课程笔记定位\n\n无需先打开另一份文稿。" + let createdID = try store.waitForCourseFileOperation { + await store.createCourseNotebookNote( + courseID: courseID, + title: "课程笔记定位", + markdown: expected + ) + } + let noteID = try XCTUnwrap(createdID) + + store.activeNotebookItemID = nil + store.noteText = "" + store.notesByItemID.removeValue(forKey: noteID) + store.loadedCourseNoteTextByItemID.removeValue(forKey: noteID) + + var publishedAfterBodyAdoption = false + let observation = store.objectWillChange.sink { + if store.noteText == expected, store.activeNoteIsLoading { + publishedAfterBodyAdoption = true + } + } + defer { observation.cancel() } + + XCTAssertTrue(store.openCourseNote(noteID, in: courseID)) + XCTAssertTrue(store.activeNoteIsLoading) + let deadline = Date().addingTimeInterval(2) + while store.activeNoteIsLoading, Date() < deadline { + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + } + + XCTAssertFalse(store.activeNoteIsLoading) + XCTAssertEqual(store.noteText, expected) + XCTAssertTrue( + publishedAfterBodyAdoption, + "正文采用后必须再发布加载结束,不能等另开文稿触发刷新" + ) + } } diff --git a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift index 56b3cde86..d29d29a48 100644 --- a/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift +++ b/Tests/WeiBeiSafetyTests/CourseProjectRootSelfCheck.swift @@ -62,8 +62,8 @@ enum CourseProjectRootSelfCheck { try step("新建课程原子落盘") { try newCourseCreatesAtomicProjectAndManifest() } - try step("Markdown 单文件同时作为文稿与笔记") { - try markdownMaterialUsesOneItemInBothSurfaces() + try step("Markdown 资料保持文稿角色") { + try markdownMaterialStaysMaterialThroughImportRace() } try step("书签失效后仍按本机资料库相对路径打开文稿") { try brokenBookmarkStillOpensInLibraryCourseFile() @@ -174,8 +174,8 @@ enum CourseProjectRootSelfCheck { } @MainActor - private static func markdownMaterialUsesOneItemInBothSurfaces() throws { - let fixture = try Fixture(name: "markdown-dual-surface") + private static func markdownMaterialStaysMaterialThroughImportRace() throws { + let fixture = try Fixture(name: "markdown-material-role") defer { fixture.remove() } let library = try fixture.makeDirectory("课程资料库") let source = fixture.root.appendingPathComponent("第一讲.md") @@ -221,30 +221,21 @@ enum CourseProjectRootSelfCheck { "Markdown 导入失败" ) try check( - item.isCourseMaterial && item.isNotebookNote + item.isCourseMaterial && !item.isNotebookNote && store?.courseMaterials(in: courseID).map(\.id) == [item.id] - && store?.courseNotes(in: courseID).map(\.id) == [item.id] + && store?.courseNotes(in: courseID).isEmpty == true && store?.importedItems.filter({ $0.id == item.id }).count == 1, - "Markdown 没有以同一条目同时出现在文稿和笔记,或扫描竞态产生了重复条目" + "Markdown 资料被错误转成笔记,或扫描竞态产生了重复条目" ) try check(store?.openCourseMaterial(item.id, in: courseID) == true, "文稿入口无法打开") - store?.openCourseNote(item.id, in: courseID) - try store?.waitForCourseNoteLoadsForSelfCheck() - try check(store?.noteText.contains("原始内容") == true, "笔记入口首轮读盘后正文为空") - store?.updateNote("# 第一讲\n\n已同步更新") - store?.flushPendingNotePersistence() - try check( - try String(contentsOf: require(item.url, "Markdown 路径丢失"), encoding: .utf8) - .contains("已同步更新"), - "笔记编辑没有写回文稿对应的同一个文件" - ) try check(store?.flushPendingWorkspaceSave() == true, "工作区保存失败") store = makeStore(fixture: fixture) try check( store?.courseMaterials(in: courseID).map(\.id) == [item.id] - && store?.courseNotes(in: courseID).map(\.id) == [item.id] + && store?.courseNotes(in: courseID).isEmpty == true + && store?.importedItems.first(where: { $0.id == item.id })?.isNotebookNote == false && store?.importedItems.filter({ $0.id == item.id }).count == 1, - "重开后 Markdown 双入口或单文件身份丢失" + "重开后 Markdown 资料角色或单文件身份丢失" ) } diff --git a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift b/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift index cfb95c543..bf83fb656 100644 --- a/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift +++ b/Tests/WeiBeiSafetyTests/FileModelPhase0BaselineTests.swift @@ -57,7 +57,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "外删课") let source = base.appendingPathComponent("诗歌.md") try "原始正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let unsavedInput = "用户正在输入、尚未落盘的新内容" @@ -89,7 +89,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "冲突课") let source = base.appendingPathComponent("笔记.md") try "磁盘版本".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) @@ -171,7 +171,7 @@ final class FileModelPhase0BaselineTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "移除课") let source = base.appendingPathComponent("草稿.md") try "原稿".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) diff --git a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift b/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift index 07f45b5ed..c919c673a 100644 --- a/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/LibraryMigrationSafetyTests.swift @@ -393,7 +393,7 @@ final class LibraryMigrationSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "挂起课") let source = base.appendingPathComponent("笔记.md") try "原始内容".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) diff --git a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift index 219bfe12e..be8a29132 100644 --- a/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift +++ b/Tests/WeiBeiSafetyTests/LibraryRelativeOnlyTests.swift @@ -84,15 +84,32 @@ enum LibraryRelativeOnlyCheck { let source = outside.appendingPathComponent("讲义.txt") let sourceBytes = Data("hello-library\n".utf8) try sourceBytes.write(to: source) - let copiedCommon = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: source, isNote: false) + let copiedCommon = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: source, + isNote: false + ) + } XCTAssertEqual(FileManager.default.contents(atPath: source.path), sourceBytes) XCTAssertEqual(copiedCommon.deletingLastPathComponent().lastPathComponent, "通用资料") - let copiedCourse = try store.copyExternalFileIntoCourse(source, courseID: originalCourseID, isNote: false) + let courseImport = try store.importFileIntoCourseForSelfCheck( + source, + courseID: originalCourseID, + role: .material + ) + let copiedCourse = try XCTUnwrap(courseImport.item.url) XCTAssertEqual(FileManager.default.contents(atPath: source.path), sourceBytes) XCTAssertEqual(copiedCourse.deletingLastPathComponent().lastPathComponent, "文稿") XCTAssertNotEqual(copiedCommon.path, copiedCourse.path) - let same = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: source, isNote: false) + let same = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: source, + isNote: false + ) + } XCTAssertEqual(same.path, copiedCommon.path) let other = outside.appendingPathComponent("讲义-2.txt") try Data("different-content\n".utf8).write(to: other) @@ -101,7 +118,13 @@ enum LibraryRelativeOnlyCheck { let renamedSource = outside.appendingPathComponent("讲义.txt") try? FileManager.default.removeItem(at: renamedSource) try FileManager.default.moveItem(at: colliding, to: renamedSource) - let second = try WorkspaceStore.copyExternalFileIntoLibrary(root: library, sourceURL: renamedSource, isNote: false) + let second = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: renamedSource, + isNote: false + ) + } XCTAssertNotEqual(second.lastPathComponent, copiedCommon.lastPathComponent) XCTAssertEqual(FileManager.default.contents(atPath: copiedCommon.path), sourceBytes) @@ -208,15 +231,15 @@ enum LibraryInsideOnlyCheck { XCTAssertNil(store.resolvedLibraryURL(for: escapeItem)) let sharedBytes = Data("shared-in-library\n".utf8) - let commonURL = try WorkspaceStore.copyExternalFileIntoLibrary( - root: library, - sourceURL: { - let source = outside.appendingPathComponent("共享讲义.txt") - try sharedBytes.write(to: source) - return source - }(), - isNote: false - ) + let sharedSource = outside.appendingPathComponent("共享讲义.txt") + try sharedBytes.write(to: sharedSource) + let commonURL = try store.waitForCourseFileOperation { + try await store.copyExternalFileIntoLibrary( + root: library, + sourceURL: sharedSource, + isNote: false + ) + } let courseA = try store.createCourseInLibrary(title: "共享甲") let courseB = try store.createCourseInLibrary(title: "共享乙") let imported = importFilesAndWait(store, [commonURL], markdownAsNotes: false) diff --git a/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift b/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift index 78e64e6f1..aac009d72 100644 --- a/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift +++ b/Tests/WeiBeiSafetyTests/PoetryIncidentRegressionTests.swift @@ -62,7 +62,7 @@ final class PoetryIncidentRegressionTests: XCTestCase { ) throws -> (item: StudyItem, url: URL) { let source = base.appendingPathComponent("诗歌.md") try "# 诗歌\n\n真实正文:山川异域,风月同天。".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) return (imported.item, url) } diff --git a/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift b/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift index 2a78c1e6b..c61a4906d 100644 --- a/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift +++ b/Tests/WeiBeiSafetyTests/SidebarPerformanceTests.swift @@ -198,6 +198,77 @@ final class SidebarPerformanceTests: XCTestCase { withExtendedLifetime((workspaceObservation, drawerObservation, model)) {} } + @MainActor + func testRecentBatchClearsExistingSearchAndTargetsFirstVisibleRow() { + let fixture = makeStore(itemCount: 0) + defer { try? FileManager.default.removeItem(at: fixture.root) } + let course = Course(title: "批量课") + let courseMaterial = StudyItem( + id: "recent-course-material", + title: "课程文稿", + subtitle: "course.txt", + kind: .text, + urlPath: nil, + isSample: false + ) + let courseNote = StudyItem( + id: "recent-course-note", + title: "课程笔记", + subtitle: "course-note.md", + kind: .markdown, + urlPath: nil, + isSample: false, + isNotebookNote: true + ) + let commonMaterial = StudyItem( + id: "recent-common-material", + title: "通用资料", + subtitle: "common.txt", + kind: .text, + urlPath: nil, + isSample: false + ) + let commonNote = StudyItem( + id: "recent-common-note", + title: "独立笔记", + subtitle: "common-note.md", + kind: .markdown, + urlPath: nil, + isSample: false, + isNotebookNote: true + ) + fixture.store.courses = [course] + fixture.store.importedItems = [courseMaterial, courseNote, commonMaterial, commonNote] + fixture.store.courseItemMemberships = [ + CourseItemMembership(courseID: course.id, itemID: courseMaterial.id), + CourseItemMembership(courseID: course.id, itemID: courseNote.id), + ] + fixture.store.activeCourseID = course.id + let model = CourseSidebarModel(store: fixture.store) + + XCTAssertEqual( + model.firstVisibleItemID(in: [courseNote.id, courseMaterial.id]), + courseMaterial.id + ) + XCTAssertEqual( + model.firstVisibleItemID(in: [commonNote.id, commonMaterial.id]), + commonMaterial.id + ) + + model.updateQuery("不会匹配") + pumpMainRunLoop() + fixture.store.librarySearch = "" + fixture.store.recentlyImportedItemIDs = [commonMaterial.id, commonNote.id] + pumpMainRunLoop() + + XCTAssertEqual(model.query, "") + XCTAssertEqual(model.recentlyImportedItemIDs, [commonMaterial.id, commonNote.id]) + XCTAssertEqual( + model.firstVisibleItemID(in: model.recentlyImportedItemIDs), + commonMaterial.id + ) + } + @MainActor func testDrawerEscapeClearsSearchBeforeDismissal() { let fixture = makeStore(itemCount: 0) diff --git a/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift b/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift index 9fe1af779..cf1d1fab2 100644 --- a/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/TransientToleranceSafetyTests.swift @@ -109,7 +109,7 @@ final class TransientToleranceSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "断链课") let source = base.appendingPathComponent("笔记.md") try "原始正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) @@ -181,7 +181,7 @@ final class TransientToleranceSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "横幅课") let source = base.appendingPathComponent("笔记.md") try "正文".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let backingURL = try XCTUnwrap(store.resolvedLibraryURL(for: item)) store.select(itemID: item.id) diff --git a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift index 693cf2825..eb4b4ffc7 100644 --- a/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift +++ b/Tests/WeiBeiSafetyTests/WriteGateSafetyTests.swift @@ -1,3 +1,4 @@ +import Combine import Foundation @testable import WeiBei import WeiBeiCore @@ -48,7 +49,7 @@ final class WriteGateSafetyTests: XCTestCase { let source = base.appendingPathComponent("\(fileName ?? "笔记-\(UUID().uuidString)").md") try content.write(to: source, atomically: true, encoding: .utf8) let imported = try store.importFileIntoCourseForSelfCheck( - source, courseID: courseID, role: .material + source, courseID: courseID, role: .note ) let url = try XCTUnwrap(store.resolvedLibraryURL(for: imported.item)) return (imported.item, url) @@ -108,6 +109,8 @@ final class WriteGateSafetyTests: XCTestCase { let store = try makeStore(base: base, library: library, backupRoot: backupRoot) let courseID = try store.createCourseInLibrary(title: "闸门课") let (item, url) = try importNote(store, base: base, courseID: courseID, content: "原始内容") + // 真实笔记导入会建立可信基线;本场景专门验证“没有基线且无法重读”。 + store.noteBackingContentDigestsByItemID[item.id] = nil try FileManager.default.setAttributes([.posixPermissions: 0o000], ofItemAtPath: url.path) defer { try? FileManager.default.setAttributes([.posixPermissions: 0o644], ofItemAtPath: url.path) } @@ -192,6 +195,38 @@ final class WriteGateSafetyTests: XCTestCase { XCTAssertEqual(store.lastSelfWrittenNoteDigestsByItemID[item.id], Self.digest(of: "第二版")) } + func testGateAdoptsIdenticalExternalDiskContentWithoutConflict() throws { + let base = makeTempRoot("weibei-gate-identical-external-content") + defer { try? FileManager.default.removeItem(at: base) } + let backupRoot = base.appendingPathComponent("backups", isDirectory: true) + let store = WorkspaceStore( + workspaceDirectory: base.appendingPathComponent("workspace", isDirectory: true), + noteBackupRootURL: backupRoot, + startsAtBlankEntries: true, + startsCourseFileMaintenance: false + ) + let original = "# 原文\n\n这是原始正文。\n" + let external = original + "\n这句来自应用外部。\n" + let itemID = "imported:identical-external-content" + let url = base.appendingPathComponent("合成笔记.md") + + try original.write(to: url, atomically: true, encoding: .utf8) + try external.write(to: url, atomically: true, encoding: .utf8) + + XCTAssertNoThrow( + try store.writeNotebookMarkdownThroughGate( + external, + itemID: itemID, + url: url, + expectedBaseline: Self.digest(of: original) + ), + "干净快照与当前磁盘正文完全一致时,旧基线不应制造外部修改冲突" + ) + XCTAssertEqual(try String(contentsOf: url, encoding: .utf8), external) + XCTAssertEqual(store.noteBackingContentDigestsByItemID[itemID], Self.digest(of: external)) + XCTAssertEqual(store.lastSelfWrittenNoteDigestsByItemID[itemID], Self.digest(of: external)) + } + func testRenameRewriteRoutesThroughGate() throws { let base = makeTempRoot("weibei-gate-rename") defer { try? FileManager.default.removeItem(at: base) } @@ -254,7 +289,7 @@ final class WriteGateSafetyTests: XCTestCase { let courseID = try store.createCourseInLibrary(title: "闸门课") let source = base.appendingPathComponent("笔记.md") try "第一版".write(to: source, atomically: true, encoding: .utf8) - let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .material) + let imported = try store.importFileIntoCourseForSelfCheck(source, courseID: courseID, role: .note) let item = imported.item let url = try XCTUnwrap(store.resolvedLibraryURL(for: item)) store.noteEditingSession.replaceDocument(with: item.id) @@ -394,6 +429,68 @@ final class WriteGateSafetyTests: XCTestCase { XCTAssertTrue(store.noteText.contains("磁盘上的新内容")) } + func testAtomicExternalEditAdoptsDiskAfterSwitchingAwayAndBack() throws { + let base = makeTempRoot("weibei-external-adopt-after-switch") + defer { try? FileManager.default.removeItem(at: base) } + let store = try makeStore( + base: base, + library: base.appendingPathComponent("资料库"), + backupRoot: base.appendingPathComponent("backups") + ) + let courseID = try store.createCourseInLibrary(title: "外部修改课") + let original = "# 合成笔记\n\n原始正文\n" + let external = original + "\n外部修改验收:正文已从磁盘更新,界面应自动采用。\n" + let target = try importNote( + store, base: base, courseID: courseID, + content: original, fileName: "合成笔记" + ) + let other = try importNote( + store, base: base, courseID: courseID, + content: "# 01\n\n另一份笔记\n", fileName: "01" + ) + + XCTAssertTrue(store.openCourseNote(target.item.id, in: courseID)) + waitForCourseNoteLoad(store, itemID: target.item.id) + store.noteEditingSession.replaceDocument(with: target.item.id) + XCTAssertEqual(store.noteText, original) + + var completionPublished = false + let observation = store.objectWillChange.sink { + if store.activeNoteItemID == target.item.id, + store.noteText == external, + !store.activeNoteIsLoading { + completionPublished = true + } + } + defer { observation.cancel() } + + try external.write(to: target.url, atomically: true, encoding: .utf8) + XCTAssertTrue(store.openCourseNote(other.item.id, in: courseID)) + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + XCTAssertTrue(store.openCourseNote(target.item.id, in: courseID)) + waitForCourseNoteLoad(store, itemID: target.item.id) + + XCTAssertFalse(store.activeNoteIsLoading, "返回后不能一直停在无编辑器的载入态") + XCTAssertEqual(store.activeNoteItemID, target.item.id) + XCTAssertEqual(store.noteText, external) + XCTAssertTrue( + completionPublished, + "外部正文采用并结束读盘后必须再发布一次,否则笔记栏仍停在无编辑器的载入画面" + ) + } + + private func waitForCourseNoteLoad( + _ store: WorkspaceStore, + itemID: String, + timeout: TimeInterval = 2 + ) { + let deadline = Date().addingTimeInterval(timeout) + while store.courseNoteLoadTasksByItemID[itemID] != nil, + Date() < deadline { + RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.01)) + } + } + func testUserNamedNoteKeepsFileNameAfterHeadingSave() throws { let base = makeTempRoot("weibei-named-note") defer { try? FileManager.default.removeItem(at: base) }