1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "ui/views/cocoa/cocoa_mouse_capture.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/logging.h"
10 #import "ui/views/cocoa/cocoa_mouse_capture_delegate.h"
14 // The ActiveEventTap is a RAII handle on the resources being used to capture
15 // events. There is either 0 or 1 active instance of this class. If a second
16 // instance is created, it will destroy the other instance before returning from
18 class CocoaMouseCapture::ActiveEventTap {
20 explicit ActiveEventTap(CocoaMouseCapture* owner);
25 // The currently active event tap, or null if there is none.
26 static ActiveEventTap* g_active_event_tap;
28 CocoaMouseCapture* owner_; // Weak. Owns this.
32 DISALLOW_COPY_AND_ASSIGN(ActiveEventTap);
35 CocoaMouseCapture::ActiveEventTap*
36 CocoaMouseCapture::ActiveEventTap::g_active_event_tap = nullptr;
38 CocoaMouseCapture::ActiveEventTap::ActiveEventTap(CocoaMouseCapture* owner)
39 : owner_(owner), local_monitor_(nil), global_monitor_(nil) {
40 if (g_active_event_tap)
41 g_active_event_tap->owner_->OnOtherClientGotCapture();
42 DCHECK(!g_active_event_tap);
43 g_active_event_tap = this;
46 CocoaMouseCapture::ActiveEventTap::~ActiveEventTap() {
47 DCHECK_EQ(g_active_event_tap, this);
48 [NSEvent removeMonitor:global_monitor_];
49 [NSEvent removeMonitor:local_monitor_];
50 g_active_event_tap = nullptr;
51 owner_->delegate_->OnMouseCaptureLost();
54 void CocoaMouseCapture::ActiveEventTap::Init() {
55 NSEventMask event_mask =
56 NSLeftMouseDownMask | NSLeftMouseUpMask | NSRightMouseDownMask |
57 NSRightMouseUpMask | NSMouseMovedMask | NSLeftMouseDraggedMask |
58 NSRightMouseDraggedMask | NSMouseEnteredMask | NSMouseExitedMask |
59 NSScrollWheelMask | NSOtherMouseDownMask | NSOtherMouseUpMask |
60 NSOtherMouseDraggedMask;
62 local_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:event_mask
63 handler:^NSEvent*(NSEvent* event) {
64 owner_->delegate_->PostCapturedEvent(event);
65 return nil; // Swallow all local events.
67 global_monitor_ = [NSEvent addGlobalMonitorForEventsMatchingMask:event_mask
68 handler:^void(NSEvent* event) {
69 owner_->delegate_->PostCapturedEvent(event);
73 CocoaMouseCapture::CocoaMouseCapture(CocoaMouseCaptureDelegate* delegate)
74 : delegate_(delegate), active_handle_(new ActiveEventTap(this)) {
75 active_handle_->Init();
78 CocoaMouseCapture::~CocoaMouseCapture() {
81 void CocoaMouseCapture::OnOtherClientGotCapture() {
82 DCHECK(active_handle_);
83 active_handle_.reset();