File: ui_controls_mac.mm

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,806; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (531 lines) | stat: -rw-r--r-- 20,433 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/40285824): Remove this and convert code to safer constructs.
#pragma allow_unsafe_buffers
#endif

#include "ui/base/test/ui_controls.h"

#import <Cocoa/Cocoa.h>

#include <vector>

#import "base/apple/foundation_util.h"
#import "base/apple/scoped_objc_class_swizzler.h"
#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/task/current_thread.h"
#import "base/task/single_thread_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "ui/events/keycodes/keyboard_code_conversion_mac.h"
#import "ui/events/test/cocoa_test_event_utils.h"
#include "ui/gfx/geometry/point.h"
#import "ui/gfx/mac/coordinate_conversion.h"

// Implementation details: We use [NSApplication sendEvent:] instead
// of [NSApplication postEvent:atStart:] so that the event gets sent
// immediately.  This lets us run the post-event task right
// immediately as well.  Unfortunately I cannot subclass NSEvent (it's
// probably a class cluster) to allow other easy answers.  For
// example, if I could subclass NSEvent, I could run the Task in it's
// dealloc routine (which necessarily happens after the event is
// dispatched).  Unlike Linux, Mac does not have message loop
// observer/notification.  Unlike windows, I cannot post non-events
// into the event queue.  (I can post other kinds of tasks but can't
// guarantee their order with regards to events).

// But [NSApplication sendEvent:] causes a problem when sending mouse click
// events. Because in order to handle mouse drag, when processing a mouse
// click event, the application may want to retrieve the next event
// synchronously by calling NSApplication's nextEventMatchingMask method.
// In this case, [NSApplication sendEvent:] causes deadlock.
// So we need to use [NSApplication postEvent:atStart:] for mouse click
// events. In order to notify the caller correctly after all events has been
// processed, we setup a task to watch for the event queue time to time and
// notify the caller as soon as there is no event in the queue.
//
// TODO(suzhe):
// 1. Investigate why using [NSApplication postEvent:atStart:] for keyboard
//    events causes BrowserKeyEventsTest.CommandKeyEvents to fail.
//    See http://crbug.com/49270
// 2. On OSX 10.6, [NSEvent addLocalMonitorForEventsMatchingMask:handler:] may
//    be used, so that we don't need to poll the event queue time to time.

using cocoa_test_event_utils::SynthesizeKeyEvent;
using cocoa_test_event_utils::TimeIntervalSinceSystemStartup;

