Merge branch 'pr-143' into feature/download

e kind of a merge, maybe it will work if not then leave it
This commit is contained in:
Hariharan Mudaliar 2025-12-08 23:00:41 +05:30
commit c1d22581dc
No known key found for this signature in database
GPG key ID: D04F1C2B9194DDFC
10 changed files with 494 additions and 78 deletions

View file

@ -419,6 +419,7 @@
INFOPLIST_KEY_NSCameraUsageDescription = "We need your camera for Mirror mode"; INFOPLIST_KEY_NSCameraUsageDescription = "We need your camera for Mirror mode";
INFOPLIST_KEY_NSDesktopFolderUsageDescription = "Atoll needs access to save screenshots to your desktop."; INFOPLIST_KEY_NSDesktopFolderUsageDescription = "Atoll needs access to save screenshots to your desktop.";
INFOPLIST_KEY_NSDocumentsFolderUsageDescription = "Atoll needs access to save and read AI assistant files."; INFOPLIST_KEY_NSDocumentsFolderUsageDescription = "Atoll needs access to save and read AI assistant files.";
INFOPLIST_KEY_NSDownloadsFolderUsageDescription = "Atoll needs access to read files in the downloads folder.";
INFOPLIST_KEY_NSHumanReadableCopyright = ""; INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_NSLocationUsageDescription = "Atoll uses your location to display accurate lock screen weather."; INFOPLIST_KEY_NSLocationUsageDescription = "Atoll uses your location to display accurate lock screen weather.";
INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Atoll uses your location to display accurate lock screen weather."; INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Atoll uses your location to display accurate lock screen weather.";
@ -488,6 +489,7 @@
INFOPLIST_KEY_NSCameraUsageDescription = "We need your camera for Mirror mode"; INFOPLIST_KEY_NSCameraUsageDescription = "We need your camera for Mirror mode";
INFOPLIST_KEY_NSDesktopFolderUsageDescription = "Atoll needs access to save screenshots to your desktop."; INFOPLIST_KEY_NSDesktopFolderUsageDescription = "Atoll needs access to save screenshots to your desktop.";
INFOPLIST_KEY_NSDocumentsFolderUsageDescription = "Atoll needs access to save and read AI assistant files."; INFOPLIST_KEY_NSDocumentsFolderUsageDescription = "Atoll needs access to save and read AI assistant files.";
INFOPLIST_KEY_NSDownloadsFolderUsageDescription = "Atoll needs access to read files in the downloads folder.";
INFOPLIST_KEY_NSHumanReadableCopyright = ""; INFOPLIST_KEY_NSHumanReadableCopyright = "";
INFOPLIST_KEY_NSLocationUsageDescription = "Atoll uses your location to display accurate lock screen weather."; INFOPLIST_KEY_NSLocationUsageDescription = "Atoll uses your location to display accurate lock screen weather.";
INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Atoll uses your location to display accurate lock screen weather."; INFOPLIST_KEY_NSLocationWhenInUseUsageDescription = "Atoll uses your location to display accurate lock screen weather.";

View file

