Skip to content

Conversation

@pablopunk
Copy link
Owner

@pablopunk pablopunk commented Mar 11, 2025

if anything goes wrong I blame claude-3.7-sonnet-thinking 🙄

Might be able to solve/mitigate #68

🤖 Summary (from sonnet)

We fixed two main issues in your app:

  1. High CPU usage when idle - Added proper state tracking so the app only processes events when actually needed
  2. Shortcut conflicts with other apps - Improved how keyboard shortcuts are handled so they don't interfere with other applications

We also added better cleanup when the app quits and made the code more robust with proper error handling.

@codesandbox
Copy link

codesandbox bot commented Mar 11, 2025

Review or Edit in CodeSandbox

Open the branch in Web EditorVS CodeInsiders

Open Preview

@coderabbitai
Copy link

coderabbitai bot commented Mar 11, 2025

Walkthrough

This pull request introduces cleanup and tracking enhancements across multiple components. In the AppDelegate, a termination method is added that invokes cleanup routines for shortcut actions. The MouseTracker now uses an isTracking flag to manage its state, with updated checks and resets in its tracking methods. Meanwhile, the ShortcutsManager is enhanced with new state variables and cleanup methods to manage active shortcuts and mouse subscriptions, along with modifications to its monitor registrations. These changes ensure that both application termination and runtime tracking are handled more robustly.

Changes

File Change Summary
Swift Shift/src/AppDelegate.swift Added applicationWillTerminate(_:) which calls removeAllActions on shortcutMonitor and cleanupAllShortcuts on ShortcutsManager.shared during shutdown.
Swift Shift/src/Manager/MouseTracker.swift Introduced private isTracking variable and updated startTracking, stopTracking, registerMouseEventMonitor, handleMouseMoved, and resetTrackingVariables with state checks and cleanup logic.
Swift Shift/src/Manager/ShortcutsManager.swift Added private variables activeShortcuts and mouseSubscriptions; introduced methods cleanupAllShortcuts, cleanupAllMouseSubscriptions, and cleanupMouseSubscriptions(action:); modified addGlobalMonitors, startTracking, and stopTracking to manage shortcut states.

Sequence Diagram(s)

sequenceDiagram
    participant AD as AppDelegate
    participant SM as ShortcutMonitor
    participant STM as ShortcutsManager
    AD->>SM: applicationWillTerminate(notification)
    Note right of AD: Remove all shortcut actions
    AD->>STM: applicationWillTerminate(notification)
    Note right of AD: Cleanup all shortcuts
Loading
sequenceDiagram
    participant MT as MouseTracker
    participant Timer as TrackingTimer
    MT->>MT: startTracking(for:button:)
    Note over MT: Verify trackedWindow exists and handle current tracking
    MT->>Timer: Start tracking timer
    MT->>MT: Set isTracking = true
    Note right of MT: Register mouse event monitor with guard on isTracking
Loading

Poem

I'm a bouncy rabbit, swift on my feet,
Cleaning up shortcuts, making shutdown neat.
I track the mouse with a careful glance,
Resetting states with each lively dance.
Hoppin' through code, I celebrate this chance!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a9773a8 and fe2d8f4.

📒 Files selected for processing (3)
  • Swift Shift/src/AppDelegate.swift (1 hunks)
  • Swift Shift/src/Manager/MouseTracker.swift (4 hunks)
  • Swift Shift/src/Manager/ShortcutsManager.swift (6 hunks)
🧰 Additional context used
🪛 SwiftLint (0.57.0)
Swift Shift/src/Manager/ShortcutsManager.swift

[Warning] 54-54: where clauses are preferred over a single if inside a for

(for_where)

🔇 Additional comments (21)
Swift Shift/src/AppDelegate.swift (1)

22-27: Looks good to ensure proper cleanup on app termination.
No issues found. This approach clarifies the termination process and helps remove shortcuts and other resources cleanly.

Swift Shift/src/Manager/MouseTracker.swift (8)

28-28: Good addition for clearer tracking state management.
Introducing isTracking strengthens code readability and helps avoid accidental overlapping sessions.


33-37: Properly cleans up ongoing tracking sessions.
Stopping any active tracking before starting a new one prevents collisions and ensures consistent state.


39-45: Smart check for a valid window.
Only proceeding if trackedWindow is set avoids unnecessary calls and potential nil-pointer errors.


53-53: Correct final step in stopTracking.
Resetting isTracking here ensures a clean hand-off after stopping the timer and monitor.


125-127: Prevents multiple monitors from stacking.
Calling removeMouseEventMonitor() first is a good way to avoid duplicate event handlers or memory leaks.


134-137: Ensures events are handled only during active tracking.
By checking isTracking inside the global monitor, you neatly gate other mouse events outside of tracking sessions.


149-150: Defensive check in handleMouseMoved(_:).
Verifying isTracking and required references reduces risk of null calls and unexpected behavior.


272-273: Fully resets window-related state.
Clearing out quadrant and windowSize aligns with the rest of the reset logic for a complete teardown.

Swift Shift/src/Manager/ShortcutsManager.swift (12)

39-40: Storing active shortcuts and mouse subscriptions in dedicated structures is efficient.
These collections make it clearer which actions are currently enabled and which subscriptions remain active.


43-46: Initializes shortcut states correctly.
Setting all shortcut types to false from the start ensures consistent defaults.


50-69: Robust shortcut cleanup routine.
cleanupAllShortcuts() systematically stops tracking, clears monitors, and resets state, improving reliability during shutdown or manual resets.

🧰 Tools
🪛 SwiftLint (0.57.0)

[Warning] 54-54: where clauses are preferred over a single if inside a for

(for_where)


113-113: Additional cleanup call to mouse subscriptions.
Including cleanupAllMouseSubscriptions() in clearActionsAndMonitors() guarantees everything—key- and mouse-based—gets wiped together.


127-132: Central method to cancel all mouse-related events.
cleanupAllMouseSubscriptions() effectively consolidates unsubscription logic, preventing leaks or stale listeners.


142-142: No practical changes.


152-152: No functional additions.


156-190: Comprehensive flag-change handling for modifier-only shortcuts.
By monitoring global and local flagsChanged events, this approach reliably tracks activation and deactivation of shortcuts.


217-218: Clear labeling of mouse event keys.
Defining downKey and upKey strings clarifies which subscription is for which action.


220-242: Subscribing to mouse events conditionally.
Leveraging activeShortcuts ensures the system only starts tracking when the shortcut is indeed active.


246-247: Correctly updating activeShortcuts on stop.
Setting the dictionary entry to false keeps state in sync.


249-258: Methodical approach to cleaning specific mouse subscriptions.
cleanupMouseSubscriptions(action:) helps maintain a granular approach for unsubscribing only to the relevant events.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@pablopunk pablopunk marked this pull request as draft March 11, 2025 19:45
@pablopunk pablopunk marked this pull request as ready for review March 11, 2025 20:07
@pablopunk pablopunk merged commit 33ebeda into main Mar 11, 2025
3 checks passed
@pablopunk pablopunk deleted the refactor-mouse-events-with-ai branch March 11, 2025 20:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants