Skip to content

armgit / cra

Public Imported from GitHub
0

The open-source Arc replacement for macOS. Spaces, pinned tabs, split view, Little Windows and Arc's shortcuts on Chromium, with your Arc sidebar imported in one go.

Library ▸ Downloads lists downloads still running, with their progress (#245)

Victor1b29a73334fc
diff --git a/Packages/CraCore/Sources/CraCore/DownloadList.swift b/Packages/CraCore/Sources/CraCore/DownloadList.swift
new file mode 100644
index 0000000..6b97815
--- /dev/null
+++ b/Packages/CraCore/Sources/CraCore/DownloadList.swift
@@ -0,0 +1,99 @@
+import Foundation
+
+/// The downloads Cra lists: finished files (kept in downloads.json) and downloads Chromium is still
+/// reporting on, or that ended without a file (this session only). Two places show them: the tray
+/// over the Library button and Library ▸ Downloads.
+public enum DownloadList {
+ /// A finished download, as saved in downloads.json.
+ public struct Entry: Codable, Identifiable, Equatable, Sendable {
+ public let id: UUID
+ public var path: String
+ public var date: Date
+
+ public init(id: UUID, path: String, date: Date) {
+ self.id = id
+ self.path = path
+ self.date = date
+ }
+
+ public var name: String { (path as NSString).lastPathComponent }
+ }
+
+ /// A download Chromium is still reporting on, or one that ended without a file.
+ public struct Live: Identifiable, Equatable, Sendable {
+ public let id: UInt32
+ public var name: String
+ public var path: String
+ public var started: Date
+ public var received: Int64
+ public var total: Int64
+ public var percent: Int
+ public var bytesPerSecond: Double?
+ /// The last point the speed was measured from.
+ public var sampleBytes: Int64 = 0
+ public var sampleAt = Date.distantPast
+ public var failed = false
+ public var cancelled = false
+ /// When Chromium last reported on it.
+ public var updated: Date
+
+ public init(id: UInt32, name: String, path: String, started: Date, received: Int64, total: Int64, percent: Int, updated: Date) {
+ self.id = id
+ self.name = name
+ self.path = path
+ self.started = started
+ self.received = received
+ self.total = total
+ self.percent = percent
+ self.updated = updated
+ }
+
+ public var running: Bool { !failed && !cancelled }
+ public var row: DownloadRow.State {
+ failed ? .failed : cancelled ? .cancelled : .downloading(received: received, total: total, bytesPerSecond: bytesPerSecond)
+ }
+ }
+
+ /// A row in either list.
+ public enum Listed: Identifiable, Equatable, Sendable {
+ case finished(Entry)
+ case live(Live)
+
+ public var id: String {
+ switch self {
+ case .finished(let e): return e.id.uuidString
+ case .live(let l): return "live-\(l.id)"
+ }
+ }
+ public var date: Date {
+ switch self {
+ case .finished(let e): return e.date
+ case .live(let l): return l.started
+ }
+ }
+ public var name: String {
+ switch self {
+ case .finished(let e): return e.name
+ case .live(let l): return l.name
+ }
+ }
+ }
+
+ /// The tray: the newest `limit` downloads, oldest first: files still on disk, and running,
+ /// failed or cancelled ones.
+ public static func tray(entries: [Entry], live: [Live], limit: Int, fileExists: (String) -> Bool) -> [Listed] {
+ let finished = entries.filter { fileExists($0.path) }.map(Listed.finished)
+ return Array((finished + live.map(Listed.live)).sorted { $0.date < $1.date }.suffix(limit))
+ }
+
+ /// Library ▸ Downloads, newest first, narrowed to names containing `query`: the same rows as the
+ /// tray, without its limit. A running download is listed too, with its progress (#245); before,
+ /// the page showed only finished files, so the one being downloaded was missing exactly where
+ /// people go to look for it.
+ public static func library(entries: [Entry], live: [Live], query: String, fileExists: (String) -> Bool) -> [Listed] {
+ let needle = query.lowercased().trimmingCharacters(in: .whitespaces)
+ let finished = entries.filter { fileExists($0.path) }.map(Listed.finished)
+ let all = (finished + live.map(Listed.live)).sorted { $0.date > $1.date }
+ return needle.isEmpty ? all : all.filter { $0.name.lowercased().contains(needle) }
+ }
+}
diff --git a/Packages/CraCore/Tests/CraCoreTests/DownloadListTests.swift b/Packages/CraCore/Tests/CraCoreTests/DownloadListTests.swift
new file mode 100644
index 0000000..c4b2fc7
--- /dev/null
+++ b/Packages/CraCore/Tests/CraCoreTests/DownloadListTests.swift
@@ -0,0 +1,43 @@
+import CraCore
+import Foundation
+import Testing
+
+/// What the downloads tray and Library ▸ Downloads list.
+struct DownloadListTests {
+ let t0 = Date(timeIntervalSince1970: 1_800_000_000)
+
+ func entry(_ name: String, at s: TimeInterval) -> DownloadList.Entry {
+ DownloadList.Entry(id: UUID(), path: "/Downloads/" + name, date: t0.addingTimeInterval(s))
+ }
+
+ func live(_ id: UInt32, _ name: String, at s: TimeInterval, failed: Bool = false) -> DownloadList.Live {
+ var l = DownloadList.Live(id: id, name: name, path: "", started: t0.addingTimeInterval(s), received: 172_200_000,
+ total: 257_100_000, percent: 66, updated: t0.addingTimeInterval(s))
+ l.failed = failed
+ return l
+ }
+
+ /// A download still running shows on Library ▸ Downloads, not only in the tray, with the ones
+ /// that failed this session; newest first, next to the finished files still on disk.
+ @Test(.bug("https://github.com/VictorKildahl/cra/issues/245"))
+ func libraryListsRunningDownloads() {
+ let old = entry("report.pdf", at: 0), gone = entry("deleted.zip", at: 10), done = entry("photo.jpg", at: 20)
+ let rows = DownloadList.library(entries: [old, gone, done], live: [live(7, "big.dmg", at: 30), live(8, "broken.iso", at: 5, failed: true)],
+ query: "", fileExists: { $0 != gone.path })
+ #expect(rows.map(\.name) == ["big.dmg", "photo.jpg", "broken.iso", "report.pdf"])
+ #expect(rows.first == .live(live(7, "big.dmg", at: 30)))
+ }
+
+ @Test func librarySearchMatchesRunningAndFinishedNames() {
+ let rows = DownloadList.library(entries: [entry("Invoice-March.pdf", at: 0), entry("cat.png", at: 1)],
+ live: [live(1, "invoice-april.pdf", at: 2)], query: " INVOICE ", fileExists: { _ in true })
+ #expect(rows.map(\.name) == ["invoice-april.pdf", "Invoice-March.pdf"])
+ }
+
+ /// The tray keeps the newest few, oldest at the top, live rows included (Arc's tray).
+ @Test func trayKeepsTheNewestOldestFirst() {
+ let rows = DownloadList.tray(entries: [entry("a", at: 0), entry("b", at: 1), entry("c", at: 3)], live: [live(1, "d", at: 2)],
+ limit: 3, fileExists: { $0 != "/Downloads/c" })
+ #expect(rows.map(\.name) == ["a", "b", "d"])
+ }
+}
diff --git a/Sources/Cra/Services/DownloadHistory.swift b/Sources/Cra/Services/DownloadHistory.swift
index f712c7c..fccf143 100644
--- a/Sources/Cra/Services/DownloadHistory.swift
+++ b/Sources/Cra/Services/DownloadHistory.swift
@@ -3,19 +3,18 @@ import Observation
import QuickLookThumbnailing
/// Finished downloads, newest last, for the list Arc shows when you hover the Library
-/// button (its downloads tray). Kept in downloads.json; files deleted since drop out.
-/// Downloads still running, and ones that failed or were cancelled, are listed too (`live`,
-/// not saved): Arc shows progress and failures there, not in a toast.
+/// button (its downloads tray) and on Library ▸ Downloads. Kept in downloads.json; files deleted
+/// since drop out. Downloads still running, and ones that failed or were cancelled, are listed
+/// in both too (`live`, not saved): Arc shows progress and failures there, not in a toast. Which
+/// rows each list shows is `DownloadList` (CraCore).
@MainActor
@Observable
final class DownloadHistory {
static let shared = DownloadHistory()
- struct Entry: Codable, Identifiable, Equatable {
- let id: UUID
- var path: String
- var date: Date
- }
+ typealias Entry = DownloadList.Entry
+ typealias Live = DownloadList.Live
+ typealias Listed = DownloadList.Listed
/// Arc 1.170 listed every recent download it still had on disk (four, oldest at the
/// top); how many it shows at most was not observed.
@@ -31,56 +30,17 @@ final class DownloadHistory {
entries = file.load(or: { [] })
}
- /// A download Chromium is still reporting on, or one that ended without a file.
- struct Live: Identifiable, Equatable {
- let id: UInt32
- var name: String
- var path: String
- var started: Date
- var received: Int64
- var total: Int64
- var percent: Int
- var bytesPerSecond: Double?
- /// The last point the speed was measured from.
- var sampleBytes: Int64 = 0
- var sampleAt = Date.distantPast
- var failed = false
- var cancelled = false
- /// When Chromium last reported on it (see MainWindowController.checkStalledDownloads).
- var updated: Date
-
- var running: Bool { !failed && !cancelled }
- var row: DownloadRow.State {
- failed ? .failed : cancelled ? .cancelled : .downloading(received: received, total: total, bytesPerSecond: bytesPerSecond)
- }
- }
-
private(set) var live: [Live] = []
- /// A row in the hover list.
- enum Listed: Identifiable, Equatable {
- case finished(Entry)
- case live(Live)
-
- var id: String {
- switch self {
- case .finished(let e): return e.id.uuidString
- case .live(let l): return "live-\(l.id)"
- }
- }
- var date: Date {
- switch self {
- case .finished(let e): return e.date
- case .live(let l): return l.started
- }
- }
- }
-
/// The hover list: newest downloads, oldest first: files still on disk, and running, failed
/// or cancelled ones.
var recent: [Listed] {
- let finished = entries.filter { FileManager.default.fileExists(atPath: $0.path) }.map(Listed.finished)
- return Array((finished + live.map(Listed.live)).sorted { $0.date < $1.date }.suffix(Self.listLimit))
+ DownloadList.tray(entries: entries, live: live, limit: Self.listLimit) { FileManager.default.fileExists(atPath: $0) }
+ }
+
+ /// Library ▸ Downloads: every download, newest first, running ones included (#245).
+ func library(query: String) -> [Listed] {
+ DownloadList.library(entries: entries, live: live, query: query) { FileManager.default.fileExists(atPath: $0) }
}
var hasRunningDownloads: Bool { live.contains(where: \.running) }
diff --git a/Sources/Cra/UI/Sidebar/LibraryView.swift b/Sources/Cra/UI/Sidebar/LibraryView.swift
index fbe93b5..5013344 100644
--- a/Sources/Cra/UI/Sidebar/LibraryView.swift
+++ b/Sources/Cra/UI/Sidebar/LibraryView.swift
@@ -1,5 +1,6 @@
import AppKit
import SwiftUI
+import UniformTypeIdentifiers
/// The Library's pages Cra has, in the order of Arc's rail (which also lists Easels and Boosts).
enum LibraryPage: String, CaseIterable {
@@ -291,7 +292,7 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
case media([MediaLibrary.File])
case easel(id: UUID, title: String, edited: Date)
case boost(Boost)
- case download(DownloadHistory.Entry)
+ case download(DownloadHistory.Listed)
case archived(ArchivedItem)
}
@@ -382,6 +383,7 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
withObservationTracking {
_ = store.archive
_ = DownloadHistory.shared.entries
+ _ = DownloadHistory.shared.live
_ = DownloadHistory.shared.thumbnails.count
_ = MediaScanner.shared.files
_ = BoostStore.shared.boosts
@@ -414,8 +416,9 @@ private final class LibraryListView: NSView, NSTextFieldDelegate, NSTableViewDat
empty.show(symbol: "photo.on.rectangle", title: all.isEmpty ? "Nothing here yet!" : "No matches",
detail: all.isEmpty ? "Screenshots, pictures and videos in the folders you show appear here." : nil)
case .downloads:
- let all = DownloadHistory.shared.entries.reversed().filter { FileManager.default.fileExists(atPath: $0.path) }
- let shown = needle.isEmpty ? all : all.filter { ($0.path as NSString).lastPathComponent.lowercased().contains(needle) }
+ // Running, failed and cancelled downloads too, as in the tray (#245).
+ let all = DownloadHistory.shared.library(query: "")
+ let shown = needle.isEmpty ? all : DownloadHistory.shared.library(query: query)
for (label, entries) in Self.grouped(shown, date: \.date) {
out.append(.header(label))
out += entries.map { .download($0) }
@@ -657,7 +660,9 @@ extension LibraryListView: NSMenuDelegate {
}
menu.addItem(.separator())
MenuItems.add(menu, "Remove from Archive") { store.removeFromArchive(e.id) }
- case .download(let e):
+ case .download(.live):
+ break
+ case .download(.finished(let e)):
let url = URL(fileURLWithPath: e.path)
MenuItems.add(menu, "Open") { NSWorkspace.shared.open(url) }
MenuItems.add(menu, "Show in Finder") { NSWorkspace.shared.activateFileViewerSelecting([url]) }
@@ -704,7 +709,9 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
private let detail = NSTextField.sidebarLabel(size: 12)
private var tip: ArcTooltipAnchorView?
private var colors = SidebarColors()
+ /// A finished download's file: opened by a click, dragged out.
private var download: DownloadHistory.Entry?
+ private var isDownloadRow = false
private var restore: (() -> Void)?
private var downAt: NSPoint?
private var hovering = false { didSet { if hovering != oldValue { refreshHover() } } }
@@ -740,6 +747,7 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
func showArchived(_ e: ArchivedItem, icon image: NSImage?, colors: SidebarColors, restore: @escaping () -> Void) {
self.colors = colors
download = nil
+ isDownloadRow = false
self.restore = restore
let ink: NSColor = colors.isDark ? .white : .black
tile.layer?.contents = nil
@@ -759,6 +767,7 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
func showBoost(_ b: Boost, colors: SidebarColors, open: @escaping () -> Void) {
self.colors = colors
download = nil
+ isDownloadRow = false
restore = open
let ink: NSColor = colors.isDark ? .white : .black
tile.layer?.contents = nil
@@ -777,6 +786,7 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
func showEasel(title text: String, edited: Date, colors: SidebarColors, open: @escaping () -> Void) {
self.colors = colors
download = nil
+ isDownloadRow = false
restore = open
let ink: NSColor = colors.isDark ? .white : .black
tile.layer?.contents = nil
@@ -792,13 +802,26 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
apply(ink: ink)
}
- func showDownload(_ e: DownloadHistory.Entry, colors: SidebarColors) {
+ /// A download on Library ▸ Downloads: a finished file (thumbnail, name, age) or one still
+ /// running, failed or cancelled (its type's icon, name, progress or what went wrong; #245).
+ func showDownload(_ listed: DownloadHistory.Listed, colors: SidebarColors) {
self.colors = colors
- download = e
+ isDownloadRow = true
restore = nil
let ink: NSColor = colors.isDark ? .white : .black
icon.isHidden = true
- if let image = DownloadHistory.shared.thumbnail(for: e.path) {
+ let image: NSImage?
+ switch listed {
+ case .finished(let e):
+ download = e
+ image = DownloadHistory.shared.thumbnail(for: e.path)
+ detail.stringValue = Self.age.localizedString(for: min(e.date, Date()), relativeTo: Date())
+ case .live(let l):
+ download = nil
+ image = NSWorkspace.shared.icon(for: UTType(filenameExtension: (l.name as NSString).pathExtension) ?? .data)
+ detail.stringValue = DownloadRow.subtitle(l.row, now: Date())
+ }
+ if let image {
var rect = NSRect(x: 0, y: 0, width: 32, height: 32)
let scale = window?.backingScaleFactor ?? 2
tile.layer?.contents = image.cgImage(forProposedRect: &rect, context: nil, hints: [.ctm: AffineTransform(scale: scale)])
@@ -808,14 +831,14 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
tile.layer?.contents = nil
tile.layer?.backgroundColor = ink.withAlphaComponent(0.04).cgColor
}
- title.stringValue = (e.path as NSString).lastPathComponent
+ title.stringValue = listed.name
title.lineBreakMode = .byTruncatingMiddle
- detail.stringValue = Self.age.localizedString(for: min(e.date, Date()), relativeTo: Date())
tip?.text = ""
apply(ink: ink)
}
private func apply(ink: NSColor) {
+ alphaValue = 1 // a reused cell may come from a Boost that was off
title.textColor = ink.withAlphaComponent(0.82)
detail.textColor = ink.withAlphaComponent(0.55)
refreshHover()
@@ -831,7 +854,7 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
card.frame = bounds.insetBy(dx: 4, dy: 2)
let h = card.bounds.height
// Archived: 24 pt tile 9 pt in; download: 32 pt thumbnail 5 pt in; the text 10 pt after.
- let isDownload = download != nil
+ let isDownload = isDownloadRow
let t: CGFloat = isDownload ? 32 : 24
let x: CGFloat = isDownload ? 5 : 9
tile.frame = NSRect(x: x, y: (h - t) / 2, width: t, height: t)
@@ -870,7 +893,7 @@ private final class LibraryItemCell: NSView, NSDraggingSource {
override func mouseUp(with event: NSEvent) {
defer { downAt = nil }
guard downAt != nil, bounds.contains(convert(event.locationInWindow, from: nil)) else { return }
- if let download { NSWorkspace.shared.open(URL(fileURLWithPath: download.path)) } else { restore?() }
+ if let download { NSWorkspace.shared.open(URL(fileURLWithPath: download.path)) } else if !isDownloadRow { restore?() }
}
func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation {