event.h 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086
  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.
  4. #ifndef UI_EVENTS_EVENT_H_
  5. #define UI_EVENTS_EVENT_H_
  6. #include <cstdint>
  7. #include <memory>
  8. #include <string>
  9. #include <vector>
  10. #include "base/containers/flat_map.h"
  11. #include "base/gtest_prod_util.h"
  12. #include "base/memory/raw_ptr.h"
  13. #include "base/time/time.h"
  14. #include "ui/events/event_constants.h"
  15. #include "ui/events/gesture_event_details.h"
  16. #include "ui/events/gestures/gesture_types.h"
  17. #include "ui/events/keycodes/dom/dom_key.h"
  18. #include "ui/events/keycodes/keyboard_codes.h"
  19. #include "ui/events/platform_event.h"
  20. #include "ui/events/pointer_details.h"
  21. #include "ui/events/types/event_type.h"
  22. #include "ui/gfx/geometry/point.h"
  23. #include "ui/gfx/geometry/point_conversions.h"
  24. #include "ui/latency/latency_info.h"
  25. namespace gfx {
  26. class Transform;
  27. }
  28. namespace ui {
  29. class CancelModeEvent;
  30. class Event;
  31. class EventTarget;
  32. class KeyEvent;
  33. class LocatedEvent;
  34. class MouseEvent;
  35. class MouseWheelEvent;
  36. class ScrollEvent;
  37. class TouchEvent;
  38. enum class DomCode;
  39. // Note: In order for Clone() to work properly, every concrete class
  40. // transitively inheriting Event must implement Clone() explicitly, even if any
  41. // ancestors have provided an implementation.
  42. class EVENTS_EXPORT Event {
  43. public:
  44. using Properties = base::flat_map<std::string, std::vector<uint8_t>>;
  45. virtual ~Event();
  46. class DispatcherApi {
  47. public:
  48. explicit DispatcherApi(Event* event) : event_(event) {}
  49. DispatcherApi(const DispatcherApi&) = delete;
  50. DispatcherApi& operator=(const DispatcherApi&) = delete;
  51. void set_target(EventTarget* target) { event_->target_ = target; }
  52. void set_phase(EventPhase phase) { event_->phase_ = phase; }
  53. void set_result(int result) {
  54. event_->result_ = static_cast<EventResult>(result);
  55. }
  56. void set_time_stamp(base::TimeTicks time) { event_->time_stamp_ = time; }
  57. private:
  58. raw_ptr<Event, DanglingUntriaged> event_;
  59. };
  60. void SetNativeEvent(const PlatformEvent& event);
  61. const PlatformEvent& native_event() const { return native_event_; }
  62. EventType type() const { return type_; }
  63. // time_stamp represents time since machine was booted.
  64. const base::TimeTicks time_stamp() const { return time_stamp_; }
  65. int flags() const { return flags_; }
  66. // Returns a name for the event, typically used in logging/debugging. This is
  67. // a convenience for EventTypeName(type()) (EventTypeName() is in
  68. // event_utils).
  69. const char* GetName() const;
  70. // This is only intended to be used externally by classes that are modifying
  71. // events in an EventRewriter.
  72. void set_flags(int flags) { flags_ = flags; }
  73. EventTarget* target() const { return target_; }
  74. EventPhase phase() const { return phase_; }
  75. EventResult result() const { return result_; }
  76. LatencyInfo* latency() { return &latency_; }
  77. const LatencyInfo* latency() const { return &latency_; }
  78. void set_latency(const LatencyInfo& latency) { latency_ = latency; }
  79. int source_device_id() const { return source_device_id_; }
  80. void set_source_device_id(int id) { source_device_id_ = id; }
  81. // Sets the properties associated with this Event.
  82. void SetProperties(const Properties& properties);
  83. // Returns the properties associated with this event, which may be null.
  84. // The properties are meant to provide a way to associate arbitrary key/value
  85. // pairs with Events and not used by Event.
  86. const Properties* properties() const { return properties_.get(); }
  87. // By default, events are "cancelable", this means any default processing that
  88. // the containing abstraction layer may perform can be prevented by calling
  89. // SetHandled(). SetHandled() or StopPropagation() must not be called for
  90. // events that are not cancelable.
  91. bool cancelable() const { return cancelable_; }
  92. // The following methods return true if the respective keys were pressed at
  93. // the time the event was created.
  94. bool IsShiftDown() const { return (flags_ & EF_SHIFT_DOWN) != 0; }
  95. bool IsControlDown() const { return (flags_ & EF_CONTROL_DOWN) != 0; }
  96. bool IsAltDown() const { return (flags_ & EF_ALT_DOWN) != 0; }
  97. bool IsCommandDown() const { return (flags_ & EF_COMMAND_DOWN) != 0; }
  98. bool IsAltGrDown() const { return (flags_ & EF_ALTGR_DOWN) != 0; }
  99. bool IsCapsLockOn() const { return (flags_ & EF_CAPS_LOCK_ON) != 0; }
  100. bool IsSynthesized() const { return (flags_ & EF_IS_SYNTHESIZED) != 0; }
  101. bool IsCancelModeEvent() const { return type_ == ET_CANCEL_MODE; }
  102. bool IsKeyEvent() const {
  103. return type_ == ET_KEY_PRESSED || type_ == ET_KEY_RELEASED;
  104. }
  105. bool IsMouseEvent() const {
  106. return type_ == ET_MOUSE_PRESSED ||
  107. type_ == ET_MOUSE_DRAGGED ||
  108. type_ == ET_MOUSE_RELEASED ||
  109. type_ == ET_MOUSE_MOVED ||
  110. type_ == ET_MOUSE_ENTERED ||
  111. type_ == ET_MOUSE_EXITED ||
  112. type_ == ET_MOUSEWHEEL ||
  113. type_ == ET_MOUSE_CAPTURE_CHANGED;
  114. }
  115. bool IsTouchEvent() const {
  116. return type_ == ET_TOUCH_RELEASED ||
  117. type_ == ET_TOUCH_PRESSED ||
  118. type_ == ET_TOUCH_MOVED ||
  119. type_ == ET_TOUCH_CANCELLED;
  120. }
  121. bool IsGestureEvent() const {
  122. switch (type_) {
  123. case ET_GESTURE_SCROLL_BEGIN:
  124. case ET_GESTURE_SCROLL_END:
  125. case ET_GESTURE_SCROLL_UPDATE:
  126. case ET_GESTURE_TAP:
  127. case ET_GESTURE_DOUBLE_TAP:
  128. case ET_GESTURE_TAP_CANCEL:
  129. case ET_GESTURE_TAP_DOWN:
  130. case ET_GESTURE_TAP_UNCONFIRMED:
  131. case ET_GESTURE_BEGIN:
  132. case ET_GESTURE_END:
  133. case ET_GESTURE_TWO_FINGER_TAP:
  134. case ET_GESTURE_PINCH_BEGIN:
  135. case ET_GESTURE_PINCH_END:
  136. case ET_GESTURE_PINCH_UPDATE:
  137. case ET_GESTURE_LONG_PRESS:
  138. case ET_GESTURE_LONG_TAP:
  139. case ET_GESTURE_SWIPE:
  140. case ET_GESTURE_SHOW_PRESS:
  141. // When adding a gesture event which is paired with an event which
  142. // occurs earlier, add the event to |IsEndingEvent|.
  143. return true;
  144. case ET_SCROLL_FLING_CANCEL:
  145. case ET_SCROLL_FLING_START:
  146. // These can be ScrollEvents too. EF_FROM_TOUCH determines if they're
  147. // Gesture or Scroll events.
  148. return (flags_ & EF_FROM_TOUCH) == EF_FROM_TOUCH;
  149. default:
  150. break;
  151. }
  152. return false;
  153. }
  154. // An ending event is paired with the event which started it. Setting capture
  155. // should not prevent ending events from getting to their initial target.
  156. bool IsEndingEvent() const {
  157. switch (type_) {
  158. case ET_TOUCH_CANCELLED:
  159. case ET_GESTURE_TAP_CANCEL:
  160. case ET_GESTURE_END:
  161. case ET_GESTURE_SCROLL_END:
  162. case ET_GESTURE_PINCH_END:
  163. return true;
  164. default:
  165. return false;
  166. }
  167. }
  168. bool IsScrollEvent() const {
  169. // Flings can be GestureEvents too. EF_FROM_TOUCH determines if they're
  170. // Gesture or Scroll events.
  171. return type_ == ET_SCROLL || ((type_ == ET_SCROLL_FLING_START ||
  172. type_ == ET_SCROLL_FLING_CANCEL) &&
  173. !(flags() & EF_FROM_TOUCH));
  174. }
  175. bool IsPinchEvent() const {
  176. return type_ == ET_GESTURE_PINCH_BEGIN ||
  177. type_ == ET_GESTURE_PINCH_UPDATE || type_ == ET_GESTURE_PINCH_END;
  178. }
  179. bool IsScrollGestureEvent() const {
  180. return type_ == ET_GESTURE_SCROLL_BEGIN ||
  181. type_ == ET_GESTURE_SCROLL_UPDATE || type_ == ET_GESTURE_SCROLL_END;
  182. }
  183. bool IsFlingScrollEvent() const {
  184. return type_ == ET_SCROLL_FLING_CANCEL || type_ == ET_SCROLL_FLING_START;
  185. }
  186. bool IsMouseWheelEvent() const { return type_ == ET_MOUSEWHEEL; }
  187. bool IsLocatedEvent() const {
  188. return IsMouseEvent() || IsScrollEvent() || IsTouchEvent() ||
  189. IsGestureEvent() || type_ == ET_DROP_TARGET_EVENT;
  190. }
  191. // Convenience methods to cast |this| to a CancelModeEvent.
  192. // IsCancelModeEvent() must be true as a precondition to calling these
  193. // methods.
  194. CancelModeEvent* AsCancelModeEvent();
  195. const CancelModeEvent* AsCancelModeEvent() const;
  196. // Convenience methods to cast |this| to a GestureEvent. IsGestureEvent()
  197. // must be true as a precondition to calling these methods.
  198. GestureEvent* AsGestureEvent();
  199. const GestureEvent* AsGestureEvent() const;
  200. // Convenience methods to cast |this| to a KeyEvent. IsKeyEvent()
  201. // must be true as a precondition to calling these methods.
  202. KeyEvent* AsKeyEvent();
  203. const KeyEvent* AsKeyEvent() const;
  204. // Convenience methods to cast |this| to a LocatedEvent. IsLocatedEvent()
  205. // must be true as a precondition to calling these methods.
  206. LocatedEvent* AsLocatedEvent();
  207. const LocatedEvent* AsLocatedEvent() const;
  208. // Convenience methods to cast |this| to a MouseEvent. IsMouseEvent()
  209. // must be true as a precondition to calling these methods.
  210. MouseEvent* AsMouseEvent();
  211. const MouseEvent* AsMouseEvent() const;
  212. // Convenience methods to cast |this| to a MouseWheelEvent.
  213. // IsMouseWheelEvent() must be true as a precondition to calling these
  214. // methods.
  215. MouseWheelEvent* AsMouseWheelEvent();
  216. const MouseWheelEvent* AsMouseWheelEvent() const;
  217. // Convenience methods to cast |this| to a ScrollEvent. IsScrollEvent()
  218. // must be true as a precondition to calling these methods.
  219. ScrollEvent* AsScrollEvent();
  220. const ScrollEvent* AsScrollEvent() const;
  221. // Convenience methods to cast |this| to a TouchEvent. IsTouchEvent()
  222. // must be true as a precondition to calling these methods.
  223. TouchEvent* AsTouchEvent();
  224. const TouchEvent* AsTouchEvent() const;
  225. // Returns true if the event has a valid |native_event_|.
  226. bool HasNativeEvent() const;
  227. // Immediately stops the propagation of the event. This must be called only
  228. // from an EventHandler during an event-dispatch. Any event handler that may
  229. // be in the list will not receive the event after this is called.
  230. // Note that StopPropagation() can be called only for cancelable events.
  231. void StopPropagation();
  232. bool stopped_propagation() const { return !!(result_ & ER_CONSUMED); }
  233. // Marks the event as having been handled. A handled event does not reach the
  234. // next event phase. For example, if an event is handled during the pre-target
  235. // phase, then the event is dispatched to all pre-target handlers, but not to
  236. // the target or post-target handlers.
  237. // Note that SetHandled() can be called only for cancelable events.
  238. void SetHandled();
  239. bool handled() const { return result_ != ER_UNHANDLED; }
  240. // For debugging. Not a stable serialization format.
  241. virtual std::string ToString() const;
  242. // Copies an arbitrary event. If you have a typed event (e.g. a MouseEvent)
  243. // just use its copy constructor.
  244. //
  245. // Every concrete class transitively inheriting Event must implement this
  246. // method, even if any ancestors have provided an implementation.
  247. virtual std::unique_ptr<Event> Clone() const = 0;
  248. protected:
  249. Event(EventType type, base::TimeTicks time_stamp, int flags);
  250. Event(const PlatformEvent& native_event, EventType type, int flags);
  251. Event(const Event& copy);
  252. Event& operator=(const Event& rhs);
  253. void SetType(EventType type);
  254. void set_cancelable(bool cancelable) { cancelable_ = cancelable; }
  255. void set_time_stamp(base::TimeTicks time_stamp) { time_stamp_ = time_stamp; }
  256. private:
  257. friend class EventTestApi;
  258. EventType type_;
  259. base::TimeTicks time_stamp_;
  260. LatencyInfo latency_;
  261. int flags_;
  262. PlatformEvent native_event_;
  263. bool delete_native_event_ = false;
  264. bool cancelable_ = true;
  265. // Neither Event copy constructor nor the assignment operator copies
  266. // `target_`, as `target_` should be explicitly set so the setter will be
  267. // responsible for tracking it.
  268. //
  269. // TODO(crbug.com/1298696): Breaks events_unittests.
  270. raw_ptr<EventTarget, DegradeToNoOpWhenMTE> target_ = nullptr;
  271. EventPhase phase_ = EP_PREDISPATCH;
  272. EventResult result_ = ER_UNHANDLED;
  273. // The device id the event came from, or ED_UNKNOWN_DEVICE if the information
  274. // is not available.
  275. int source_device_id_ = ED_UNKNOWN_DEVICE;
  276. std::unique_ptr<Properties> properties_;
  277. };
  278. class EVENTS_EXPORT CancelModeEvent : public Event {
  279. public:
  280. CancelModeEvent();
  281. ~CancelModeEvent() override;
  282. // Event:
  283. std::unique_ptr<Event> Clone() const override;
  284. };
  285. class EVENTS_EXPORT LocatedEvent : public Event {
  286. public:
  287. // Convenience function that casts |event| to a LocatedEvent if it is one,
  288. // otherwise returns null.
  289. static const LocatedEvent* FromIfValid(const Event* event) {
  290. return event && event->IsLocatedEvent() ? event->AsLocatedEvent() : nullptr;
  291. }
  292. ~LocatedEvent() override;
  293. float x() const { return location_.x(); }
  294. float y() const { return location_.y(); }
  295. void set_location(const gfx::Point& location) {
  296. location_ = gfx::PointF(location);
  297. }
  298. void set_location_f(const gfx::PointF& location) { location_ = location; }
  299. gfx::Point location() const { return gfx::ToFlooredPoint(location_); }
  300. const gfx::PointF& location_f() const { return location_; }
  301. void set_root_location(const gfx::Point& root_location) {
  302. root_location_ = gfx::PointF(root_location);
  303. }
  304. void set_root_location_f(const gfx::PointF& root_location) {
  305. root_location_ = root_location;
  306. }
  307. gfx::Point root_location() const {
  308. return gfx::ToFlooredPoint(root_location_);
  309. }
  310. const gfx::PointF& root_location_f() const { return root_location_; }
  311. // Transform the locations using |inverted_root_transform| and
  312. // |inverted_local_transform|. |inverted_local_transform| is only used if
  313. // the event has a target.
  314. virtual void UpdateForRootTransform(
  315. const gfx::Transform& inverted_root_transform,
  316. const gfx::Transform& inverted_local_transform);
  317. template <class T>
  318. void ConvertLocationToTarget(const T* source, const T* target) {
  319. if (!target || target == source)
  320. return;
  321. gfx::Point offset = gfx::ToFlooredPoint(location_);
  322. T::ConvertPointToTarget(source, target, &offset);
  323. gfx::Vector2d diff = gfx::ToFlooredPoint(location_) - offset;
  324. location_ = location_ - diff;
  325. }
  326. // Event:
  327. std::string ToString() const override;
  328. protected:
  329. friend class LocatedEventTestApi;
  330. LocatedEvent(const LocatedEvent& copy);
  331. explicit LocatedEvent(const PlatformEvent& native_event);
  332. // Create a new LocatedEvent which is identical to the provided model.
  333. // If source / target windows are provided, the model location will be
  334. // converted from |source| coordinate system to |target| coordinate system.
  335. template <class T>
  336. LocatedEvent(const LocatedEvent& model, T* source, T* target)
  337. : Event(model),
  338. location_(model.location_),
  339. root_location_(model.root_location_) {
  340. ConvertLocationToTarget(source, target);
  341. }
  342. // Used for synthetic events in testing.
  343. LocatedEvent(EventType type,
  344. const gfx::PointF& location,
  345. const gfx::PointF& root_location,
  346. base::TimeTicks time_stamp,
  347. int flags);
  348. // Location of the event relative to the target window and in the target
  349. // window's coordinate space. If there is no target this is the same as
  350. // |root_location_|. Native events may generate float values with sub-pixel
  351. // precision.
  352. gfx::PointF location_;
  353. // Location of the event. What coordinate system this is in depends upon the
  354. // phase of event dispatch. For client code (meaning EventHandlers) it is
  355. // generally in screen coordinates, but early on it may be in pixels and
  356. // relative to a display. Native events may generate float values with
  357. // sub-pixel precision.
  358. gfx::PointF root_location_;
  359. };
  360. class EVENTS_EXPORT MouseEvent : public LocatedEvent {
  361. public:
  362. // NOTE: On some platforms this will allow an event to be constructed from a
  363. // void*, see PlatformEvent.
  364. explicit MouseEvent(const PlatformEvent& native_event);
  365. // Create a new MouseEvent based on the provided model.
  366. // Uses the provided |type| and |flags| for the new event.
  367. // If source / target windows are provided, the model location will be
  368. // converted from |source| coordinate system to |target| coordinate system.
  369. template <class T>
  370. MouseEvent(const MouseEvent& model, T* source, T* target)
  371. : LocatedEvent(model, source, target),
  372. changed_button_flags_(model.changed_button_flags_),
  373. movement_(model.movement_),
  374. pointer_details_(model.pointer_details_) {}
  375. template <class T>
  376. MouseEvent(const MouseEvent& model,
  377. T* source,
  378. T* target,
  379. EventType type,
  380. int flags)
  381. : LocatedEvent(model, source, target),
  382. changed_button_flags_(model.changed_button_flags_),
  383. movement_(model.movement_),
  384. pointer_details_(model.pointer_details_) {
  385. SetType(type);
  386. set_flags(flags);
  387. }
  388. // Note: Use the ctor for MouseWheelEvent if type is ET_MOUSEWHEEL.
  389. MouseEvent(EventType type,
  390. const gfx::PointF& location,
  391. const gfx::PointF& root_location,
  392. base::TimeTicks time_stamp,
  393. int flags,
  394. int changed_button_flags,
  395. const PointerDetails& pointer_details =
  396. PointerDetails(EventPointerType::kMouse, kPointerIdMouse));
  397. // DEPRECATED: Prefer constructor that takes gfx::PointF.
  398. MouseEvent(EventType type,
  399. const gfx::Point& location,
  400. const gfx::Point& root_location,
  401. base::TimeTicks time_stamp,
  402. int flags,
  403. int changed_button_flags,
  404. const PointerDetails& pointer_details =
  405. PointerDetails(EventPointerType::kMouse, kPointerIdMouse));
  406. MouseEvent(const MouseEvent& copy);
  407. ~MouseEvent() override;
  408. void InitializeNative();
  409. class DispatcherApi {
  410. public:
  411. explicit DispatcherApi(MouseEvent* event) : event_(event) {}
  412. DispatcherApi(const DispatcherApi&) = delete;
  413. DispatcherApi& operator=(const DispatcherApi&) = delete;
  414. // TODO(eirage): convert this to builder pattern.
  415. void set_movement(const gfx::Vector2dF& movement) {
  416. event_->movement_ = movement;
  417. event_->set_flags(event_->flags() | EF_UNADJUSTED_MOUSE);
  418. }
  419. private:
  420. raw_ptr<MouseEvent> event_;
  421. };
  422. // Conveniences to quickly test what button is down
  423. bool IsOnlyLeftMouseButton() const {
  424. return button_flags() == EF_LEFT_MOUSE_BUTTON;
  425. }
  426. bool IsLeftMouseButton() const {
  427. return (flags() & EF_LEFT_MOUSE_BUTTON) != 0;
  428. }
  429. bool IsOnlyMiddleMouseButton() const {
  430. return button_flags() == EF_MIDDLE_MOUSE_BUTTON;
  431. }
  432. bool IsMiddleMouseButton() const {
  433. return (flags() & EF_MIDDLE_MOUSE_BUTTON) != 0;
  434. }
  435. bool IsOnlyRightMouseButton() const {
  436. return button_flags() == EF_RIGHT_MOUSE_BUTTON;
  437. }
  438. bool IsRightMouseButton() const {
  439. return (flags() & EF_RIGHT_MOUSE_BUTTON) != 0;
  440. }
  441. bool IsAnyButton() const { return button_flags() != 0; }
  442. // Returns the flags for the mouse buttons.
  443. int button_flags() const {
  444. return flags() & (EF_LEFT_MOUSE_BUTTON | EF_MIDDLE_MOUSE_BUTTON |
  445. EF_RIGHT_MOUSE_BUTTON | EF_BACK_MOUSE_BUTTON |
  446. EF_FORWARD_MOUSE_BUTTON);
  447. }
  448. // Compares two mouse down events and returns true if the second one should
  449. // be considered a repeat of the first.
  450. static bool IsRepeatedClickEvent(const MouseEvent& event1,
  451. const MouseEvent& event2);
  452. // Get the click count. Can be 1, 2 or 3 for mousedown messages, 0 otherwise.
  453. int GetClickCount() const;
  454. // Set the click count for a mousedown message. Can be 1, 2 or 3.
  455. void SetClickCount(int click_count);
  456. // Identifies the button that changed. During a press this corresponds to the
  457. // button that was pressed and during a release this corresponds to the button
  458. // that was released.
  459. // NOTE: during a press and release flags() contains the complete set of
  460. // flags. Use this to determine the button that was pressed or released.
  461. int changed_button_flags() const { return changed_button_flags_; }
  462. // Updates the button that changed.
  463. void set_changed_button_flags(int flags) { changed_button_flags_ = flags; }
  464. const gfx::Vector2dF& movement() const { return movement_; }
  465. const PointerDetails& pointer_details() const { return pointer_details_; }
  466. // Event:
  467. std::string ToString() const override;
  468. std::unique_ptr<Event> Clone() const override;
  469. private:
  470. FRIEND_TEST_ALL_PREFIXES(EventTest, DoubleClickRequiresUniqueTimestamp);
  471. FRIEND_TEST_ALL_PREFIXES(EventTest, SingleClickRightLeft);
  472. // Returns the repeat count based on the previous mouse click, if it is
  473. // recent enough and within a small enough distance.
  474. static int GetRepeatCount(const MouseEvent& click_event);
  475. // Resets the last_click_event_ for unit tests.
  476. static void ResetLastClickForTest();
  477. // See description above getter for details.
  478. int changed_button_flags_;
  479. // Raw mouse movement value reported from mouse hardware. The value of this is
  480. // platform dependent and may change depending upon the hardware connected to
  481. // the device. This field is only set if the flag EF_UNADJUSTED_MOUSE is
  482. // present (which is the case on windows platforms, and CrOS if the
  483. // kEnableOrdinalMotion flag is set).
  484. //
  485. // TODO(b/171249701): always enable on CrOS.
  486. gfx::Vector2dF movement_;
  487. // The most recent user-generated MouseEvent, used to detect double clicks.
  488. static MouseEvent* last_click_event_;
  489. // Structure for holding pointer details for implementing PointerEvents API.
  490. PointerDetails pointer_details_;
  491. };
  492. class ScrollEvent;
  493. class EVENTS_EXPORT MouseWheelEvent : public MouseEvent {
  494. public:
  495. // See |offset| for details.
  496. static const int kWheelDelta;
  497. explicit MouseWheelEvent(const PlatformEvent& native_event);
  498. explicit MouseWheelEvent(const ScrollEvent& scroll_event);
  499. MouseWheelEvent(const MouseEvent& mouse_event, int x_offset, int y_offset);
  500. MouseWheelEvent(const MouseWheelEvent& copy);
  501. ~MouseWheelEvent() override;
  502. template <class T>
  503. MouseWheelEvent(const MouseWheelEvent& model, T* source, T* target)
  504. : MouseEvent(model, source, target, model.type(), model.flags()),
  505. offset_(model.x_offset(), model.y_offset()),
  506. tick_120ths_(model.tick_120ths()) {}
  507. // Used for synthetic events in testing and by the gesture recognizer.
  508. MouseWheelEvent(
  509. const gfx::Vector2d& offset,
  510. const gfx::PointF& location,
  511. const gfx::PointF& root_location,
  512. base::TimeTicks time_stamp,
  513. int flags,
  514. int changed_button_flags,
  515. const absl::optional<gfx::Vector2d> tick_120ths = absl::nullopt);
  516. // DEPRECATED: Prefer the constructor that takes gfx::PointF.
  517. MouseWheelEvent(const gfx::Vector2d& offset,
  518. const gfx::Point& location,
  519. const gfx::Point& root_location,
  520. base::TimeTicks time_stamp,
  521. int flags,
  522. int changed_button_flags);
  523. // The amount to scroll. This is not necessarily linearly related to the
  524. // amount that the wheel moved, due to scroll acceleration.
  525. // Note: x_offset() > 0/y_offset() > 0 means scroll left/up.
  526. int x_offset() const { return offset_.x(); }
  527. int y_offset() const { return offset_.y(); }
  528. const gfx::Vector2d& offset() const { return offset_; }
  529. // The amount the wheel(s) moved, in 120ths of a tick.
  530. const gfx::Vector2d& tick_120ths() const { return tick_120ths_; }
  531. // Event:
  532. std::unique_ptr<Event> Clone() const override;
  533. private:
  534. gfx::Vector2d offset_;
  535. gfx::Vector2d tick_120ths_;
  536. };
  537. // NOTE: Pen (stylus) events use TouchEvent with kPen. They were
  538. // originally implemented as MouseEvent but switched to TouchEvent when UX
  539. // decided not to show hover effects for pen.
  540. class EVENTS_EXPORT TouchEvent : public LocatedEvent {
  541. public:
  542. explicit TouchEvent(const PlatformEvent& native_event);
  543. // Create a new TouchEvent which is identical to the provided model.
  544. // If source / target windows are provided, the model location will be
  545. // converted from |source| coordinate system to |target| coordinate system.
  546. template <class T>
  547. TouchEvent(const TouchEvent& model, T* source, T* target)
  548. : LocatedEvent(model, source, target),
  549. unique_event_id_(model.unique_event_id_),
  550. may_cause_scrolling_(model.may_cause_scrolling_),
  551. hovering_(false),
  552. pointer_details_(model.pointer_details_) {}
  553. TouchEvent(EventType type,
  554. const gfx::PointF& location,
  555. const gfx::PointF& root_location,
  556. base::TimeTicks time_stamp,
  557. const PointerDetails& pointer_details,
  558. int flags = 0);
  559. // DEPRECATED: Prefer the constructor that takes gfx::PointF.
  560. TouchEvent(EventType type,
  561. const gfx::Point& location,
  562. base::TimeTicks time_stamp,
  563. const PointerDetails& pointer_details,
  564. int flags = 0);
  565. TouchEvent(const TouchEvent& copy);
  566. ~TouchEvent() override;
  567. // A unique identifier for this event.
  568. uint32_t unique_event_id() const { return unique_event_id_; }
  569. void set_may_cause_scrolling(bool causes) { may_cause_scrolling_ = causes; }
  570. bool may_cause_scrolling() const { return may_cause_scrolling_; }
  571. void set_hovering(bool hovering) { hovering_ = hovering; }
  572. bool hovering() const { return hovering_; }
  573. // Overridden from LocatedEvent.
  574. void UpdateForRootTransform(
  575. const gfx::Transform& inverted_root_transform,
  576. const gfx::Transform& inverted_local_transform) override;
  577. // Marks the event as not participating in synchronous gesture recognition.
  578. void DisableSynchronousHandling();
  579. bool synchronous_handling_disabled() const {
  580. return !!(result() & ER_DISABLE_SYNC_HANDLING);
  581. }
  582. const PointerDetails& pointer_details() const { return pointer_details_; }
  583. void SetPointerDetailsForTest(const PointerDetails& pointer_details);
  584. float ComputeRotationAngle() const;
  585. // Event:
  586. std::unique_ptr<Event> Clone() const override;
  587. private:
  588. // A unique identifier for the touch event.
  589. // NOTE: this is *not* serialized over mojom, as the number is unique to
  590. // a particular process, and as mojom may go cross process, to serialize could
  591. // lead to conflicts.
  592. uint32_t unique_event_id_;
  593. // Whether the (unhandled) touch event will produce a scroll event (e.g., a
  594. // touchmove that exceeds the platform slop region, or a touchend that
  595. // causes a fling). Defaults to false.
  596. bool may_cause_scrolling_ = false;
  597. // True for devices like some pens when they support hovering over
  598. // digitizer and they send events while hovering.
  599. bool hovering_ = false;
  600. // Structure for holding pointer details for implementing PointerEvents API.
  601. PointerDetails pointer_details_;
  602. };
  603. // A KeyEvent is really two distinct classes, melded together due to the
  604. // DOM legacy of Windows key events: a keystroke event (is_char_ == false),
  605. // or a character event (is_char_ == true).
  606. //
  607. // For a keystroke event,
  608. // -- |bool is_char_| is false.
  609. // -- |EventType Event::type()| can be ET_KEY_PRESSED or ET_KEY_RELEASED.
  610. // -- |DomCode code_| and |int Event::flags()| represent the physical key event.
  611. // - code_ is a platform-independent representation of the physical key,
  612. // based on DOM UI Events KeyboardEvent |code| values. It does not
  613. // vary depending on key layout.
  614. // http://www.w3.org/TR/DOM-Level-3-Events-code/
  615. // - Event::flags() provides the active modifiers for the physical key
  616. // press. Its value reflects the state after the event; that is, for
  617. // a modifier key, a press includes the corresponding flag and a release
  618. // does not.
  619. // -- |DomKey key_| provides the meaning (character or action) of the key
  620. // event, in the context of the active layout and modifiers. It corresponds
  621. // to DOM UI Events KeyboardEvent |key| values.
  622. // http://www.w3.org/TR/DOM-Level-3-Events-key/
  623. // -- |KeyboardCode key_code_| supports the legacy web event |keyCode| field,
  624. // and its VKEY_ values are chosen to match Windows/IE for compatibility.
  625. // For printable characters, this may or may not be a layout-mapped value,
  626. // imitating MS Windows: if the mapped key generates a character that has
  627. // an associated VKEY_ code, then key_code_ is that code; if not, then
  628. // key_code_ is the unmapped VKEY_ code. For example, US, Greek, Cyrillic,
  629. // Japanese, etc. all use VKEY_Q for the key beside Tab, while French uses
  630. // VKEY_A. The stored key_code_ is non-located (e.g. VKEY_SHIFT rather than
  631. // VKEY_LSHIFT, VKEY_1 rather than VKEY_NUMPAD1).
  632. // -- |uint32_t scan_code_| [USE_OZONE only] supports remapping of the top
  633. // function row based on a sysfs attribute provided by the kernel. This
  634. // allows devices to have a custom top row layout and still be able to
  635. // perform translation back and forth between F-Key and Action-Key. The
  636. // value of this scan code is device specific.
  637. //
  638. // For a character event,
  639. // -- |bool is_char_| is true.
  640. // -- |EventType Event::type()| is ET_KEY_PRESSED.
  641. // -- |DomCode code_| is DomCode::NONE.
  642. // -- |DomKey key_| is a UTF-16 code point.
  643. // -- |KeyboardCode key_code_| is conflated with the character-valued key_
  644. // by some code, because both arrive in the wParam field of a Windows event.
  645. //
  646. class EVENTS_EXPORT KeyEvent : public Event {
  647. public:
  648. // Create a KeyEvent from a NativeEvent. For Windows this native event can
  649. // be either a keystroke message (WM_KEYUP/WM_KEYDOWN) or a character message
  650. // (WM_CHAR). Other systems have only keystroke events.
  651. explicit KeyEvent(const PlatformEvent& native_event);
  652. // Create a KeyEvent from a NativeEvent but with mocked flags.
  653. // This method is necessary for Windows since MSG does not contain all flags.
  654. KeyEvent(const PlatformEvent& native_event, int event_flags);
  655. // Create a keystroke event from a legacy KeyboardCode.
  656. // This should not be used in new code.
  657. KeyEvent(EventType type,
  658. KeyboardCode key_code,
  659. int flags,
  660. base::TimeTicks time_stamp = base::TimeTicks());
  661. // Create a fully defined keystroke event.
  662. KeyEvent(EventType type,
  663. KeyboardCode key_code,
  664. DomCode code,
  665. int flags,
  666. DomKey key,
  667. base::TimeTicks time_stamp,
  668. bool is_char = false);
  669. // Create a character event.
  670. KeyEvent(char16_t character,
  671. KeyboardCode key_code,
  672. DomCode code,
  673. int flags,
  674. base::TimeTicks time_stamp = base::TimeTicks());
  675. // Used for synthetic events with code of DOM KeyboardEvent (e.g. 'KeyA')
  676. // See also: ui/events/keycodes/dom/dom_values.txt
  677. KeyEvent(EventType type, KeyboardCode key_code, DomCode code, int flags);
  678. KeyEvent(const KeyEvent& rhs);
  679. KeyEvent& operator=(const KeyEvent& rhs);
  680. ~KeyEvent() override;
  681. // Returns true if synthesizing key repeat in InitializeNative is enabled.
  682. static bool IsSynthesizeKeyRepeatEnabled();
  683. // Sets whether to enable synthesizing key repeat in InitializeNative().
  684. static void SetSynthesizeKeyRepeatEnabled(bool enabled);
  685. void InitializeNative();
  686. // This bypasses the normal mapping from keystroke events to characters,
  687. // which allows an I18N virtual keyboard to fabricate a keyboard event that
  688. // does not have a corresponding KeyboardCode (example: U+00E1 Latin small
  689. // letter A with acute, U+0410 Cyrillic capital letter A).
  690. void set_character(char16_t character) {
  691. key_ = DomKey::FromCharacter(character);
  692. }
  693. // Gets the character generated by this key event. It only supports Unicode
  694. // BMP characters.
  695. char16_t GetCharacter() const;
  696. // If this is a keystroke event with key_code_ VKEY_RETURN, returns '\r';
  697. // otherwise returns the same as GetCharacter().
  698. char16_t GetUnmodifiedText() const;
  699. // If the Control key is down in the event, returns a layout-independent
  700. // character (corresponding to US layout); otherwise returns the same
  701. // as GetUnmodifiedText().
  702. char16_t GetText() const;
  703. // True if this is a character event, false if this is a keystroke event.
  704. bool is_char() const { return is_char_; }
  705. bool is_repeat() const { return (flags() & EF_IS_REPEAT) != 0; }
  706. // Gets the associated (Windows-based) KeyboardCode for this key event.
  707. // Historically, this has also been used to obtain the character associated
  708. // with a character event, because both use the Window message 'wParam' field.
  709. // This should be avoided; if necessary for backwards compatibility, use
  710. // GetConflatedWindowsKeyCode().
  711. KeyboardCode key_code() const { return key_code_; }
  712. // This is only intended to be used externally by classes that are modifying
  713. // events in an EventRewriter.
  714. void set_key_code(KeyboardCode key_code) { key_code_ = key_code; }
  715. #if defined(USE_OZONE)
  716. // The scan code of the physical key. This is used to perform the mapping
  717. // of top row keys from Actions back to F-Keys on new Chrome OS keyboards
  718. // that supply the mapping via the kernel.
  719. uint32_t scan_code() const { return scan_code_; }
  720. void set_scan_code(uint32_t scan_code) { scan_code_ = scan_code; }
  721. #endif // defined(USE_OZONE)
  722. // Returns the same value as key_code(), except that located codes are
  723. // returned in place of non-located ones (e.g. VKEY_LSHIFT or VKEY_RSHIFT
  724. // instead of VKEY_SHIFT). This is a hybrid of semantic and physical
  725. // for legacy DOM reasons.
  726. KeyboardCode GetLocatedWindowsKeyboardCode() const;
  727. // For a keystroke event, returns the same value as key_code().
  728. // For a character event, returns the same value as GetCharacter().
  729. // This exists for backwards compatibility with Windows key events.
  730. uint16_t GetConflatedWindowsKeyCode() const;
  731. // Returns true for [Alt]+<num-pad digit> Unicode alt key codes used by Win.
  732. // TODO(msw): Additional work may be needed for analogues on other platforms.
  733. bool IsUnicodeKeyCode() const;
  734. // Returns the DOM .code (physical key identifier) for a keystroke event.
  735. DomCode code() const { return code_; }
  736. std::string GetCodeString() const;
  737. // Returns the DOM .key (layout meaning) for a keystroke event.
  738. DomKey GetDomKey() const;
  739. // Normalizes flags_ so that it describes the state after the event.
  740. // (Native X11 event flags describe the state before the event.)
  741. void NormalizeFlags();
  742. // Event:
  743. std::string ToString() const override;
  744. std::unique_ptr<Event> Clone() const override;
  745. protected:
  746. friend class KeyEventTestApi;
  747. // This allows a subclass TranslatedKeyEvent to be a non character event.
  748. void set_is_char(bool is_char) { is_char_ = is_char; }
  749. private:
  750. // Determine key_ on a keystroke event from code_ and flags().
  751. void ApplyLayout() const;
  752. // Tells if this is a repeated KeyEvent based on |last_key_event|, which is
  753. // then updated with the new last KeyEvent address.
  754. bool IsRepeated(KeyEvent** last_key_event);
  755. // Returns the pointer for the last processed KeyEvent.
  756. KeyEvent** GetLastKeyEvent();
  757. KeyboardCode key_code_;
  758. #if defined(USE_OZONE)
  759. // The scan code of the physical key on Chrome OS.
  760. uint32_t scan_code_ = 0;
  761. #endif // defined(USE_OZONE)
  762. // DOM KeyboardEvent |code| (e.g. DomCode::US_A, DomCode::SPACE).
  763. // http://www.w3.org/TR/DOM-Level-3-Events-code/
  764. //
  765. // This value represents the physical position in the keyboard and can be
  766. // converted from / to keyboard scan code like XKB.
  767. DomCode code_;
  768. // True if this is a character event, false if this is a keystroke event.
  769. bool is_char_ = false;
  770. // TODO(kpschoedel): refactor so that key_ is not mutable.
  771. // This requires defining the KeyEvent completely at construction rather
  772. // than lazily under GetCharacter(), which likely also means removing
  773. // the two 'incomplete' constructors. crbug.com/444045
  774. //
  775. // DOM KeyboardEvent |key|
  776. // http://www.w3.org/TR/DOM-Level-3-Events-key/
  777. //
  778. // This value represents the meaning of a key, which is either a Unicode
  779. // character, or a named DomKey:: value.
  780. // This is not necessarily initialized when the event is constructed;
  781. // it may be set only if and when GetCharacter() or GetDomKey() is called.
  782. mutable DomKey key_ = DomKey::NONE;
  783. static KeyEvent* last_key_event_;
  784. #if defined(USE_OZONE)
  785. static KeyEvent* last_ibus_key_event_;
  786. #endif
  787. static bool synthesize_key_repeat_enabled_;
  788. };
  789. class EVENTS_EXPORT ScrollEvent : public MouseEvent {
  790. public:
  791. explicit ScrollEvent(const PlatformEvent& native_event);
  792. template <class T>
  793. ScrollEvent(const ScrollEvent& model, T* source, T* target)
  794. : MouseEvent(model, source, target),
  795. x_offset_(model.x_offset_),
  796. y_offset_(model.y_offset_),
  797. x_offset_ordinal_(model.x_offset_ordinal_),
  798. y_offset_ordinal_(model.y_offset_ordinal_),
  799. finger_count_(model.finger_count_),
  800. momentum_phase_(model.momentum_phase_),
  801. scroll_event_phase_(model.scroll_event_phase_) {}
  802. ScrollEvent(EventType type,
  803. const gfx::PointF& location,
  804. const gfx::PointF& root_location,
  805. base::TimeTicks time_stamp,
  806. int flags,
  807. float x_offset,
  808. float y_offset,
  809. float x_offset_ordinal,
  810. float y_offset_ordinal,
  811. int finger_count,
  812. EventMomentumPhase momentum_phase = EventMomentumPhase::NONE,
  813. ScrollEventPhase phase = ScrollEventPhase::kNone);
  814. // DEPRECATED: Prefer the constructor that takes gfx::PointF.
  815. ScrollEvent(EventType type,
  816. const gfx::Point& location,
  817. base::TimeTicks time_stamp,
  818. int flags,
  819. float x_offset,
  820. float y_offset,
  821. float x_offset_ordinal,
  822. float y_offset_ordinal,
  823. int finger_count,
  824. EventMomentumPhase momentum_phase = EventMomentumPhase::NONE,
  825. ScrollEventPhase phase = ScrollEventPhase::kNone);
  826. ScrollEvent(const ScrollEvent& copy);
  827. ~ScrollEvent() override;
  828. // Scale the scroll event's offset value.
  829. // This is useful in the multi-monitor setup where it needs to be scaled
  830. // to provide a consistent user experience.
  831. void Scale(const float factor);
  832. float x_offset() const { return x_offset_; }
  833. float y_offset() const { return y_offset_; }
  834. float x_offset_ordinal() const { return x_offset_ordinal_; }
  835. float y_offset_ordinal() const { return y_offset_ordinal_; }
  836. int finger_count() const { return finger_count_; }
  837. EventMomentumPhase momentum_phase() const { return momentum_phase_; }
  838. ScrollEventPhase scroll_event_phase() const { return scroll_event_phase_; }
  839. // Event:
  840. std::string ToString() const override;
  841. std::unique_ptr<Event> Clone() const override;
  842. private:
  843. // Potential accelerated offsets.
  844. float x_offset_;
  845. float y_offset_;
  846. // Unaccelerated offsets.
  847. float x_offset_ordinal_;
  848. float y_offset_ordinal_;
  849. // Number of fingers on the pad.
  850. int finger_count_;
  851. // For non-fling events, provides momentum information (e.g. for the case
  852. // where the device provides continuous event updates during a fling).
  853. EventMomentumPhase momentum_phase_ = EventMomentumPhase::NONE;
  854. // Provides phase information if device can provide.
  855. ScrollEventPhase scroll_event_phase_ = ScrollEventPhase::kNone;
  856. };
  857. class EVENTS_EXPORT GestureEvent : public LocatedEvent {
  858. public:
  859. // The constructor takes a default unique_touch_id of zero to support many
  860. // (80+) existing tests that doesn't care about this id.
  861. GestureEvent(float x,
  862. float y,
  863. int flags,
  864. base::TimeTicks time_stamp,
  865. const GestureEventDetails& details,
  866. uint32_t unique_touch_event_id = 0);
  867. // Create a new GestureEvent which is identical to the provided model.
  868. // If source / target windows are provided, the model location will be
  869. // converted from |source| coordinate system to |target| coordinate system.
  870. template <typename T>
  871. GestureEvent(const GestureEvent& model, T* source, T* target)
  872. : LocatedEvent(model, source, target), details_(model.details_) {}
  873. GestureEvent(const GestureEvent& copy);
  874. ~GestureEvent() override;
  875. const GestureEventDetails& details() const { return details_; }
  876. uint32_t unique_touch_event_id() const { return unique_touch_event_id_; }
  877. // Event:
  878. std::string ToString() const override;
  879. std::unique_ptr<Event> Clone() const override;
  880. private:
  881. GestureEventDetails details_;
  882. // The unique id of the touch event that caused the gesture event to be
  883. // dispatched. This field gets a non-zero value only for gestures that are
  884. // released through TouchDispositionGestureFilter::SendGesture. The gesture
  885. // events that aren't fired directly in response to processing a touch-event
  886. // (e.g. timer fired ones), this id is zero. See crbug.com/618738.
  887. uint32_t unique_touch_event_id_;
  888. };
  889. } // namespace ui
  890. #endif // UI_EVENTS_EVENT_H_