namespace {

// Stores the current mouse location on the screen. So that we can use it
// when firing keyboard and mouse click events.
NSPoint g_mouse_location = { 0, 0 };

// Stores the most recently-entered window so that exit and enter events can be
// sent correctly.
__weak NSWindow* g_last_window_weak = nullptr;

// Stores the current pressed mouse buttons. Indexed by
// ui_controls::MouseButton.
bool g_mouse_button_down[3] = {false, false, false};

bool g_ui_controls_enabled = false;

void CheckUIControlsEnabled() {
  CHECK(g_ui_controls_enabled)
      << "In order to use ui_controls methods, you must be in a test "
         "executable that enables UI Controls. Currently, this is "
         "interactive_ui_tests and some fuzzing tests.\n"
         "This limitation prevents attempting to send input that might require "
         "the test process to be active and focused in an environment where "
         "the process is not guaranteed to be running exclusively, which can "
         "lead to flaky tests.";
}

// Creates the proper sequence of autoreleased key events for a key down + up.
void SynthesizeKeyEventsSequence(NSWindow* window,
                                 ui::KeyboardCode keycode,
                                 int key_event_types,
                                 int accelerator_state,
                                 std::vector<NSEvent*>* events) {
  NSEvent* event = nil;
  NSUInteger flags = 0;
  if (key_event_types & ui_controls::kKeyPress) {
    if (accelerator_state & ui_controls::kControl) {
      flags |= NSEventModifierFlagControl;
      event = SynthesizeKeyEvent(window, true, ui::VKEY_CONTROL, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kShift) {
      flags |= NSEventModifierFlagShift;
      event = SynthesizeKeyEvent(window, true, ui::VKEY_SHIFT, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kAlt) {
      flags |= NSEventModifierFlagOption;
      event = SynthesizeKeyEvent(window, true, ui::VKEY_MENU, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kCommand) {
      flags |= NSEventModifierFlagCommand;
      event = SynthesizeKeyEvent(window, true, ui::VKEY_COMMAND, flags);
      DCHECK(event);
      events->push_back(event);
    }

    event = SynthesizeKeyEvent(window, true, keycode, flags);
    DCHECK(event);
    events->push_back(event);
  }

  if (key_event_types & ui_controls::kKeyRelease) {
    event = SynthesizeKeyEvent(window, false, keycode, flags);
    DCHECK(event);
    events->push_back(event);

    if (accelerator_state & ui_controls::kCommand) {
      flags &= ~NSEventModifierFlagCommand;
      event = SynthesizeKeyEvent(window, false, ui::VKEY_COMMAND, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kAlt) {
      flags &= ~NSEventModifierFlagOption;
      event = SynthesizeKeyEvent(window, false, ui::VKEY_MENU, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kShift) {
      flags &= ~NSEventModifierFlagShift;
      event = SynthesizeKeyEvent(window, false, ui::VKEY_SHIFT, flags);
      DCHECK(event);
      events->push_back(event);
    }
    if (accelerator_state & ui_controls::kControl) {
      flags &= ~NSEventModifierFlagControl;
      event = SynthesizeKeyEvent(window, false, ui::VKEY_CONTROL, flags);
      DCHECK(event);
      events->push_back(event);
    }
  }
}

// A helper function to watch for the event queue. The specific task will be
// fired when there is no more event in the queue.
void PostWhenEventQueueIsEmpty(base::OnceClosure task) {
  NSEvent* event = [NSApp nextEventMatchingMask:NSEventMaskAny
                                      untilDate:nil
                                         inMode:NSDefaultRunLoopMode
                                        dequeue:NO];
  // If there is still event in the queue, then we need to check again.
  if (event) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&PostWhenEventQueueIsEmpty, std::move(task)));
  } else {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, std::move(task));
  }
}

// Returns the NSWindow located at |g_mouse_location|. NULL if there is no
// window there, or if the window located there is not owned by the application.
// On Mac, unless dragging, mouse events are sent to the window under the
// cursor. Note that the OS will ignore transparent windows and windows that
// explicitly ignore mouse events.
NSWindow* WindowAtCurrentMouseLocation() {
  NSInteger window_number = [NSWindow windowNumberAtPoint:g_mouse_location
                              belowWindowWithWindowNumber:0];
  NSWindow* window =
      [[NSApplication sharedApplication] windowWithWindowNumber:window_number];
  if (window)
    return window;

  // It's possible for a window owned by another application to be at that
  // location. Cocoa won't provide an NSWindow* for those. Tests should not care
  // about other applications, and raising windows in a headless application is
  // flaky due to OS restrictions. For tests, hunt through all of this
  // application's windows, top to bottom, looking for a good candidate.
  NSArray* window_list = [[NSApplication sharedApplication] orderedWindows];
  for (window in window_list) {
    // Note this skips the extra checks (e.g. fully-transparent windows), that
    // +[NSWindow windowNumberAtPoint:] performs. Tests that care about that
    // should check separately (the goal here is to minimize flakiness).
    if (NSPointInRect(g_mouse_location, [window frame]))
      return window;
  }

  // Note that -[NSApplication orderedWindows] won't include NSPanels. If a test
  // uses those, it will need to handle that itself.
  return nil;
}

// Makes a mouse event for `event_type`.
NSEvent* MakeMouseEvent(NSEventType event_type, NSWindow* window) {
  NSTimeInterval timestamp = TimeIntervalSinceSystemStartup();
  NSPoint point_in_window = g_mouse_location;
  if (window) {
    point_in_window = [window convertPointFromScreen:point_in_window];
  }
  const bool is_move = event_type == NSEventTypeMouseMoved;
  const bool is_enter_exit = event_type == NSEventTypeMouseEntered ||
                             event_type == NSEventTypeMouseExited;
  if (is_enter_exit) {
    return [NSEvent enterExitEventWithType:event_type
                                  location:point_in_window
                             modifierFlags:0
                                 timestamp:timestamp
                              windowNumber:[window windowNumber]
                                   context:nil
                               eventNumber:0
                            trackingNumber:0
                                  userData:nullptr];
  }
  return [NSEvent mouseEventWithType:event_type
                            location:point_in_window
                       modifierFlags:0
                           timestamp:timestamp
                        windowNumber:[window windowNumber]
                             context:nil
                         eventNumber:0
                          clickCount:is_move ? 0 : 1
                            pressure:is_move ? 0.0 : 1.0];
}

}  // namespace

// Donates testing implementations of NSEvent methods.
@interface FakeNSEventTestingDonor : NSObject
@end

@implementation FakeNSEventTestingDonor
+ (NSPoint)mouseLocation {
  return g_mouse_location;
}

+ (NSUInteger)pressedMouseButtons {
  NSUInteger result = 0;
  const int buttons[3] = {
      ui_controls::LEFT, ui_controls::RIGHT, ui_controls::MIDDLE};
  for (size_t i = 0; i < std::size(buttons); ++i) {
    if (g_mouse_button_down[buttons[i]])
      result |= (1 << i);
  }
  return result;
}
@end

namespace {

// Swizzles several Cocoa functions that are used to directly get mouse state,
// so that they will return the current simulated mouse position and pressed
// mouse buttons.
class MockNSEventClassMethods {
 public:
  static void Init() {
    static MockNSEventClassMethods* swizzler = nullptr;
    if (!swizzler) {
      swizzler = new MockNSEventClassMethods();
    }
  }

