Compare commits

...

4 Commits

7 changed files with 239 additions and 108 deletions

View File

@ -152,7 +152,7 @@ nonisolated struct CollectionSnapshot: Identifiable, Hashable, Sendable, Codable
let childDirectoryCount: Int
let fingerprint: String
var id: String { folderName }
var id: String { "\(folderName)::\(fingerprint)" }
}
nonisolated struct SourceSnapshot: Hashable, Sendable, Codable {

View File

@ -76,11 +76,19 @@ nonisolated struct SourceCandidate: Identifiable, Hashable, Sendable {
var id: String {
[
providerID,
sourceRootURL.standardizedFileURL.absoluteString
sourceIdentityKey(for: sourceRootURL)
].joined(separator: "::")
}
}
nonisolated func sourceIdentityKey(for url: URL) -> String {
if url.isFileURL {
return url.standardizedFileURL.resolvingSymlinksInPath().path.lowercased()
}
return url.standardized.absoluteString.lowercased()
}
nonisolated enum WorkStageState: String, Hashable, Sendable, Codable {
case pending
case running

View File

@ -965,7 +965,7 @@ enum JavaContentScanner {
under root: URL,
providerID: PlatformProviderID
) -> [SourceCandidate] {
let uniqueCandidates = Dictionary(grouping: candidates, by: \.sourceRootURL).compactMap { _, groupedCandidates in
let uniqueCandidates = Dictionary(grouping: candidates, by: { sourceIdentityKey(for: $0.sourceRootURL) }).compactMap { _, groupedCandidates in
groupedCandidates.max { lhs, rhs in
lhs.confidence < rhs.confidence
}
@ -1066,7 +1066,7 @@ enum JavaContentScanner {
while !queue.isEmpty && folders.count < maxFolderCount {
let current = queue.removeFirst()
let normalizedURL = current.url.standardizedFileURL
guard seen.insert(normalizedURL.path).inserted else {
guard seen.insert(sourceIdentityKey(for: normalizedURL)).inserted else {
continue
}
@ -1121,7 +1121,7 @@ enum JavaContentScanner {
for url in urls {
let standardizedURL = url.standardizedFileURL
guard seen.insert(standardizedURL.path).inserted else {
guard seen.insert(sourceIdentityKey(for: standardizedURL)).inserted else {
continue
}

View File

@ -183,9 +183,9 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
let providerID = probe?.providerID ?? LocalFolderSourceAccess().accessorIdentifier
let edition = probe?.edition ?? .bedrock
if sources.contains(where: { $0.id == normalizedURL }) {
sourceCandidates.removeAll { $0.sourceRootURL == normalizedURL }
updateSource(normalizedURL) { source in
if let existingSourceID = existingSourceID(matching: normalizedURL) {
sourceCandidates.removeAll { sourceIdentityKey(for: $0.sourceRootURL) == sourceIdentityKey(for: normalizedURL) }
updateSource(existingSourceID) { source in
if source.bookmarkData == nil {
source.bookmarkData = bookmarkData
}
@ -204,8 +204,8 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
}
}
}
startScan(for: normalizedURL, mode: .fullScan)
return normalizedURL
startScan(for: existingSourceID, mode: .fullScan)
return existingSourceID
}
var source = MinecraftSource(
@ -224,7 +224,7 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
source.scanDiagnostic = warning
}
let sourceID = addSource(source, shouldPersist: true, shouldScan: true)
sourceCandidates.removeAll { $0.sourceRootURL == sourceID }
sourceCandidates.removeAll { sourceIdentityKey(for: $0.sourceRootURL) == sourceIdentityKey(for: sourceID) }
return sourceID
}
@ -232,8 +232,8 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
let normalizedURL = candidate.sourceRootURL.standardizedFileURL
let bookmarkData = securityScopedBookmarkData(for: normalizedURL)
if sources.contains(where: { $0.id == normalizedURL }) {
updateSource(normalizedURL) { source in
if let existingSourceID = existingSourceID(matching: normalizedURL) {
updateSource(existingSourceID) { source in
if source.bookmarkData == nil {
source.bookmarkData = bookmarkData
}
@ -247,9 +247,9 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
source.displayName = candidate.displayName
source.capabilities = source.origin.defaultCapabilities
}
sourceCandidates.removeAll { $0.id == candidate.id || $0.sourceRootURL == normalizedURL }
startScan(for: normalizedURL, mode: .fullScan)
return normalizedURL
removeSourceCandidates(matching: candidate, sourceID: existingSourceID)
startScan(for: existingSourceID, mode: .fullScan)
return existingSourceID
}
var source = MinecraftSource(
@ -266,14 +266,14 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
source.displayName = candidate.displayName
let sourceID = addSource(source, shouldPersist: true, shouldScan: true)
sourceCandidates.removeAll { $0.id == candidate.id || $0.sourceRootURL == sourceID }
removeSourceCandidates(matching: candidate, sourceID: sourceID)
return sourceID
}
@discardableResult
func addSource(_ source: MinecraftSource, shouldPersist: Bool = false, shouldScan: Bool = true) -> URL {
if sources.contains(where: { $0.id == source.id }) {
updateSource(source.id) { existingSource in
if let existingSourceID = existingSourceID(matching: source.id) {
updateSource(existingSourceID) { existingSource in
existingSource.origin = source.origin
existingSource.accessDescriptor = source.accessDescriptor
existingSource.providerID = source.accessDescriptor.accessorIdentifier
@ -300,13 +300,13 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
}
if shouldPersist {
persistSourceIfAvailable(withID: source.id)
persistSourceIfAvailable(withID: existingSourceID(matching: source.id) ?? source.id)
}
if shouldScan {
startScan(for: source.id, mode: .fullScan)
startScan(for: existingSourceID(matching: source.id) ?? source.id, mode: .fullScan)
}
return source.id
return existingSourceID(matching: source.id) ?? source.id
}
func source(withID sourceID: URL) -> MinecraftSource? {
@ -704,8 +704,26 @@ final class SourceLibrary: ObservableObject, SourceScanSessionHosting, SourcePer
private func candidateAlreadyAdded(_ candidate: SourceCandidate) -> Bool {
sources.contains { source in
source.id == candidate.sourceRootURL.standardizedFileURL
|| source.folderURL == candidate.sourceRootURL.standardizedFileURL
sourceIdentityKey(for: source.id) == sourceIdentityKey(for: candidate.sourceRootURL)
|| sourceIdentityKey(for: source.folderURL) == sourceIdentityKey(for: candidate.sourceRootURL)
}
}
private func existingSourceID(matching url: URL) -> URL? {
let identity = sourceIdentityKey(for: url)
return sources.first { source in
sourceIdentityKey(for: source.id) == identity
|| sourceIdentityKey(for: source.folderURL) == identity
}?.id
}
private func removeSourceCandidates(matching candidate: SourceCandidate, sourceID: URL) {
let candidateIdentity = sourceIdentityKey(for: candidate.sourceRootURL)
let sourceIdentity = sourceIdentityKey(for: sourceID)
sourceCandidates.removeAll {
$0.id == candidate.id
|| sourceIdentityKey(for: $0.sourceRootURL) == candidateIdentity
|| sourceIdentityKey(for: $0.sourceRootURL) == sourceIdentity
}
}

View File

@ -214,20 +214,18 @@ enum SourceRestoration {
_ currentCollections: [CollectionSnapshot],
persistedCollections: [CollectionSnapshot]
) -> Bool {
let currentCollectionsByName = Dictionary(
uniqueKeysWithValues: currentCollections.map { ($0.folderName, $0) }
)
let persistedCollectionsByName = Dictionary(
uniqueKeysWithValues: persistedCollections.map { ($0.folderName, $0) }
)
let currentCollectionsByName = Dictionary(grouping: currentCollections, by: \.folderName)
.mapValues { $0.map(\.fingerprint).sorted() }
let persistedCollectionsByName = Dictionary(grouping: persistedCollections, by: \.folderName)
.mapValues { $0.map(\.fingerprint).sorted() }
if currentCollectionsByName.count != persistedCollectionsByName.count {
return true
}
for (folderName, persistedCollection) in persistedCollectionsByName {
guard let currentCollection = currentCollectionsByName[folderName],
currentCollection.fingerprint == persistedCollection.fingerprint else {
for (folderName, persistedFingerprints) in persistedCollectionsByName {
guard let currentFingerprints = currentCollectionsByName[folderName],
currentFingerprints == persistedFingerprints else {
return true
}
}

View File

@ -29,6 +29,21 @@ struct SidebarFilter: Identifiable, Hashable {
let selection: SidebarSelection
}
private struct SidebarNode: Identifiable, Hashable {
let id: SidebarSelection
let row: SidebarNodeRow
let children: [SidebarNode]?
var selection: SidebarSelection { id }
}
private enum SidebarNodeRow: Hashable {
case source(MinecraftSource)
case filter(SidebarFilter)
case connectedDevice(ConnectedDeviceSidebarEntry)
case sourceCandidate(SourceCandidate)
}
struct SourcesSidebarView: View {
let sources: [MinecraftSource]
let connectedDevices: [ConnectedDeviceSidebarEntry]
@ -46,42 +61,25 @@ struct SourcesSidebarView: View {
var body: some View {
List(selection: $selection) {
if !sources.isEmpty {
if !libraryNodes.isEmpty {
Section {
ForEach(sources) { source in
sourceSectionRows(for: source)
}
OutlineGroup(libraryNodes, children: \.children, content: sidebarNodeRow)
} header: {
SidebarSourcesSectionHeaderView(title: "Libraries")
}
}
if !connectedDevices.isEmpty {
if !deviceNodes.isEmpty {
Section {
ForEach(connectedDevices) { entry in
connectedDeviceSectionRows(for: entry)
}
OutlineGroup(deviceNodes, children: \.children, content: sidebarNodeRow)
} header: {
SidebarSourcesSectionHeaderView(title: "Available Devices")
}
}
if !sourceCandidates.isEmpty {
if !candidateNodes.isEmpty {
Section {
ForEach(sourceCandidates) { candidate in
SourceCandidateRow(
candidate: candidate,
onSelect: {
selection = .sourceCandidate(candidateID: candidate.id)
},
addAction: {
addCandidateSourceAction(candidate)
}
)
.tag(SidebarSelection.sourceCandidate(candidateID: candidate.id) as SidebarSelection?)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8))
}
OutlineGroup(candidateNodes, children: \.children, content: sidebarNodeRow)
} header: {
SidebarSourcesSectionHeaderView(title: "Found Sources")
}
@ -118,19 +116,52 @@ struct SourcesSidebarView: View {
}
}
@ViewBuilder
private func sourceSectionRows(for source: MinecraftSource) -> some View {
let sourceFilters = filters(source)
SourceHeaderRow(
source: source,
onSelect: {
selection = .source(sourceID: source.id)
}
private var libraryNodes: [SidebarNode] {
sources.map { source in
let childNodes = filters(source).map { filter in
SidebarNode(
id: filter.selection,
row: .filter(filter),
children: nil
)
.tag(SidebarSelection.source(sourceID: source.id) as SidebarSelection?)
}
return SidebarNode(
id: .source(sourceID: source.id),
row: .source(source),
children: childNodes.isEmpty ? nil : childNodes
)
}
}
private var deviceNodes: [SidebarNode] {
connectedDevices.map { entry in
SidebarNode(
id: .connectedDevice(deviceID: entry.id),
row: .connectedDevice(entry),
children: nil
)
}
}
private var candidateNodes: [SidebarNode] {
sourceCandidates.map { candidate in
SidebarNode(
id: .sourceCandidate(candidateID: candidate.id),
row: .sourceCandidate(candidate),
children: nil
)
}
}
@ViewBuilder
private func sidebarNodeRow(_ node: SidebarNode) -> some View {
switch node.row {
case .source(let source):
SourceHeaderRow(source: source)
.tag(node.selection as SidebarSelection?)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets(top: 6, leading: 0, bottom: 0, trailing: 0))
.listRowInsets(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8))
.contextMenu {
Button("Rescan \"\(source.displayName)\"") {
rescanSourceAction(source)
@ -142,33 +173,35 @@ struct SourcesSidebarView: View {
removeSourceAction(source)
}
}
ForEach(sourceFilters) { filter in
SidebarFilterRow(filter: filter, isIndented: true)
.tag(filter.selection as SidebarSelection?)
}
}
@ViewBuilder
private func connectedDeviceSectionRows(for entry: ConnectedDeviceSidebarEntry) -> some View {
case .filter(let filter):
SidebarFilterRow(filter: filter)
.tag(node.selection as SidebarSelection?)
case .connectedDevice(let entry):
ConnectedDeviceRow(
entry: entry,
onSelect: {
selection = .connectedDevice(deviceID: entry.id)
},
addAction: entry.hasMinecraftContainer ? {
addConnectedDeviceAction(entry)
} : nil
)
.tag(SidebarSelection.connectedDevice(deviceID: entry.id) as SidebarSelection?)
.tag(node.selection as SidebarSelection?)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets(top: 6, leading: 8, bottom: 0, trailing: 8))
case .sourceCandidate(let candidate):
SourceCandidateRow(
candidate: candidate,
addAction: {
addCandidateSourceAction(candidate)
}
)
.tag(node.selection as SidebarSelection?)
.listRowSeparator(.hidden)
.listRowInsets(EdgeInsets(top: 4, leading: 8, bottom: 4, trailing: 8))
}
}
}
private struct SourceCandidateRow: View {
let candidate: SourceCandidate
let onSelect: () -> Void
let addAction: () -> Void
var body: some View {
@ -195,8 +228,6 @@ private struct SourceCandidateRow: View {
.appMiniProminentButton()
.help("Add Source")
}
.contentShape(Rectangle())
.onTapGesture(perform: onSelect)
.padding(.vertical, 4)
}
@ -217,7 +248,6 @@ private struct SourceCandidateRow: View {
private struct SidebarFilterRow: View {
let filter: SidebarFilter
let isIndented: Bool
var body: some View {
HStack(spacing: 10) {
@ -232,7 +262,6 @@ private struct SidebarFilterRow: View {
Text(filter.count, format: .number)
.foregroundStyle(.secondary)
}
.padding(.leading, isIndented ? 16 : 0)
}
}
@ -246,7 +275,6 @@ private struct SidebarSourcesSectionHeaderView: View {
private struct SourceHeaderRow: View {
let source: MinecraftSource
let onSelect: () -> Void
var body: some View {
HStack(spacing: 8) {
@ -273,10 +301,8 @@ private struct SourceHeaderRow: View {
}
}
.frame(maxWidth: .infinity, alignment: .leading)
.padding(.leading, 5)
.padding(.vertical, 6)
.contentShape(Rectangle())
.onTapGesture(perform: onSelect)
.padding(.horizontal, 8)
.padding(.vertical, 5)
}
private var connection: DeviceConnection? {
@ -400,7 +426,6 @@ private struct CircularScanProgressView: View {
private struct ConnectedDeviceRow: View {
let entry: ConnectedDeviceSidebarEntry
let onSelect: () -> Void
let addAction: (() -> Void)?
var body: some View {
@ -430,8 +455,6 @@ private struct ConnectedDeviceRow: View {
}
}
.opacity(addAction == nil ? 0.68 : 1)
.contentShape(Rectangle())
.onTapGesture(perform: onSelect)
}
private var iconName: String {

View File

@ -385,6 +385,36 @@ struct World_Manager_for_MinecraftTests {
#expect(candidates.first?.detectedKinds.contains(.mod) == true)
}
@Test func javaProviderDeduplicatesCaseVariantSourceRoots() async throws {
let fileManager = FileManager.default
let workingURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
let upperRootURL = workingURL.appendingPathComponent("CurseForge/Minecraft", isDirectory: true)
let lowerRootURL = workingURL.appendingPathComponent("curseforge/minecraft", isDirectory: true)
let firstInstanceURL = upperRootURL.appendingPathComponent("Instances/ExampleOne", isDirectory: true)
let secondInstanceURL = upperRootURL.appendingPathComponent("Instances/ExampleTwo", isDirectory: true)
defer { try? fileManager.removeItem(at: workingURL) }
for instanceURL in [firstInstanceURL, secondInstanceURL] {
try fileManager.createDirectory(
at: instanceURL.appendingPathComponent("mods", isDirectory: true),
withIntermediateDirectories: true
)
try Data("jar".utf8).write(to: instanceURL.appendingPathComponent("mods/ExampleMod.jar"))
}
guard fileManager.fileExists(atPath: lowerRootURL.path) else {
return
}
let candidates = JavaContentScanner.discoverSourceCandidates(
providerID: JavaLocalFolderSourceAccess().accessorIdentifier,
searchRoots: [upperRootURL, lowerRootURL]
)
#expect(candidates.count == 1)
#expect(sourceIdentityKey(for: candidates[0].sourceRootURL) == sourceIdentityKey(for: upperRootURL))
}
@Test func javaAggregateRootDiscoversNestedInstanceItems() async throws {
let fileManager = FileManager.default
let workingURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
@ -413,6 +443,60 @@ struct World_Manager_for_MinecraftTests {
#expect(snapshots.map(\.folderName).contains("a/e/f/resourcepacks"))
}
@Test func sourceRestorationComparesDuplicateCollectionNamesWithoutCrashing() async throws {
let fileManager = FileManager.default
let workingURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)
defer { try? fileManager.removeItem(at: workingURL) }
try fileManager.createDirectory(at: workingURL, withIntermediateDirectories: true)
let collectionSnapshots = [
CollectionSnapshot(
folderName: "mods",
modifiedDate: Date(timeIntervalSince1970: 100),
childDirectoryCount: 1,
fingerprint: "a/b/c/mods::1::100"
),
CollectionSnapshot(
folderName: "mods",
modifiedDate: Date(timeIntervalSince1970: 200),
childDirectoryCount: 2,
fingerprint: "x/y/z/mods::2::200"
)
]
var source = MinecraftSource(
folderURL: workingURL,
origin: .javaLocalFolder(bookmarkData: nil),
accessDescriptor: SourceAccessDescriptor(
accessorIdentifier: JavaLocalFolderSourceAccess().accessorIdentifier,
kind: .localFolder,
refreshStrategy: .eagerFullScan
),
availability: .available
)
source.edition = .java
source.snapshot = SourceSnapshot(
sourceID: workingURL,
rootModifiedDate: nil,
collectionSnapshots: collectionSnapshots,
itemSnapshots: []
)
#expect(SourceRestoration.needsReconcile(source) { _, _ in collectionSnapshots } == false)
#expect(
SourceRestoration.needsReconcile(source) { _, _ in
[
collectionSnapshots[0],
CollectionSnapshot(
folderName: "mods",
modifiedDate: Date(timeIntervalSince1970: 300),
childDirectoryCount: 3,
fingerprint: "x/y/z/mods::3::300"
)
]
} == true
)
}
@Test func sourceLibraryAddSourceCandidatePreservesJavaAggregateProvider() async throws {
let fileManager = FileManager.default
let workingURL = fileManager.temporaryDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true)