base::Time multiplicative operator overloading
[chromium-blink-merge.git] / ui / events / event.cc
blob5e7d8c86377a4d6a7c5546dcde02b6a76e6c71d4
1 // Copyright (c) 2012 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 #include "ui/events/event.h"
7 #if defined(USE_X11)
8 #include <X11/extensions/XInput2.h>
9 #include <X11/keysym.h>
10 #include <X11/Xlib.h>
11 #endif
13 #include <cmath>
14 #include <cstring>
16 #include "base/metrics/histogram.h"
17 #include "base/strings/stringprintf.h"
18 #include "ui/events/event_utils.h"
19 #include "ui/events/keycodes/dom3/dom_code.h"
20 #include "ui/events/keycodes/dom3/dom_key.h"
21 #include "ui/events/keycodes/dom4/keycode_converter.h"
22 #include "ui/events/keycodes/keyboard_code_conversion.h"
23 #include "ui/gfx/geometry/point3_f.h"
24 #include "ui/gfx/geometry/point_conversions.h"
25 #include "ui/gfx/geometry/safe_integer_conversions.h"
26 #include "ui/gfx/transform.h"
27 #include "ui/gfx/transform_util.h"
29 #if defined(USE_X11)
30 #include "ui/events/keycodes/keyboard_code_conversion_x.h"
31 #elif defined(USE_OZONE)
32 #include "ui/events/ozone/layout/keyboard_layout_engine.h"
33 #include "ui/events/ozone/layout/keyboard_layout_engine_manager.h"
34 #endif
36 namespace {
38 std::string EventTypeName(ui::EventType type) {
39 #define RETURN_IF_TYPE(t) if (type == ui::t) return #t
40 #define CASE_TYPE(t) case ui::t: return #t
41 switch (type) {
42 CASE_TYPE(ET_UNKNOWN);
43 CASE_TYPE(ET_MOUSE_PRESSED);
44 CASE_TYPE(ET_MOUSE_DRAGGED);
45 CASE_TYPE(ET_MOUSE_RELEASED);
46 CASE_TYPE(ET_MOUSE_MOVED);
47 CASE_TYPE(ET_MOUSE_ENTERED);
48 CASE_TYPE(ET_MOUSE_EXITED);
49 CASE_TYPE(ET_KEY_PRESSED);
50 CASE_TYPE(ET_KEY_RELEASED);
51 CASE_TYPE(ET_MOUSEWHEEL);
52 CASE_TYPE(ET_MOUSE_CAPTURE_CHANGED);
53 CASE_TYPE(ET_TOUCH_RELEASED);
54 CASE_TYPE(ET_TOUCH_PRESSED);
55 CASE_TYPE(ET_TOUCH_MOVED);
56 CASE_TYPE(ET_TOUCH_CANCELLED);
57 CASE_TYPE(ET_DROP_TARGET_EVENT);
58 CASE_TYPE(ET_TRANSLATED_KEY_PRESS);
59 CASE_TYPE(ET_TRANSLATED_KEY_RELEASE);
60 CASE_TYPE(ET_GESTURE_SCROLL_BEGIN);
61 CASE_TYPE(ET_GESTURE_SCROLL_END);
62 CASE_TYPE(ET_GESTURE_SCROLL_UPDATE);
63 CASE_TYPE(ET_GESTURE_SHOW_PRESS);
64 CASE_TYPE(ET_GESTURE_WIN8_EDGE_SWIPE);
65 CASE_TYPE(ET_GESTURE_TAP);
66 CASE_TYPE(ET_GESTURE_TAP_DOWN);
67 CASE_TYPE(ET_GESTURE_TAP_CANCEL);
68 CASE_TYPE(ET_GESTURE_BEGIN);
69 CASE_TYPE(ET_GESTURE_END);
70 CASE_TYPE(ET_GESTURE_TWO_FINGER_TAP);
71 CASE_TYPE(ET_GESTURE_PINCH_BEGIN);
72 CASE_TYPE(ET_GESTURE_PINCH_END);
73 CASE_TYPE(ET_GESTURE_PINCH_UPDATE);
74 CASE_TYPE(ET_GESTURE_LONG_PRESS);
75 CASE_TYPE(ET_GESTURE_LONG_TAP);
76 CASE_TYPE(ET_GESTURE_SWIPE);
77 CASE_TYPE(ET_GESTURE_TAP_UNCONFIRMED);
78 CASE_TYPE(ET_GESTURE_DOUBLE_TAP);
79 CASE_TYPE(ET_SCROLL);
80 CASE_TYPE(ET_SCROLL_FLING_START);
81 CASE_TYPE(ET_SCROLL_FLING_CANCEL);
82 CASE_TYPE(ET_CANCEL_MODE);
83 CASE_TYPE(ET_UMA_DATA);
84 case ui::ET_LAST: NOTREACHED(); return std::string();
85 // Don't include default, so that we get an error when new type is added.
87 #undef CASE_TYPE
89 NOTREACHED();
90 return std::string();
93 bool IsX11SendEventTrue(const base::NativeEvent& event) {
94 #if defined(USE_X11)
95 return event && event->xany.send_event;
96 #else
97 return false;
98 #endif
101 bool X11EventHasNonStandardState(const base::NativeEvent& event) {
102 #if defined(USE_X11)
103 const unsigned int kAllStateMask =
104 Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask |
105 Mod1Mask | Mod2Mask | Mod3Mask | Mod4Mask | Mod5Mask | ShiftMask |
106 LockMask | ControlMask | AnyModifier;
107 return event && (event->xkey.state & ~kAllStateMask) != 0;
108 #else
109 return false;
110 #endif
113 unsigned long long get_next_touch_event_id() {
114 static unsigned long long id = 0;
115 return id++;
118 } // namespace
120 namespace ui {
122 ////////////////////////////////////////////////////////////////////////////////
123 // Event
125 // static
126 scoped_ptr<Event> Event::Clone(const Event& event) {
127 if (event.IsKeyEvent()) {
128 return make_scoped_ptr(new KeyEvent(static_cast<const KeyEvent&>(event)));
131 if (event.IsMouseEvent()) {
132 if (event.IsMouseWheelEvent()) {
133 return make_scoped_ptr(
134 new MouseWheelEvent(static_cast<const MouseWheelEvent&>(event)));
137 return make_scoped_ptr(
138 new MouseEvent(static_cast<const MouseEvent&>(event)));
141 if (event.IsTouchEvent()) {
142 return make_scoped_ptr(
143 new TouchEvent(static_cast<const TouchEvent&>(event)));
146 if (event.IsGestureEvent()) {
147 return make_scoped_ptr(
148 new GestureEvent(static_cast<const GestureEvent&>(event)));
151 if (event.IsScrollEvent()) {
152 return make_scoped_ptr(
153 new ScrollEvent(static_cast<const ScrollEvent&>(event)));
156 return make_scoped_ptr(new Event(event));
159 Event::~Event() {
160 if (delete_native_event_)
161 ReleaseCopiedNativeEvent(native_event_);
164 GestureEvent* Event::AsGestureEvent() {
165 CHECK(IsGestureEvent());
166 return static_cast<GestureEvent*>(this);
169 const GestureEvent* Event::AsGestureEvent() const {
170 CHECK(IsGestureEvent());
171 return static_cast<const GestureEvent*>(this);
174 bool Event::HasNativeEvent() const {
175 base::NativeEvent null_event;
176 std::memset(&null_event, 0, sizeof(null_event));
177 return !!std::memcmp(&native_event_, &null_event, sizeof(null_event));
180 void Event::StopPropagation() {
181 // TODO(sad): Re-enable these checks once View uses dispatcher to dispatch
182 // events.
183 // CHECK(phase_ != EP_PREDISPATCH && phase_ != EP_POSTDISPATCH);
184 CHECK(cancelable_);
185 result_ = static_cast<EventResult>(result_ | ER_CONSUMED);
188 void Event::SetHandled() {
189 // TODO(sad): Re-enable these checks once View uses dispatcher to dispatch
190 // events.
191 // CHECK(phase_ != EP_PREDISPATCH && phase_ != EP_POSTDISPATCH);
192 CHECK(cancelable_);
193 result_ = static_cast<EventResult>(result_ | ER_HANDLED);
196 Event::Event(EventType type, base::TimeDelta time_stamp, int flags)
197 : type_(type),
198 time_stamp_(time_stamp),
199 flags_(flags),
200 native_event_(base::NativeEvent()),
201 delete_native_event_(false),
202 cancelable_(true),
203 target_(NULL),
204 phase_(EP_PREDISPATCH),
205 result_(ER_UNHANDLED),
206 source_device_id_(ED_UNKNOWN_DEVICE) {
207 if (type_ < ET_LAST)
208 name_ = EventTypeName(type_);
211 Event::Event(const base::NativeEvent& native_event,
212 EventType type,
213 int flags)
214 : type_(type),
215 time_stamp_(EventTimeFromNative(native_event)),
216 flags_(flags),
217 native_event_(native_event),
218 delete_native_event_(false),
219 cancelable_(true),
220 target_(NULL),
221 phase_(EP_PREDISPATCH),
222 result_(ER_UNHANDLED),
223 source_device_id_(ED_UNKNOWN_DEVICE) {
224 base::TimeDelta delta = EventTimeForNow() - time_stamp_;
225 if (type_ < ET_LAST)
226 name_ = EventTypeName(type_);
227 base::HistogramBase::Sample delta_sample =
228 static_cast<base::HistogramBase::Sample>(delta.InMicroseconds());
229 UMA_HISTOGRAM_CUSTOM_COUNTS("Event.Latency.Browser", delta_sample, 1, 1000000,
230 100);
231 std::string name_for_event =
232 base::StringPrintf("Event.Latency.Browser.%s", name_.c_str());
233 base::HistogramBase* counter_for_type =
234 base::Histogram::FactoryGet(
235 name_for_event,
237 1000000,
238 100,
239 base::HistogramBase::kUmaTargetedHistogramFlag);
240 counter_for_type->Add(delta_sample);
242 #if defined(USE_X11)
243 if (native_event->type == GenericEvent) {
244 XIDeviceEvent* xiev =
245 static_cast<XIDeviceEvent*>(native_event->xcookie.data);
246 source_device_id_ = xiev->sourceid;
248 #endif
251 Event::Event(const Event& copy)
252 : type_(copy.type_),
253 time_stamp_(copy.time_stamp_),
254 latency_(copy.latency_),
255 flags_(copy.flags_),
256 native_event_(CopyNativeEvent(copy.native_event_)),
257 delete_native_event_(true),
258 cancelable_(true),
259 target_(NULL),
260 phase_(EP_PREDISPATCH),
261 result_(ER_UNHANDLED),
262 source_device_id_(copy.source_device_id_) {
263 if (type_ < ET_LAST)
264 name_ = EventTypeName(type_);
267 void Event::SetType(EventType type) {
268 if (type_ < ET_LAST)
269 name_ = std::string();
270 type_ = type;
271 if (type_ < ET_LAST)
272 name_ = EventTypeName(type_);
275 ////////////////////////////////////////////////////////////////////////////////
276 // CancelModeEvent
278 CancelModeEvent::CancelModeEvent()
279 : Event(ET_CANCEL_MODE, base::TimeDelta(), 0) {
280 set_cancelable(false);
283 CancelModeEvent::~CancelModeEvent() {
286 ////////////////////////////////////////////////////////////////////////////////
287 // LocatedEvent
289 LocatedEvent::~LocatedEvent() {
292 LocatedEvent::LocatedEvent(const base::NativeEvent& native_event)
293 : Event(native_event,
294 EventTypeFromNative(native_event),
295 EventFlagsFromNative(native_event)),
296 location_(EventLocationFromNative(native_event)),
297 root_location_(location_) {
300 LocatedEvent::LocatedEvent(EventType type,
301 const gfx::PointF& location,
302 const gfx::PointF& root_location,
303 base::TimeDelta time_stamp,
304 int flags)
305 : Event(type, time_stamp, flags),
306 location_(location),
307 root_location_(root_location) {
310 void LocatedEvent::UpdateForRootTransform(
311 const gfx::Transform& reversed_root_transform) {
312 // Transform has to be done at root level.
313 gfx::Point3F p(location_);
314 reversed_root_transform.TransformPoint(&p);
315 location_ = p.AsPointF();
316 root_location_ = location_;
319 ////////////////////////////////////////////////////////////////////////////////
320 // MouseEvent
322 MouseEvent::MouseEvent(const base::NativeEvent& native_event)
323 : LocatedEvent(native_event),
324 changed_button_flags_(
325 GetChangedMouseButtonFlagsFromNative(native_event)) {
326 if (type() == ET_MOUSE_PRESSED || type() == ET_MOUSE_RELEASED)
327 SetClickCount(GetRepeatCount(*this));
330 MouseEvent::MouseEvent(EventType type,
331 const gfx::PointF& location,
332 const gfx::PointF& root_location,
333 base::TimeDelta time_stamp,
334 int flags,
335 int changed_button_flags)
336 : LocatedEvent(type, location, root_location, time_stamp, flags),
337 changed_button_flags_(changed_button_flags) {
338 if (this->type() == ET_MOUSE_MOVED && IsAnyButton())
339 SetType(ET_MOUSE_DRAGGED);
342 // static
343 bool MouseEvent::IsRepeatedClickEvent(
344 const MouseEvent& event1,
345 const MouseEvent& event2) {
346 // These values match the Windows defaults.
347 static const int kDoubleClickTimeMS = 500;
348 static const int kDoubleClickWidth = 4;
349 static const int kDoubleClickHeight = 4;
351 if (event1.type() != ET_MOUSE_PRESSED ||
352 event2.type() != ET_MOUSE_PRESSED)
353 return false;
355 // Compare flags, but ignore EF_IS_DOUBLE_CLICK to allow triple clicks.
356 if ((event1.flags() & ~EF_IS_DOUBLE_CLICK) !=
357 (event2.flags() & ~EF_IS_DOUBLE_CLICK))
358 return false;
360 base::TimeDelta time_difference = event2.time_stamp() - event1.time_stamp();
362 if (time_difference.InMilliseconds() > kDoubleClickTimeMS)
363 return false;
365 if (std::abs(event2.x() - event1.x()) > kDoubleClickWidth / 2)
366 return false;
368 if (std::abs(event2.y() - event1.y()) > kDoubleClickHeight / 2)
369 return false;
371 return true;
374 // static
375 int MouseEvent::GetRepeatCount(const MouseEvent& event) {
376 int click_count = 1;
377 if (last_click_event_) {
378 if (event.type() == ui::ET_MOUSE_RELEASED) {
379 if (event.changed_button_flags() ==
380 last_click_event_->changed_button_flags()) {
381 last_click_complete_ = true;
382 return last_click_event_->GetClickCount();
383 } else {
384 // If last_click_event_ has changed since this button was pressed
385 // return a click count of 1.
386 return click_count;
389 if (event.time_stamp() != last_click_event_->time_stamp())
390 last_click_complete_ = true;
391 if (!last_click_complete_ ||
392 IsX11SendEventTrue(event.native_event())) {
393 click_count = last_click_event_->GetClickCount();
394 } else if (IsRepeatedClickEvent(*last_click_event_, event)) {
395 click_count = last_click_event_->GetClickCount() + 1;
397 delete last_click_event_;
399 last_click_event_ = new MouseEvent(event);
400 last_click_complete_ = false;
401 if (click_count > 3)
402 click_count = 3;
403 last_click_event_->SetClickCount(click_count);
404 return click_count;
407 void MouseEvent::ResetLastClickForTest() {
408 if (last_click_event_) {
409 delete last_click_event_;
410 last_click_event_ = NULL;
411 last_click_complete_ = false;
415 // static
416 MouseEvent* MouseEvent::last_click_event_ = NULL;
417 bool MouseEvent::last_click_complete_ = false;
419 int MouseEvent::GetClickCount() const {
420 if (type() != ET_MOUSE_PRESSED && type() != ET_MOUSE_RELEASED)
421 return 0;
423 if (flags() & EF_IS_TRIPLE_CLICK)
424 return 3;
425 else if (flags() & EF_IS_DOUBLE_CLICK)
426 return 2;
427 else
428 return 1;
431 void MouseEvent::SetClickCount(int click_count) {
432 if (type() != ET_MOUSE_PRESSED && type() != ET_MOUSE_RELEASED)
433 return;
435 DCHECK(click_count > 0);
436 DCHECK(click_count <= 3);
438 int f = flags();
439 switch (click_count) {
440 case 1:
441 f &= ~EF_IS_DOUBLE_CLICK;
442 f &= ~EF_IS_TRIPLE_CLICK;
443 break;
444 case 2:
445 f |= EF_IS_DOUBLE_CLICK;
446 f &= ~EF_IS_TRIPLE_CLICK;
447 break;
448 case 3:
449 f &= ~EF_IS_DOUBLE_CLICK;
450 f |= EF_IS_TRIPLE_CLICK;
451 break;
453 set_flags(f);
456 ////////////////////////////////////////////////////////////////////////////////
457 // MouseWheelEvent
459 MouseWheelEvent::MouseWheelEvent(const base::NativeEvent& native_event)
460 : MouseEvent(native_event),
461 offset_(GetMouseWheelOffset(native_event)) {
464 MouseWheelEvent::MouseWheelEvent(const ScrollEvent& scroll_event)
465 : MouseEvent(scroll_event),
466 offset_(gfx::ToRoundedInt(scroll_event.x_offset()),
467 gfx::ToRoundedInt(scroll_event.y_offset())) {
468 SetType(ET_MOUSEWHEEL);
471 MouseWheelEvent::MouseWheelEvent(const MouseEvent& mouse_event,
472 int x_offset,
473 int y_offset)
474 : MouseEvent(mouse_event), offset_(x_offset, y_offset) {
475 DCHECK(type() == ET_MOUSEWHEEL);
478 MouseWheelEvent::MouseWheelEvent(const MouseWheelEvent& mouse_wheel_event)
479 : MouseEvent(mouse_wheel_event),
480 offset_(mouse_wheel_event.offset()) {
481 DCHECK(type() == ET_MOUSEWHEEL);
484 MouseWheelEvent::MouseWheelEvent(const gfx::Vector2d& offset,
485 const gfx::PointF& location,
486 const gfx::PointF& root_location,
487 base::TimeDelta time_stamp,
488 int flags,
489 int changed_button_flags)
490 : MouseEvent(ui::ET_MOUSEWHEEL,
491 location,
492 root_location,
493 time_stamp,
494 flags,
495 changed_button_flags),
496 offset_(offset) {
499 #if defined(OS_WIN)
500 // This value matches windows WHEEL_DELTA.
501 // static
502 const int MouseWheelEvent::kWheelDelta = 120;
503 #else
504 // This value matches GTK+ wheel scroll amount.
505 const int MouseWheelEvent::kWheelDelta = 53;
506 #endif
508 void MouseWheelEvent::UpdateForRootTransform(
509 const gfx::Transform& inverted_root_transform) {
510 LocatedEvent::UpdateForRootTransform(inverted_root_transform);
511 gfx::DecomposedTransform decomp;
512 bool success = gfx::DecomposeTransform(&decomp, inverted_root_transform);
513 DCHECK(success);
514 if (decomp.scale[0]) {
515 offset_.set_x(
516 gfx::ToRoundedInt(SkMScalarToFloat(offset_.x() * decomp.scale[0])));
518 if (decomp.scale[1]) {
519 offset_.set_y(
520 gfx::ToRoundedInt(SkMScalarToFloat(offset_.y() * decomp.scale[1])));
524 ////////////////////////////////////////////////////////////////////////////////
525 // TouchEvent
527 TouchEvent::TouchEvent(const base::NativeEvent& native_event)
528 : LocatedEvent(native_event),
529 touch_id_(GetTouchId(native_event)),
530 unique_event_id_(get_next_touch_event_id()),
531 radius_x_(GetTouchRadiusX(native_event)),
532 radius_y_(GetTouchRadiusY(native_event)),
533 rotation_angle_(GetTouchAngle(native_event)),
534 force_(GetTouchForce(native_event)),
535 may_cause_scrolling_(false),
536 should_remove_native_touch_id_mapping_(false) {
537 latency()->AddLatencyNumberWithTimestamp(
538 INPUT_EVENT_LATENCY_ORIGINAL_COMPONENT, 0, 0,
539 base::TimeTicks::FromInternalValue(time_stamp().ToInternalValue()), 1);
540 latency()->AddLatencyNumber(INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
542 FixRotationAngle();
543 if (type() == ET_TOUCH_RELEASED || type() == ET_TOUCH_CANCELLED)
544 should_remove_native_touch_id_mapping_ = true;
547 TouchEvent::TouchEvent(EventType type,
548 const gfx::PointF& location,
549 int touch_id,
550 base::TimeDelta time_stamp)
551 : LocatedEvent(type, location, location, time_stamp, 0),
552 touch_id_(touch_id),
553 unique_event_id_(get_next_touch_event_id()),
554 radius_x_(0.0f),
555 radius_y_(0.0f),
556 rotation_angle_(0.0f),
557 force_(0.0f),
558 may_cause_scrolling_(false),
559 should_remove_native_touch_id_mapping_(false) {
560 latency()->AddLatencyNumber(INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
563 TouchEvent::TouchEvent(EventType type,
564 const gfx::PointF& location,
565 int flags,
566 int touch_id,
567 base::TimeDelta time_stamp,
568 float radius_x,
569 float radius_y,
570 float angle,
571 float force)
572 : LocatedEvent(type, location, location, time_stamp, flags),
573 touch_id_(touch_id),
574 unique_event_id_(get_next_touch_event_id()),
575 radius_x_(radius_x),
576 radius_y_(radius_y),
577 rotation_angle_(angle),
578 force_(force),
579 may_cause_scrolling_(false),
580 should_remove_native_touch_id_mapping_(false) {
581 latency()->AddLatencyNumber(INPUT_EVENT_LATENCY_UI_COMPONENT, 0, 0);
582 FixRotationAngle();
585 TouchEvent::~TouchEvent() {
586 // In ctor TouchEvent(native_event) we call GetTouchId() which in X11
587 // platform setups the tracking_id to slot mapping. So in dtor here,
588 // if this touch event is a release event, we clear the mapping accordingly.
589 if (should_remove_native_touch_id_mapping_) {
590 DCHECK(type() == ET_TOUCH_RELEASED || type() == ET_TOUCH_CANCELLED);
591 if (type() == ET_TOUCH_RELEASED || type() == ET_TOUCH_CANCELLED)
592 ClearTouchIdIfReleased(native_event());
596 void TouchEvent::UpdateForRootTransform(
597 const gfx::Transform& inverted_root_transform) {
598 LocatedEvent::UpdateForRootTransform(inverted_root_transform);
599 gfx::DecomposedTransform decomp;
600 bool success = gfx::DecomposeTransform(&decomp, inverted_root_transform);
601 DCHECK(success);
602 if (decomp.scale[0])
603 radius_x_ *= decomp.scale[0];
604 if (decomp.scale[1])
605 radius_y_ *= decomp.scale[1];
608 void TouchEvent::DisableSynchronousHandling() {
609 DispatcherApi dispatcher_api(this);
610 dispatcher_api.set_result(
611 static_cast<EventResult>(result() | ER_DISABLE_SYNC_HANDLING));
614 void TouchEvent::FixRotationAngle() {
615 while (rotation_angle_ < 0)
616 rotation_angle_ += 180;
617 while (rotation_angle_ >= 180)
618 rotation_angle_ -= 180;
621 ////////////////////////////////////////////////////////////////////////////////
622 // KeyEvent
624 // static
625 KeyEvent* KeyEvent::last_key_event_ = NULL;
627 // static
628 bool KeyEvent::IsRepeated(const KeyEvent& event) {
629 // A safe guard in case if there were continous key pressed events that are
630 // not auto repeat.
631 const int kMaxAutoRepeatTimeMs = 2000;
632 // Ignore key events that have non standard state masks as it may be
633 // reposted by an IME. IBUS-GTK uses this field to detect the
634 // re-posted event for example. crbug.com/385873.
635 if (X11EventHasNonStandardState(event.native_event()))
636 return false;
637 if (event.is_char())
638 return false;
639 if (event.type() == ui::ET_KEY_RELEASED) {
640 delete last_key_event_;
641 last_key_event_ = NULL;
642 return false;
644 CHECK_EQ(ui::ET_KEY_PRESSED, event.type());
645 if (!last_key_event_) {
646 last_key_event_ = new KeyEvent(event);
647 return false;
649 if (event.key_code() == last_key_event_->key_code() &&
650 event.flags() == last_key_event_->flags() &&
651 (event.time_stamp() - last_key_event_->time_stamp()).InMilliseconds() <
652 kMaxAutoRepeatTimeMs) {
653 last_key_event_->set_time_stamp(event.time_stamp());
654 return true;
656 delete last_key_event_;
657 last_key_event_ = new KeyEvent(event);
658 return false;
661 KeyEvent::KeyEvent(const base::NativeEvent& native_event)
662 : Event(native_event,
663 EventTypeFromNative(native_event),
664 EventFlagsFromNative(native_event)),
665 key_code_(KeyboardCodeFromNative(native_event)),
666 code_(CodeFromNative(native_event)),
667 is_char_(IsCharFromNative(native_event)),
668 platform_keycode_(PlatformKeycodeFromNative(native_event)),
669 key_(DomKey::NONE),
670 character_(0) {
671 if (IsRepeated(*this))
672 set_flags(flags() | ui::EF_IS_REPEAT);
674 #if defined(USE_X11)
675 NormalizeFlags();
676 #endif
677 #if defined(OS_WIN)
678 // Only Windows has native character events.
679 if (is_char_)
680 character_ = native_event.wParam;
681 #endif
684 KeyEvent::KeyEvent(EventType type,
685 KeyboardCode key_code,
686 int flags)
687 : Event(type, EventTimeForNow(), flags),
688 key_code_(key_code),
689 code_(DomCode::NONE),
690 is_char_(false),
691 platform_keycode_(0),
692 key_(DomKey::NONE),
693 character_() {
696 KeyEvent::KeyEvent(EventType type,
697 KeyboardCode key_code,
698 DomCode code,
699 int flags)
700 : Event(type, EventTimeForNow(), flags),
701 key_code_(key_code),
702 code_(code),
703 is_char_(false),
704 platform_keycode_(0),
705 key_(DomKey::NONE),
706 character_(0) {
709 KeyEvent::KeyEvent(EventType type,
710 KeyboardCode key_code,
711 DomCode code,
712 int flags,
713 DomKey key,
714 base::char16 character,
715 base::TimeDelta time_stamp)
716 : Event(type, time_stamp, flags),
717 key_code_(key_code),
718 code_(code),
719 is_char_(false),
720 platform_keycode_(0),
721 key_(key),
722 character_(character) {
725 KeyEvent::KeyEvent(base::char16 character, KeyboardCode key_code, int flags)
726 : Event(ET_KEY_PRESSED, EventTimeForNow(), flags),
727 key_code_(key_code),
728 code_(DomCode::NONE),
729 is_char_(true),
730 platform_keycode_(0),
731 key_(DomKey::CHARACTER),
732 character_(character) {
735 KeyEvent::KeyEvent(const KeyEvent& rhs)
736 : Event(rhs),
737 key_code_(rhs.key_code_),
738 code_(rhs.code_),
739 is_char_(rhs.is_char_),
740 platform_keycode_(rhs.platform_keycode_),
741 key_(rhs.key_),
742 character_(rhs.character_) {
743 if (rhs.extended_key_event_data_)
744 extended_key_event_data_.reset(rhs.extended_key_event_data_->Clone());
747 KeyEvent& KeyEvent::operator=(const KeyEvent& rhs) {
748 if (this != &rhs) {
749 Event::operator=(rhs);
750 key_code_ = rhs.key_code_;
751 code_ = rhs.code_;
752 key_ = rhs.key_;
753 is_char_ = rhs.is_char_;
754 platform_keycode_ = rhs.platform_keycode_;
755 character_ = rhs.character_;
757 if (rhs.extended_key_event_data_)
758 extended_key_event_data_.reset(rhs.extended_key_event_data_->Clone());
760 return *this;
763 KeyEvent::~KeyEvent() {}
765 void KeyEvent::SetExtendedKeyEventData(scoped_ptr<ExtendedKeyEventData> data) {
766 extended_key_event_data_ = data.Pass();
769 void KeyEvent::ApplyLayout() const {
770 // If the client has set the character (e.g. faked key events from virtual
771 // keyboard), it's client's responsibility to set the dom key correctly.
772 // Otherwise, set the dom key as unidentified.
773 // Please refer to crbug.com/443889.
774 if (character_ != 0) {
775 key_ = DomKey::UNIDENTIFIED;
776 return;
778 #if defined(OS_WIN)
779 // Native Windows character events always have is_char_ == true,
780 // so this is a synthetic or native keystroke event.
781 // Therefore, perform only the fallback action.
782 GetMeaningFromKeyCode(key_code_, flags(), &key_, &character_);
783 #elif defined(USE_X11)
784 // When a control key is held, prefer ASCII characters to non ASCII
785 // characters in order to use it for shortcut keys. GetCharacterFromKeyCode
786 // returns 'a' for VKEY_A even if the key is actually bound to 'à' in X11.
787 // GetCharacterFromXEvent returns 'à' in that case.
788 character_ = (IsControlDown() || !native_event()) ?
789 GetCharacterFromKeyCode(key_code_, flags()) :
790 GetCharacterFromXEvent(native_event());
791 // TODO(kpschoedel): set key_ field for X11.
792 #elif defined(USE_OZONE)
793 KeyboardCode key_code;
794 if (!KeyboardLayoutEngineManager::GetKeyboardLayoutEngine()->Lookup(
795 code_, flags(), &key_, &character_, &key_code, &platform_keycode_)) {
796 GetMeaningFromKeyCode(key_code_, flags(), &key_, &character_);
798 #else
799 if (native_event()) {
800 DCHECK(EventTypeFromNative(native_event()) == ET_KEY_PRESSED ||
801 EventTypeFromNative(native_event()) == ET_KEY_RELEASED);
803 // TODO(kpschoedel): revise to use DOM code_ instead of Windows key_code_
804 GetMeaningFromKeyCode(key_code_, flags(), &key_, &character_);
805 #endif
808 DomKey KeyEvent::GetDomKey() const {
809 // Determination of character_ and key_ may be done lazily.
810 if (key_ == DomKey::NONE)
811 ApplyLayout();
812 return key_;
815 base::char16 KeyEvent::GetCharacter() const {
816 // Determination of character_ and key_ may be done lazily.
817 if (key_ == DomKey::NONE)
818 ApplyLayout();
819 return character_;
822 base::char16 KeyEvent::GetText() const {
823 if ((flags() & EF_CONTROL_DOWN) != 0) {
824 // TODO(kpschoedel): revise to use DOM code_ instead of Windows key_code_
825 return GetControlCharacterForKeycode(key_code_,
826 (flags() & EF_SHIFT_DOWN) != 0);
828 return GetUnmodifiedText();
831 base::char16 KeyEvent::GetUnmodifiedText() const {
832 if (!is_char_ && (key_code_ == VKEY_RETURN))
833 return '\r';
834 return GetCharacter();
837 bool KeyEvent::IsUnicodeKeyCode() const {
838 #if defined(OS_WIN)
839 if (!IsAltDown())
840 return false;
841 const int key = key_code();
842 if (key >= VKEY_NUMPAD0 && key <= VKEY_NUMPAD9)
843 return true;
844 // Check whether the user is using the numeric keypad with num-lock off.
845 // In that case, EF_EXTENDED will not be set; if it is set, the key event
846 // originated from the relevant non-numpad dedicated key, e.g. [Insert].
847 return (!(flags() & EF_EXTENDED) &&
848 (key == VKEY_INSERT || key == VKEY_END || key == VKEY_DOWN ||
849 key == VKEY_NEXT || key == VKEY_LEFT || key == VKEY_CLEAR ||
850 key == VKEY_RIGHT || key == VKEY_HOME || key == VKEY_UP ||
851 key == VKEY_PRIOR));
852 #else
853 return false;
854 #endif
857 void KeyEvent::NormalizeFlags() {
858 int mask = 0;
859 switch (key_code()) {
860 case VKEY_CONTROL:
861 mask = EF_CONTROL_DOWN;
862 break;
863 case VKEY_SHIFT:
864 mask = EF_SHIFT_DOWN;
865 break;
866 case VKEY_MENU:
867 mask = EF_ALT_DOWN;
868 break;
869 case VKEY_CAPITAL:
870 mask = EF_CAPS_LOCK_DOWN;
871 break;
872 default:
873 return;
875 if (type() == ET_KEY_PRESSED)
876 set_flags(flags() | mask);
877 else
878 set_flags(flags() & ~mask);
881 bool KeyEvent::IsTranslated() const {
882 switch (type()) {
883 case ET_KEY_PRESSED:
884 case ET_KEY_RELEASED:
885 return false;
886 case ET_TRANSLATED_KEY_PRESS:
887 case ET_TRANSLATED_KEY_RELEASE:
888 return true;
889 default:
890 NOTREACHED();
891 return false;
895 void KeyEvent::SetTranslated(bool translated) {
896 switch (type()) {
897 case ET_KEY_PRESSED:
898 case ET_TRANSLATED_KEY_PRESS:
899 SetType(translated ? ET_TRANSLATED_KEY_PRESS : ET_KEY_PRESSED);
900 break;
901 case ET_KEY_RELEASED:
902 case ET_TRANSLATED_KEY_RELEASE:
903 SetType(translated ? ET_TRANSLATED_KEY_RELEASE : ET_KEY_RELEASED);
904 break;
905 default:
906 NOTREACHED();
910 KeyboardCode KeyEvent::GetLocatedWindowsKeyboardCode() const {
911 return NonLocatedToLocatedKeyboardCode(key_code_, code_);
914 uint16 KeyEvent::GetConflatedWindowsKeyCode() const {
915 if (is_char_)
916 return character_;
917 return key_code_;
920 std::string KeyEvent::GetCodeString() const {
921 return KeycodeConverter::DomCodeToCodeString(code_);
924 ////////////////////////////////////////////////////////////////////////////////
925 // ScrollEvent
927 ScrollEvent::ScrollEvent(const base::NativeEvent& native_event)
928 : MouseEvent(native_event) {
929 if (type() == ET_SCROLL) {
930 GetScrollOffsets(native_event,
931 &x_offset_, &y_offset_,
932 &x_offset_ordinal_, &y_offset_ordinal_,
933 &finger_count_);
934 } else if (type() == ET_SCROLL_FLING_START ||
935 type() == ET_SCROLL_FLING_CANCEL) {
936 GetFlingData(native_event,
937 &x_offset_, &y_offset_,
938 &x_offset_ordinal_, &y_offset_ordinal_,
939 NULL);
940 } else {
941 NOTREACHED() << "Unexpected event type " << type()
942 << " when constructing a ScrollEvent.";
946 ScrollEvent::ScrollEvent(EventType type,
947 const gfx::PointF& location,
948 base::TimeDelta time_stamp,
949 int flags,
950 float x_offset,
951 float y_offset,
952 float x_offset_ordinal,
953 float y_offset_ordinal,
954 int finger_count)
955 : MouseEvent(type, location, location, time_stamp, flags, 0),
956 x_offset_(x_offset),
957 y_offset_(y_offset),
958 x_offset_ordinal_(x_offset_ordinal),
959 y_offset_ordinal_(y_offset_ordinal),
960 finger_count_(finger_count) {
961 CHECK(IsScrollEvent());
964 void ScrollEvent::Scale(const float factor) {
965 x_offset_ *= factor;
966 y_offset_ *= factor;
967 x_offset_ordinal_ *= factor;
968 y_offset_ordinal_ *= factor;
971 ////////////////////////////////////////////////////////////////////////////////
972 // GestureEvent
974 GestureEvent::GestureEvent(float x,
975 float y,
976 int flags,
977 base::TimeDelta time_stamp,
978 const GestureEventDetails& details)
979 : LocatedEvent(details.type(),
980 gfx::PointF(x, y),
981 gfx::PointF(x, y),
982 time_stamp,
983 flags | EF_FROM_TOUCH),
984 details_(details) {
987 GestureEvent::~GestureEvent() {
990 } // namespace ui