Skip to content

Commit

Permalink
Wait for mouse to stop moving before moving items
Browse files Browse the repository at this point in the history
  • Loading branch information
jordanbaird committed Oct 13, 2024
1 parent 6ce5b1b commit 6d0290a
Showing 1 changed file with 62 additions and 13 deletions.
75 changes: 62 additions & 13 deletions Ice/MenuBar/ItemManagement/MenuBarItemManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -467,6 +467,62 @@ extension MenuBarItemManager {
}
}

// MARK: - Async Waiters

extension MenuBarItemManager {
/// Waits asynchronously for all menu bar items to stop moving.
///
/// - Parameter timeout: Amount of time to wait before throwing an error.
func waitForItemsToStopMoving(timeout: Duration? = nil) async throws {
let taskBody: @Sendable () async throws -> Void = {
while await self.isMovingItem {
try Task.checkCancellation()
try await Task.sleep(for: .milliseconds(10))
}
}
let checkTask = if let timeout {
Task(timeout: timeout) {
try await taskBody()
}
} else {
Task {
try await taskBody()
}
}
try await checkTask.value
}

/// Waits asynchronously for the mouse to stop moving.
///
/// - Parameters:
/// - threshold: A threshold to use to determine whether the mouse has stopped moving.
/// - timeout: Amount of time to wait before throwing an error.
func waitForMouseToStopMoving(threshold: TimeInterval = 0.1, timeout: Duration? = nil) async throws {
let taskBody: @Sendable () async throws -> Void = {
while true {
try Task.checkCancellation()
guard let date = await self.lastMouseMoveStartDate else {
break
}
if Date.now.timeIntervalSince(date) > threshold {
break
}
try await Task.sleep(for: .milliseconds(10))
}
}
let checkTask = if let timeout {
Task(timeout: timeout) {
try await taskBody()
}
} else {
Task {
try await taskBody()
}
}
try await checkTask.value
}
}

// MARK: - Move Items

extension MenuBarItemManager {
Expand Down Expand Up @@ -990,6 +1046,12 @@ extension MenuBarItemManager {
return
}

do {
try await waitForMouseToStopMoving()
} catch {
throw EventError(code: .couldNotComplete, item: item)
}

Logger.itemManager.info("Moving \(item.logString) to \(destination.logString)")

guard let appState else {
Expand Down Expand Up @@ -1064,19 +1126,6 @@ extension MenuBarItemManager {
throw EventError(code: .otherTimeout, item: item)
}
}

/// Waits asynchronously for all menu bar items to stop moving.
///
/// - Parameter timeout: Amount of time to wait before throwing an error.
func waitForItemsToStopMoving(timeout: Duration) async throws {
let isMovingItemCheckTask = Task(timeout: timeout) {
while await self.isMovingItem {
try Task.checkCancellation()
try await Task.sleep(for: .milliseconds(10))
}
}
try await isMovingItemCheckTask.value
}
}

// MARK: - Click Items
Expand Down

0 comments on commit 6d0290a

Please sign in to comment.