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/event_monitor_mac.h"
7 #import <Cocoa/Cocoa.h>
9 #include "base/logging.h"
10 #include "ui/events/event.h"
11 #include "ui/events/event_handler.h"
12 #include "ui/events/event_utils.h"
17 scoped_ptr<EventMonitor> EventMonitor::CreateApplicationMonitor(
18 ui::EventHandler* event_handler) {
19 return make_scoped_ptr(new EventMonitorMac(event_handler, nullptr));
23 scoped_ptr<EventMonitor> EventMonitor::CreateWindowMonitor(
24 ui::EventHandler* event_handler,
25 gfx::NativeWindow target_window) {
26 return make_scoped_ptr(new EventMonitorMac(event_handler, target_window));
30 gfx::Point EventMonitor::GetLastMouseLocation() {
31 NSPoint mouseLocation = [NSEvent mouseLocation];
32 // Flip coordinates to gfx (0,0 in top-left corner) using primary screen.
33 NSScreen* screen = [[NSScreen screens] objectAtIndex:0];
34 mouseLocation.y = NSMaxY([screen frame]) - mouseLocation.y;
35 return gfx::Point(mouseLocation.x, mouseLocation.y);
38 EventMonitorMac::EventMonitorMac(ui::EventHandler* event_handler,
39 gfx::NativeWindow target_window) {
40 DCHECK(event_handler);
41 monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSAnyEventMask
42 handler:^NSEvent*(NSEvent* event) {
43 if (!target_window || [event window] == target_window) {
44 scoped_ptr<ui::Event> ui_event = ui::EventFromNative(event);
45 event_handler->OnEvent(ui_event.get());
51 EventMonitorMac::~EventMonitorMac() {
52 [NSEvent removeMonitor:monitor_];