  MockNSEventClassMethods(const MockNSEventClassMethods&) = delete;
  MockNSEventClassMethods& operator=(const MockNSEventClassMethods&) = delete;

 private:
  MockNSEventClassMethods()
      : mouse_location_swizzler_([NSEvent class],
                                 [FakeNSEventTestingDonor class],
                                 @selector(mouseLocation)),
        pressed_mouse_buttons_swizzler_([NSEvent class],
                                        [FakeNSEventTestingDonor class],
                                        @selector(pressedMouseButtons)) {}

  base::apple::ScopedObjCClassSwizzler mouse_location_swizzler_;
  base::apple::ScopedObjCClassSwizzler pressed_mouse_buttons_swizzler_;
};

}  // namespace

namespace ui_controls {

void EnableUIControls() {
  g_ui_controls_enabled = true;
  MockNSEventClassMethods::Init();
}

bool IsUIControlsEnabled() {
  return g_ui_controls_enabled;
}

void ResetUIControlsIfEnabled() {}

bool SendKeyPress(gfx::NativeWindow window,
                  ui::KeyboardCode key,
                  bool control,
                  bool shift,
                  bool alt,
                  bool command) {
  CheckUIControlsEnabled();
  return SendKeyPressNotifyWhenDone(window, key, control, shift, alt, command,
                                    base::OnceClosure());
}

// The implementation in ui_controls_aura.cc sends key press *and* release, so
// this implementation does the same.
bool SendKeyPressNotifyWhenDone(gfx::NativeWindow window,
                                ui::KeyboardCode key,
                                bool control,
                                bool shift,
                                bool alt,
                                bool command,
                                base::OnceClosure task,
                                KeyEventType wait_for) {
  // This doesn't time out if `window` is deleted before the key release events
  // are dispatched, so it's fine to ignore `wait_for` and always wait for key
  // release events.
  CheckUIControlsEnabled();
  return SendKeyEventsNotifyWhenDone(
      window, key, kKeyPress | kKeyRelease, std::move(task),
      GenerateAcceleratorState(control, shift, alt, command));
}

bool SendKeyEvents(gfx::NativeWindow window,
                   ui::KeyboardCode key,
                   int key_event_types,
                   int accelerator_state) {
  CheckUIControlsEnabled();
  return SendKeyEventsNotifyWhenDone(window, key, key_event_types,
                                     base::OnceClosure(), accelerator_state);
}

bool SendKeyEventsNotifyWhenDone(gfx::NativeWindow window,
                                 ui::KeyboardCode key,
                                 int key_event_types,
                                 base::OnceClosure task,
                                 int accelerator_state) {
  CheckUIControlsEnabled();
  DCHECK(base::CurrentUIThread::IsSet());

  std::vector<NSEvent*> events;
  SynthesizeKeyEventsSequence(window.GetNativeNSWindow(), key, key_event_types,
                              accelerator_state, &events);

  // TODO(suzhe): Using [NSApplication postEvent:atStart:] here causes
  // BrowserKeyEventsTest.CommandKeyEvents to fail. See http://crbug.com/49270
  // But using [NSApplication sendEvent:] should be safe for keyboard events,
  // because until now, no code wants to retrieve the next event when handling
  // a keyboard event.
  for (std::vector<NSEvent*>::iterator iter = events.begin();
       iter != events.end(); ++iter)
    [[NSApplication sharedApplication] sendEvent:*iter];

  if (!task.is_null()) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&PostWhenEventQueueIsEmpty, std::move(task)));
  }

  return true;
}

bool SendMouseMove(int x, int y, gfx::NativeWindow window_hint) {
  CheckUIControlsEnabled();
  return SendMouseMoveNotifyWhenDone(x, y, base::OnceClosure(), window_hint);
}

