Skip to content

Commit

Permalink
🔀 Merge pull request #656 from iSapozhnik/chore/memory-leak-in-event-…
Browse files Browse the repository at this point in the history
…monitor

🐞 Fix memory leak in `NSEventMonitor`
  • Loading branch information
MrKai77 authored Dec 31, 2024
2 parents eec2f86 + 11e24b1 commit e28cd1f
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions Loop/Utilities/EventMonitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ protocol EventMonitor {
}

class NSEventMonitor: EventMonitor, Identifiable, Equatable {
private weak var localEventMonitor: AnyObject?
private weak var globalEventMonitor: AnyObject?
private var localEventMonitor: Any?
private var globalEventMonitor: Any?

private let scope: NSEventMonitor.Scope
private let eventTypeMask: NSEvent.EventTypeMask
private let eventHandler: (NSEvent) -> (NSEvent?)

private var scope: NSEventMonitor.Scope
private var eventTypeMask: NSEvent.EventTypeMask
private var eventHandler: (NSEvent) -> (NSEvent?)
var isEnabled: Bool = false

enum Scope {
Expand All @@ -42,35 +43,36 @@ class NSEventMonitor: EventMonitor, Identifiable, Equatable {
if scope == .local || scope == .all {
localEventMonitor = NSEvent.addLocalMonitorForEvents(
matching: eventTypeMask,
handler: eventHandler
) as AnyObject

isEnabled = true
handler: { [weak self] event in
self?.eventHandler(event)
}
)
}

if scope == .global || scope == .all {
globalEventMonitor = NSEvent.addGlobalMonitorForEvents(
matching: eventTypeMask,
handler: { _ = self.eventHandler($0) }
) as AnyObject

isEnabled = true
handler: { [weak self] event in
_ = self?.eventHandler(event)
}
)
}

isEnabled = true
}

func stop() {
if let localEventMonitor {
NSEvent.removeMonitor(localEventMonitor)
isEnabled = false
}

if let globalEventMonitor {
NSEvent.removeMonitor(globalEventMonitor)
isEnabled = false
}
isEnabled = false
}

var id = UUID()
let id = UUID()
static func == (lhs: NSEventMonitor, rhs: NSEventMonitor) -> Bool {
lhs.id == rhs.id
}
Expand Down

0 comments on commit e28cd1f

Please sign in to comment.