@ -28,6 +28,7 @@ struct ContentView: View {
@ObservedObject var privacyManager = PrivacyIndicatorManager.shared @ObservedObject var privacyManager = PrivacyIndicatorManager.shared
@ObservedObject var doNotDisturbManager = DoNotDisturbManager.shared @ObservedObject var doNotDisturbManager = DoNotDisturbManager.shared
@ObservedObject var lockScreenManager = LockScreenManager.shared @ObservedObject var lockScreenManager = LockScreenManager.shared
@State private var downloadManager = DownloadManager.shared
@Default(.enableStatsFeature) var enableStatsFeature @Default(.enableStatsFeature) var enableStatsFeature
@Default(.showCpuGraph) var showCpuGraph @Default(.showCpuGraph) var showCpuGraph
@ -465,6 +466,9 @@ struct ContentView: View {
ReminderLiveActivity() ReminderLiveActivity()
} else if (!coordinator.expandingView.show || coordinator.expandingView.type == .recording) && vm.notchState == .closed && (recordingManager.isRecording || !recordingManager.isRecorderIdle) && Defaults[.enableScreenRecordingDetection] && !vm.hideOnClosed { } else if (!coordinator.expandingView.show || coordinator.expandingView.type == .recording) && vm.notchState == .closed && (recordingManager.isRecording || !recordingManager.isRecorderIdle) && Defaults[.enableScreenRecordingDetection] && !vm.hideOnClosed {
RecordingLiveActivity() RecordingLiveActivity()
} else if (!coordinator.expandingView.show || coordinator.expandingView.type == .download) && vm.notchState == .closed && downloadManager.isDownloading && Defaults[.enableDownloadListener] && !vm.hideOnClosed {
DownloadLiveActivity()
.transition(.blurReplace.animation(.interactiveSpring(dampingFraction: 1.2)))
} else if (!coordinator.expandingView.show || coordinator.expandingView.type == .doNotDisturb) && vm.notchState == .closed && doNotDisturbManager.isDoNotDisturbActive && Defaults[.enableDoNotDisturbDetection] && Defaults[.showDoNotDisturbIndicator] && !vm.hideOnClosed && !lockScreenManager.isLocked { } else if (!coordinator.expandingView.show || coordinator.expandingView.type == .doNotDisturb) && vm.notchState == .closed && doNotDisturbManager.isDoNotDisturbActive && Defaults[.enableDoNotDisturbDetection] && Defaults[.showDoNotDisturbIndicator] && !vm.hideOnClosed && !lockScreenManager.isLocked {
DoNotDisturbLiveActivity() DoNotDisturbLiveActivity()
} else if (!coordinator.expandingView.show || coordinator.expandingView.type == .lockScreen) && vm.notchState == .closed && (lockScreenManager.isLocked || !lockScreenManager.isLockIdle) && Defaults[.enableLockScreenLiveActivity] && !vm.hideOnClosed { } else if (!coordinator.expandingView.show || coordinator.expandingView.type == .lockScreen) && vm.notchState == .closed && (lockScreenManager.isLocked || !lockScreenManager.isLockIdle) && Defaults[.enableLockScreenLiveActivity] && !vm.hideOnClosed {

View file

@ -99,6 +99,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
let dndManager = DoNotDisturbManager.shared // NEW: DND detection let dndManager = DoNotDisturbManager.shared // NEW: DND detection
let bluetoothAudioManager = BluetoothAudioManager.shared // NEW: Bluetooth audio detection let bluetoothAudioManager = BluetoothAudioManager.shared // NEW: Bluetooth audio detection
let idleAnimationManager = IdleAnimationManager.shared // NEW: Custom idle animations let idleAnimationManager = IdleAnimationManager.shared // NEW: Custom idle animations
let downloadManager = DownloadManager.shared // NEW: Chromium downloads detection
let lockScreenPanelManager = LockScreenPanelManager.shared // NEW: Lock screen music panel let lockScreenPanelManager = LockScreenPanelManager.shared // NEW: Lock screen music panel
let systemTimerBridge = SystemTimerBridge.shared let systemTimerBridge = SystemTimerBridge.shared
var closeNotchWorkItem: DispatchWorkItem? var closeNotchWorkItem: DispatchWorkItem?

View file

@ -201,12 +201,15 @@ class DynamicIslandViewCoordinator: ObservableObject {
didSet { didSet {
if expandingView.show { if expandingView.show {
expandingViewTask?.cancel() expandingViewTask?.cancel()
let duration: TimeInterval = (expandingView.type == .download ? 2 : 3) // Only auto-hide for battery, not for downloads (DownloadManager handles that)
if expandingView.type != .download {
let duration: TimeInterval = 3
expandingViewTask = Task { [weak self] in expandingViewTask = Task { [weak self] in
try? await Task.sleep(for: .seconds(duration)) try? await Task.sleep(for: .seconds(duration))
guard let self = self, !Task.isCancelled else { return } guard let self = self, !Task.isCancelled else { return }
self.toggleExpandingView(status: false, type: .battery) self.toggleExpandingView(status: false, type: .battery)
} }
}
} else { } else {
expandingViewTask?.cancel() expandingViewTask?.cancel()
} }

View file

@ -4093,6 +4093,7 @@
} }
}, },
"Both" : { "Both" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -7170,7 +7171,12 @@
} }
} }
}, },
"Download Detection" : {
"comment" : "A section header in the Downloads settings view.",
"isCommentAutoGenerated" : true
},
"Download icon style" : { "Download icon style" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -7203,6 +7209,7 @@
} }
}, },
"Download indicators" : { "Download indicators" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"fr" : { "fr" : {
"stringUnit" : { "stringUnit" : {
@ -8473,6 +8480,7 @@
"isCommentAutoGenerated" : true "isCommentAutoGenerated" : true
}, },
"Exclude apps" : { "Exclude apps" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -12875,6 +12883,10 @@
}, },
"Monitor clipboard changes and keep a history of recent copies. Use Cmd+Shift+V to quickly access clipboard history." : { "Monitor clipboard changes and keep a history of recent copies. Use Cmd+Shift+V to quickly access clipboard history." : {
},
"Monitor your Downloads folder for Chromium-style downloads (.crdownload files) and show a live activity in the Dynamic Island while downloads are in progress." : {
"comment" : "A footer description for the \"Downloads\" section of the settings view.",
"isCommentAutoGenerated" : true
}, },
"Monitoring Behavior" : { "Monitoring Behavior" : {
@ -13902,9 +13914,6 @@
} }
} }
} }
},
"No excluded apps" : {
}, },
"No excludes" : { "No excludes" : {
"extractionState" : "stale", "extractionState" : "stale",
@ -14788,6 +14797,7 @@
} }
}, },
"Only app icon" : { "Only app icon" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -14798,6 +14808,7 @@
} }
}, },
"Only download icon" : { "Only download icon" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -14860,6 +14871,7 @@
}, },
"Percentage" : { "Percentage" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {
@ -15064,6 +15076,7 @@
"isCommentAutoGenerated" : true "isCommentAutoGenerated" : true
}, },
"Progress bar" : { "Progress bar" : {
"extractionState" : "stale",
"localizations" : { "localizations" : {
"en" : { "en" : {
"stringUnit" : { "stringUnit" : {

View file

@ -0,0 +1,103 @@
//
// DownloadLiveActivity.swift
// DynamicIsland
//
// Shows a download indicator when Chromium-style downloads
// are detected in the user's Downloads folder.
//
import SwiftUI
import Defaults
struct DownloadLiveActivity: View {
@EnvironmentObject var vm: DynamicIslandViewModel
@State private var downloadManager = DownloadManager.shared
@State private var isHovering: Bool = false
@State private var gestureProgress: CGFloat = 0
@State private var isExpanded: Bool = false
private var tint: Color {
.accentColor
}
var body: some View {
HStack(spacing: 0) {
// Left side: download icon capsule
Color.clear
.background {
if isExpanded {
HStack {
ZStack {
RoundedRectangle(cornerRadius: 6, style: .continuous)
.fill(tint.opacity(0.14))
Image(systemName: "arrow.down.circle.fill")
.font(.system(size: 14, weight: .semibold))
.foregroundStyle(tint)
}
.frame(
width: vm.effectiveClosedNotchHeight - 12,
height: vm.effectiveClosedNotchHeight - 12
)
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .leading)
}
}
.frame(
width: isExpanded ? max(0, vm.effectiveClosedNotchHeight - (isHovering ? 0 : 12) + gestureProgress / 2) : 0,
height: vm.effectiveClosedNotchHeight - (isHovering ? 0 : 12)
)
// Center: closed notch body (slightly wider during downloads)
Rectangle()
.fill(.black)
.frame(
width: vm.closedNotchSize.width
+ (isHovering ? 8 : 0)
+ (downloadManager.isDownloading ? 40 : 0)
)
// Right side: indeterminate-style progress bar
Color.clear
.background {
if isExpanded {
HStack {
if downloadManager.isDownloadCompleted {
Image(systemName: "checkmark.circle.fill")
.foregroundStyle(.green)
.font(.system(size: 16, weight: .semibold))
.padding(.trailing, 6)
} else if Defaults[.selectedDownloadIndicatorStyle] == .circle {
SpinningCircleDownloadView()
.padding(.trailing, 6)
} else {
ProgressView()
.progressViewStyle(.linear)
.tint(.accentColor)
.frame(width: 40)
}
}
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .trailing)
}
}
.frame(
width: isExpanded ? max(60, vm.effectiveClosedNotchHeight) : 0,
height: vm.effectiveClosedNotchHeight - (isHovering ? 0 : 12)
)
}
.frame(height: vm.effectiveClosedNotchHeight + (isHovering ? 8 : 0))
.onAppear {
withAnimation(.smooth(duration: 0.35)) {
isExpanded = true
}
}
.onChange(of: downloadManager.isDownloading) { _, newValue in
withAnimation(.smooth(duration: 0.35)) {
isExpanded = newValue
}
}
}
}

View file

@ -0,0 +1,28 @@
import SwiftUI
struct SpinningCircleDownloadView: View {
@State private var isRotating = false
var body: some View {
ZStack {
// Gray track
Circle()
.stroke(Color.gray.opacity(0.3), lineWidth: 3.5)
// Blue spinning segment
Circle()
.trim(from: 0, to: 0.25)
.stroke(
Color.accentColor,
style: StrokeStyle(lineWidth: 3.5, lineCap: .round)
)
.rotationEffect(Angle(degrees: isRotating ? 360 : 0))
.onAppear {
withAnimation(.linear(duration: 1).repeatForever(autoreverses: false)) {
isRotating = true
}
}
}
.frame(width: 16, height: 16)
}
}

View file

@ -256,13 +256,10 @@ struct SettingsView: View {
.padding(.horizontal, 12) .padding(.horizontal, 12)
List(filteredTabs, selection: selectionBinding) { tab in List(filteredTabs, selection: selectionBinding) { tab in
let isComingSoon = tab == .downloads
NavigationLink(value: tab) { NavigationLink(value: tab) {
HStack(spacing: 10) { HStack(spacing: 10) {
sidebarIcon(for: tab) sidebarIcon(for: tab)
.opacity(isComingSoon ? 0.45 : 1)
Text(tab.title) Text(tab.title)
.foregroundStyle(isComingSoon ? Color.secondary : Color.primary)
if tab == .osd { if tab == .osd {
Spacer() Spacer()
Text("ALPHA") Text("ALPHA")
@ -274,16 +271,10 @@ struct SettingsView: View {
Capsule() Capsule()
.fill(Color.orange) .fill(Color.orange)
) )
} else if isComingSoon {
Spacer()
comingSoonTag()
} }
} }
.padding(.vertical, 4) .padding(.vertical, 4)
} }
.tag(tab)
.disabled(isComingSoon)
.listRowInsets(EdgeInsets(top: 4, leading: 12, bottom: 4, trailing: 10))
} }
.listStyle(SidebarListStyle()) .listStyle(SidebarListStyle())
.frame(minWidth: 200) .frame(minWidth: 200)
@ -310,7 +301,7 @@ struct SettingsView: View {
.frame(width: 700) .frame(width: 700)
.onChange(of: searchText) { _, newValue in .onChange(of: searchText) { _, newValue in
let matches = tabsMatchingSearch(newValue) let matches = tabsMatchingSearch(newValue)
guard let firstMatch = matches.first(where: { $0 != .downloads }) else { return } guard let firstMatch = matches.first else { return }
if !matches.contains(resolvedSelection) { if !matches.contains(resolvedSelection) {
selectedTab = firstMatch selectedTab = firstMatch
} }
@ -349,7 +340,6 @@ struct SettingsView: View {
Binding( Binding(
get: { resolvedSelection }, get: { resolvedSelection },
set: { newValue in set: { newValue in
guard newValue != .downloads else { return }
selectedTab = newValue selectedTab = newValue
} }
) )
@ -1079,78 +1069,107 @@ struct Downloads: View {
var body: some View { var body: some View {
Form { Form {
warningBadge("We don't support downloads yet", "It will be supported later on.")
Section { Section {
Defaults.Toggle("Show download progress", key: .enableDownloadListener) Defaults.Toggle("Enable download detection", key: .enableDownloadListener)
.settingsHighlight(id: highlightID("Show download progress")) .settingsHighlight(id: highlightID("Enable download detection"))
.disabled(true) VStack(alignment: .leading, spacing: 12) {
Defaults.Toggle("Enable Safari Downloads", key: .enableSafariDownloads) Text("Download indicator style")
.settingsHighlight(id: highlightID("Enable Safari Downloads")) .font(.system(size: 13, weight: .semibold))
.disabled(!Defaults[.enableDownloadListener]) .foregroundStyle(.white)
Picker("Download indicator style", selection: $selectedDownloadIndicatorStyle) {
Text("Progress bar") HStack(spacing: 16) {
.tag(DownloadIndicatorStyle.progress) DownloadStyleButton(
Text("Percentage") style: .progress,
.tag(DownloadIndicatorStyle.percentage) isSelected: selectedDownloadIndicatorStyle == .progress,
disabled: !Defaults[.enableDownloadListener]
) {
selectedDownloadIndicatorStyle = .progress
}
DownloadStyleButton(
style: .circle,
isSelected: selectedDownloadIndicatorStyle == .circle,
disabled: !Defaults[.enableDownloadListener]
) {
selectedDownloadIndicatorStyle = .circle
}
}
} }
.settingsHighlight(id: highlightID("Download indicator style")) .settingsHighlight(id: highlightID("Download indicator style"))
Picker("Download icon style", selection: $selectedDownloadIconStyle) {
Text("Only app icon")
.tag(DownloadIconStyle.onlyAppIcon)
Text("Only download icon")
.tag(DownloadIconStyle.onlyIcon)
Text("Both")
.tag(DownloadIconStyle.iconAndAppIcon)
}
.settingsHighlight(id: highlightID("Download icon style"))
} header: { } header: {
HStack { Text("Download Detection")
Text("Download indicators") } footer: {
comingSoonTag() Text("Monitor your Downloads folder for Chromium-style downloads (.crdownload files) and show a live activity in the Dynamic Island while downloads are in progress.")
}
}
Section {
List {
ForEach([].indices, id: \.self) { index in
Text("\(index)")
}
}
.frame(minHeight: 96)
.overlay {
if true {
Text("No excluded apps")
.foregroundStyle(Color(.secondaryLabelColor))
}
}
.actionBar(padding: 0) {
Group {
Button {} label: {
Image(systemName: "plus")
.frame(width: 25, height: 16, alignment: .center)
.contentShape(Rectangle())
.foregroundStyle(.secondary)
}
Divider()
Button {} label: {
Image(systemName: "minus")
.frame(width: 20, height: 16, alignment: .center)
.contentShape(Rectangle())
.foregroundStyle(.secondary)
}
}
}
} header: {
HStack(spacing: 4) {
Text("Exclude apps")
comingSoonTag()
}
} }
} }
.navigationTitle("Downloads") .navigationTitle("Downloads")
.disabled(true) }
.opacity(0.6)
struct DownloadStyleButton: View {
let style: DownloadIndicatorStyle
let isSelected: Bool
let disabled: Bool
let action: () -> Void
@State private var isHovering = false
var body: some View {
VStack(spacing: 8) {
ZStack {
RoundedRectangle(cornerRadius: 12)
.fill(backgroundColor)
.overlay(
RoundedRectangle(cornerRadius: 12)
.strokeBorder(borderColor, lineWidth: isSelected ? 2 : 1)
)
if style == .progress {
ProgressView()
.progressViewStyle(.linear)
.tint(.accentColor)
.frame(width: 40)
} else {
SpinningCircleDownloadView()
}
}
.frame(width: 80, height: 60)
.onHover { hovering in
if !disabled {
withAnimation(.easeInOut(duration: 0.2)) {
isHovering = hovering
}
}
}
Text(style.rawValue)
.font(.caption)
.fontWeight(.medium)
.lineLimit(2)
.multilineTextAlignment(.center)
.frame(width: 100)
.foregroundStyle(disabled ? .secondary : .primary)
}
.contentShape(Rectangle())
.onTapGesture {
if !disabled {
action()
}
}
.opacity(disabled ? 0.5 : 1.0)
}
private var backgroundColor: Color {
if disabled { return Color(nsColor: .controlBackgroundColor) }
if isSelected { return Color.accentColor.opacity(0.1) }
if isHovering { return Color.primary.opacity(0.05) }
return Color(nsColor: .controlBackgroundColor)
}
private var borderColor: Color {
if isSelected { return Color.accentColor }
if isHovering { return Color.primary.opacity(0.1) }
return Color.clear
}
} }
} }

View file

@ -46,6 +46,7 @@ enum SettingsEnum {
enum DownloadIndicatorStyle: String, Defaults.Serializable { enum DownloadIndicatorStyle: String, Defaults.Serializable {
case progress = "Progress" case progress = "Progress"
case percentage = "Percentage" case percentage = "Percentage"
case circle = "Circle"
} }
enum DownloadIconStyle: String, Defaults.Serializable { enum DownloadIconStyle: String, Defaults.Serializable {

View file

@ -0,0 +1,242 @@
import Foundation
import SwiftUI
import Observation
import Defaults
@Observable
@MainActor
class DownloadManager {
static let shared = DownloadManager()
private(set) var isDownloading: Bool = false
private(set) var isDownloadCompleted: Bool = false
private let coordinator = DynamicIslandViewCoordinator.shared
private var source: DispatchSourceFileSystemObject?
private let queue = DispatchQueue(label: "com.dynamicisland.downloads.monitor", qos: .utility)
private var completionTimer: Timer?
private var hasPerformedInitialScan: Bool = false
private var initialCrDownloadFiles: Set<String> = []
private var previousAllFiles: Set<String> = []
private var ignoredFiles: Set<String> = []
private var downloadsDirectory: URL? {
FileManager.default.urls(for: .downloadsDirectory, in: .userDomainMask).first
}
init() {
requestDownloadsPermissionIfNeeded()
startMonitoringIfNeeded()
Defaults.publisher(.enableDownloadListener)
.sink { [weak self] _ in
guard let self else { return }
Task { @MainActor in
self.startMonitoringIfNeeded()
}
}
}
private func startMonitoringIfNeeded() {
if Defaults[.enableDownloadListener] {
startMonitoring()
} else {
stopMonitoring()
updateDownloadingState(isActive: false)
}
}
private func startMonitoring() {
guard source == nil, let downloadsDirectory else { return }
hasPerformedInitialScan = false
initialCrDownloadFiles.removeAll()
previousAllFiles.removeAll()
ignoredFiles.removeAll()
isDownloading = false
let path = downloadsDirectory.path
let fd = open(path, O_EVTONLY)
guard fd >= 0 else { return }
let src = DispatchSource.makeFileSystemObjectSource(
fileDescriptor: fd,
eventMask: [.write, .rename, .delete, .attrib],
queue: queue
)
src.setEventHandler { [weak self] in
self?.scanDownloadsDirectory()
}
src.setCancelHandler {
close(fd)
}
source = src
src.resume()
scanDownloadsDirectory()
}
private func stopMonitoring() {
source?.cancel()
source = nil
hasPerformedInitialScan = false
initialCrDownloadFiles.removeAll()
ignoredFiles.removeAll()
isDownloading = false
}
private func scanDownloadsDirectory() {
guard let downloadsDirectory else { return }
let crDownloadFiles: Set<String>
let allFiles: Set<String>
do {
let contents = try FileManager.default.contentsOfDirectory(
at: downloadsDirectory,
includingPropertiesForKeys: [.creationDateKey]
)
crDownloadFiles = Set(contents
.filter {
let ext = $0.pathExtension.lowercased()
return ext == "crdownload" || ext == "download"
}
.map { $0.lastPathComponent }
)
allFiles = Set(contents.map { $0.lastPathComponent })
} catch {
return
}
Task { @MainActor in
self.processDownloadFiles(crDownloadFiles, allFiles: allFiles)
}
}
private func processDownloadFiles(_ crDownloadFiles: Set<String>, allFiles: Set<String>) {
if !hasPerformedInitialScan {
hasPerformedInitialScan = true
initialCrDownloadFiles = crDownloadFiles
previousAllFiles = allFiles
ignoredFiles = crDownloadFiles
isDownloading = false
return
}
let newFiles = crDownloadFiles.subtracting(initialCrDownloadFiles)
let disappearedFiles = initialCrDownloadFiles.subtracting(crDownloadFiles)
let newRegularFiles = allFiles.subtracting(previousAllFiles).subtracting(crDownloadFiles)
initialCrDownloadFiles = crDownloadFiles
previousAllFiles = allFiles
let activeFiles = crDownloadFiles.subtracting(ignoredFiles)
let hasActiveDownloads = !activeFiles.isEmpty
if !newFiles.isEmpty {
let newActiveFiles = newFiles.subtracting(ignoredFiles)
if !newActiveFiles.isEmpty {
if !isDownloading {
updateDownloadingState(isActive: true)
}
}
}
// completion logic
if isDownloading {
if !hasActiveDownloads {
if !newRegularFiles.isEmpty || disappearedFiles.isEmpty {
if !isDownloadCompleted {
updateDownloadingState(isActive: false)
}
} else {
closeDownloadViewImmediately()
}
}
} else if hasActiveDownloads {
updateDownloadingState(isActive: true)
}
}
private func requestDownloadsPermissionIfNeeded() {
guard let downloadsDirectory else { return }
_ = try? FileManager.default.contentsOfDirectory(at: downloadsDirectory, includingPropertiesForKeys: nil)
}
private func updateDownloadingState(isActive: Bool) {
completionTimer?.invalidate()
completionTimer = nil
if isActive {
isDownloadCompleted = false
if !isDownloading {
withAnimation(.smooth) {
isDownloading = true
}
coordinator.toggleExpandingView(
status: true,
type: .download,
value: 0,
browser: .chromium
)
}
} else {
if isDownloading {
withAnimation(.smooth) {
isDownloadCompleted = true
}
completionTimer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: false) { [weak self] _ in
Task { @MainActor in
self?.closeDownloadView()
}
}
}
}
}
private func closeDownloadView() {
withAnimation(.smooth) {
isDownloading = false
isDownloadCompleted = false
}
coordinator.toggleExpandingView(
status: false,
type: .download,
value: 0,
browser: .chromium
)
}
private func closeDownloadViewImmediately() {
completionTimer?.invalidate()
completionTimer = nil
withAnimation(.smooth) {
isDownloading = false
isDownloadCompleted = false
}
coordinator.toggleExpandingView(
status: false,
type: .download,
value: 0,
browser: .chromium
)
}
}