// Input position is in screen coordinates.  However, NSEventTypeMouseMoved
// events require them window-relative, so we adjust.  We *DO* flip
// the coordinate space, so input events can be the same for all
// platforms.  E.g. (0,0) is upper-left.
bool SendMouseMoveNotifyWhenDone(int x,
                                 int y,
                                 base::OnceClosure task,
                                 gfx::NativeWindow window_hint) {
  CheckUIControlsEnabled();

  g_mouse_location = gfx::ScreenPointToNSPoint(gfx::Point(x, y));  // flip!
  NSWindow* window = window_hint ? window_hint.GetNativeNSWindow()
                                 : WindowAtCurrentMouseLocation();

  // Possibly send exit and enter events.
  if (g_last_window_weak != window) {
    if (g_last_window_weak) {
      NSEvent* event =
          MakeMouseEvent(NSEventTypeMouseExited, g_last_window_weak);
      [g_last_window_weak.contentView mouseExited:event];
    }
    if (window) {
      NSEvent* event = MakeMouseEvent(NSEventTypeMouseEntered, window);
      [g_last_window_weak.contentView mouseEntered:event];
    }
  }
  g_last_window_weak = window;

  NSEventType event_type = NSEventTypeMouseMoved;
  if (g_mouse_button_down[LEFT]) {
    event_type = NSEventTypeLeftMouseDragged;
  } else if (g_mouse_button_down[RIGHT]) {
    event_type = NSEventTypeRightMouseDragged;
  } else if (g_mouse_button_down[MIDDLE]) {
    event_type = NSEventTypeOtherMouseDragged;
  }

  // Moves must be sent directly to the window as they won't be relayed by the
  // OS.
  NSEvent* event = MakeMouseEvent(event_type, window);
  if (window_hint && event_type == NSEventTypeMouseMoved) {
    if (window) {
      [window.contentView mouseMoved:event];
    }
  } else {
    [[NSApplication sharedApplication] postEvent:event atStart:NO];
  }

  // Maybe post the follow-up task.
  if (!task.is_null()) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&PostWhenEventQueueIsEmpty, std::move(task)));
  }

  return true;
}

bool SendMouseEvents(MouseButton type,
                     int button_state,
                     int accelerator_state,
                     gfx::NativeWindow window_hint) {
  CheckUIControlsEnabled();
  return SendMouseEventsNotifyWhenDone(type, button_state, base::OnceClosure(),
                                       accelerator_state, window_hint);
}

bool SendMouseEventsNotifyWhenDone(MouseButton type,
                                   int button_state,
                                   base::OnceClosure task,
                                   int accelerator_state,
                                   gfx::NativeWindow window_hint) {
  CheckUIControlsEnabled();
  // Handle the special case of mouse clicking (UP | DOWN) case.
  if (button_state == (UP | DOWN)) {
    return (SendMouseEventsNotifyWhenDone(type, DOWN, base::OnceClosure(),
                                          accelerator_state, window_hint) &&
            SendMouseEventsNotifyWhenDone(type, UP, std::move(task),
                                          accelerator_state, window_hint));
  }
  NSEventType event_type = NSEventTypeLeftMouseDown;
  if (type == LEFT) {
    if (button_state == UP) {
      event_type = NSEventTypeLeftMouseUp;
    } else {
      event_type = NSEventTypeLeftMouseDown;
    }
  } else if (type == MIDDLE) {
    if (button_state == UP) {
      event_type = NSEventTypeOtherMouseUp;
    } else {
      event_type = NSEventTypeOtherMouseDown;
    }
  } else {
    CHECK_EQ(type, RIGHT);
    if (button_state == UP) {
      event_type = NSEventTypeRightMouseUp;
    } else {
      event_type = NSEventTypeRightMouseDown;
    }
  }
  g_mouse_button_down[type] = button_state == DOWN;

  NSWindow* window = window_hint ? window_hint.GetNativeNSWindow()
                                 : WindowAtCurrentMouseLocation();

  NSPoint pointInWindow = g_mouse_location;
  if (window) {
    pointInWindow = [window convertPointFromScreen:pointInWindow];
  }

  // Process the accelerator key state.
  NSEventModifierFlags modifier = 0;
  if (accelerator_state & kShift)
    modifier |= NSEventModifierFlagShift;
  if (accelerator_state & kControl)
    modifier |= NSEventModifierFlagControl;
  if (accelerator_state & kAlt)
    modifier |= NSEventModifierFlagOption;
  if (accelerator_state & kCommand)
    modifier |= NSEventModifierFlagCommand;

  NSEvent* event =
      [NSEvent mouseEventWithType:event_type
                         location:pointInWindow
                    modifierFlags:modifier
                        timestamp:TimeIntervalSinceSystemStartup()
                     windowNumber:[window windowNumber]
                          context:nil
                      eventNumber:0
                       clickCount:1
                         pressure:button_state == DOWN ? 1.0 : 0.0];
  [[NSApplication sharedApplication] postEvent:event atStart:NO];

  if (!task.is_null()) {
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindOnce(&PostWhenEventQueueIsEmpty, std::move(task)));
  }

  return true;
}

bool SendMouseClick(MouseButton type, gfx::NativeWindow window_hint) {
  CheckUIControlsEnabled();
  return SendMouseEventsNotifyWhenDone(type, UP | DOWN, base::OnceClosure(),
                                       kNoAccelerator, window_hint);
}

bool IsFullKeyboardAccessEnabled() {
  return [NSApp isFullKeyboardAccessEnabled];
}

}  // namespace ui_controls