summaryrefslogtreecommitdiffstats
path: root/remote/test/puppeteer/packages/puppeteer-core/src/cdp/Input.ts
blob: 0674ef46341392181de917fa24c5ba0e7c7e9b45 (plain)
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
/**
 * @license
 * Copyright 2017 Google Inc.
 * SPDX-License-Identifier: Apache-2.0
 */

import type {Protocol} from 'devtools-protocol';

import type {CDPSession} from '../api/CDPSession.js';
import type {Point} from '../api/ElementHandle.js';
import {
  Keyboard,
  Mouse,
  MouseButton,
  Touchscreen,
  type KeyDownOptions,
  type KeyPressOptions,
  type KeyboardTypeOptions,
  type MouseClickOptions,
  type MouseMoveOptions,
  type MouseOptions,
  type MouseWheelOptions,
} from '../api/Input.js';
import {
  _keyDefinitions,
  type KeyDefinition,
  type KeyInput,
} from '../common/USKeyboardLayout.js';
import {assert} from '../util/assert.js';

type KeyDescription = Required<
  Pick<KeyDefinition, 'keyCode' | 'key' | 'text' | 'code' | 'location'>
>;

/**
 * @internal
 */
export class CdpKeyboard extends Keyboard {
  #client: CDPSession;
  #pressedKeys = new Set<string>();

  _modifiers = 0;

  constructor(client: CDPSession) {
    super();
    this.#client = client;
  }

  updateClient(client: CDPSession): void {
    this.#client = client;
  }

  override async down(
    key: KeyInput,
    options: Readonly<KeyDownOptions> = {
      text: undefined,
      commands: [],
    }
  ): Promise<void> {
    const description = this.#keyDescriptionForString(key);

    const autoRepeat = this.#pressedKeys.has(description.code);
    this.#pressedKeys.add(description.code);
    this._modifiers |= this.#modifierBit(description.key);

    const text = options.text === undefined ? description.text : options.text;
    await this.#client.send('Input.dispatchKeyEvent', {
      type: text ? 'keyDown' : 'rawKeyDown',
      modifiers: this._modifiers,
      windowsVirtualKeyCode: description.keyCode,
      code: description.code,
      key: description.key,
      text: text,
      unmodifiedText: text,
      autoRepeat,
      location: description.location,
      isKeypad: description.location === 3,
      commands: options.commands,
    });
  }

  #modifierBit(key: string): number {
    if (key === 'Alt') {
      return 1;
    }
    if (key === 'Control') {
      return 2;
    }
    if (key === 'Meta') {
      return 4;
    }
    if (key === 'Shift') {
      return 8;
    }
    return 0;
  }

  #keyDescriptionForString(keyString: KeyInput): KeyDescription {
    const shift = this._modifiers & 8;
    const description = {
      key: '',
      keyCode: 0,
      code: '',
      text: '',
      location: 0,
    };

    const definition = _keyDefinitions[keyString];
    assert(definition, `Unknown key: "${keyString}"`);

    if (definition.key) {
      description.key = definition.key;
    }
    if (shift && definition.shiftKey) {
      description.key = definition.shiftKey;
    }

    if (definition.keyCode) {
      description.keyCode = definition.keyCode;
    }
    if (shift && definition.shiftKeyCode) {
      description.keyCode = definition.shiftKeyCode;
    }

    if (definition.code) {
      description.code = definition.code;
    }

    if (definition.location) {
      description.location = definition.location;
    }

    if (description.key.length === 1) {
      description.text = description.key;
    }

    if (definition.text) {
      description.text = definition.text;
    }
    if (shift && definition.shiftText) {
      description.text = definition.shiftText;
    }

    // if any modifiers besides shift are pressed, no text should be sent
    if (this._modifiers & ~8) {
      description.text = '';
    }

    return description;
  }

  override async up(key: KeyInput): Promise<void> {
    const description = this.#keyDescriptionForString(key);

    this._modifiers &= ~this.#modifierBit(description.key);
    this.#pressedKeys.delete(description.code);
    await this.#client.send('Input.dispatchKeyEvent', {
      type: 'keyUp',
      modifiers: this._modifiers,
      key: description.key,
      windowsVirtualKeyCode: description.keyCode,
      code: description.code,
      location: description.location,
    });
  }

  override async sendCharacter(char: string): Promise<void> {
    await this.#client.send('Input.insertText', {text: char});
  }

  private charIsKey(char: string): char is KeyInput {
    return !!_keyDefinitions[char as KeyInput];
  }

  override async type(
    text: string,
    options: Readonly<KeyboardTypeOptions> = {}
  ): Promise<void> {
    const delay = options.delay || undefined;
    for (const char of text) {
      if (this.charIsKey(char)) {
        await this.press(char, {delay});
      } else {
        if (delay) {
          await new Promise(f => {
            return setTimeout(f, delay);
          });
        }
        await this.sendCharacter(char);
      }
    }
  }

  override async press(
    key: KeyInput,
    options: Readonly<KeyPressOptions> = {}
  ): Promise<void> {
    const {delay = null} = options;
    await this.down(key, options);
    if (delay) {
      await new Promise(f => {
        return setTimeout(f, options.delay);
      });
    }
    await this.up(key);
  }
}

/**
 * This must follow {@link Protocol.Input.DispatchMouseEventRequest.buttons}.
 */
const enum MouseButtonFlag {
  None = 0,
  Left = 1,
  Right = 1 << 1,
  Middle = 1 << 2,
  Back = 1 << 3,
  Forward = 1 << 4,
}

const getFlag = (button: MouseButton): MouseButtonFlag => {
  switch (button) {
    case MouseButton.Left:
      return MouseButtonFlag.Left;
    case MouseButton.Right:
      return MouseButtonFlag.Right;
    case MouseButton.Middle:
      return MouseButtonFlag.Middle;
    case MouseButton.Back:
      return MouseButtonFlag.Back;
    case MouseButton.Forward:
      return MouseButtonFlag.Forward;
  }
};

/**
 * This should match
 * https://source.chromium.org/chromium/chromium/src/+/refs/heads/main:content/browser/renderer_host/input/web_input_event_builders_mac.mm;drc=a61b95c63b0b75c1cfe872d9c8cdf927c226046e;bpv=1;bpt=1;l=221.
 */
const getButtonFromPressedButtons = (
  buttons: number
): Protocol.Input.MouseButton => {
  if (buttons & MouseButtonFlag.Left) {
    return MouseButton.Left;
  } else if (buttons & MouseButtonFlag.Right) {
    return MouseButton.Right;
  } else if (buttons & MouseButtonFlag.Middle) {
    return MouseButton.Middle;
  } else if (buttons & MouseButtonFlag.Back) {
    return MouseButton.Back;
  } else if (buttons & MouseButtonFlag.Forward) {
    return MouseButton.Forward;
  }
  return 'none';
};

interface MouseState {
  /**
   * The current position of the mouse.
   */
  position: Point;
  /**
   * The buttons that are currently being pressed.
   */
  buttons: number;
}

/**
 * @internal
 */
export class CdpMouse extends Mouse {
  #client: CDPSession;
  #keyboard: CdpKeyboard;

  constructor(client: CDPSession, keyboard: CdpKeyboard) {
    super();
    this.#client = client;
    this.#keyboard = keyboard;
  }

  updateClient(client: CDPSession): void {
    this.#client = client;
  }

  #_state: Readonly<MouseState> = {
    position: {x: 0, y: 0},
    buttons: MouseButtonFlag.None,
  };
  get #state(): MouseState {
    return Object.assign({...this.#_state}, ...this.#transactions);
  }

  // Transactions can run in parallel, so we store each of thme in this array.
  #transactions: Array<Partial<MouseState>> = [];
  #createTransaction(): {
    update: (updates: Partial<MouseState>) => void;
    commit: () => void;
    rollback: () => void;
  } {
    const transaction: Partial<MouseState> = {};
    this.#transactions.push(transaction);
    const popTransaction = () => {
      this.#transactions.splice(this.#transactions.indexOf(transaction), 1);
    };
    return {
      update: (updates: Partial<MouseState>) => {
        Object.assign(transaction, updates);
      },
      commit: () => {
        this.#_state = {...this.#_state, ...transaction};
        popTransaction();
      },
      rollback: popTransaction,
    };
  }

  /**
   * This is a shortcut for a typical update, commit/rollback lifecycle based on
   * the error of the action.
   */
  async #withTransaction(
    action: (update: (updates: Partial<MouseState>) => void) => Promise<unknown>
  ): Promise<void> {
    const {update, commit, rollback} = this.#createTransaction();
    try {
      await action(update);
      commit();
    } catch (error) {
      rollback();
      throw error;
    }
  }

  override async reset(): Promise<void> {
    const actions = [];
    for (const [flag, button] of [
      [MouseButtonFlag.Left, MouseButton.Left],
      [MouseButtonFlag.Middle, MouseButton.Middle],
      [MouseButtonFlag.Right, MouseButton.Right],
      [MouseButtonFlag.Forward, MouseButton.Forward],
      [MouseButtonFlag.Back, MouseButton.Back],
    ] as const) {
      if (this.#state.buttons & flag) {
        actions.push(this.up({button: button}));
      }
    }
    if (this.#state.position.x !== 0 || this.#state.position.y !== 0) {
      actions.push(this.move(0, 0));
    }
    await Promise.all(actions);
  }

  override async move(
    x: number,
    y: number,
    options: Readonly<MouseMoveOptions> = {}
  ): Promise<void> {
    const {steps = 1} = options;
    const from = this.#state.position;
    const to = {x, y};
    for (let i = 1; i <= steps; i++) {
      await this.#withTransaction(updateState => {
        updateState({
          position: {
            x: from.x + (to.x - from.x) * (i / steps),
            y: from.y + (to.y - from.y) * (i / steps),
          },
        });
        const {buttons, position} = this.#state;
        return this.#client.send('Input.dispatchMouseEvent', {
          type: 'mouseMoved',
          modifiers: this.#keyboard._modifiers,
          buttons,
          button: getButtonFromPressedButtons(buttons),
          ...position,
        });
      });
    }
  }

  override async down(options: Readonly<MouseOptions> = {}): Promise<void> {
    const {button = MouseButton.Left, clickCount = 1} = options;
    const flag = getFlag(button);
    if (!flag) {
      throw new Error(`Unsupported mouse button: ${button}`);
    }
    if (this.#state.buttons & flag) {
      throw new Error(`'${button}' is already pressed.`);
    }
    await this.#withTransaction(updateState => {
      updateState({
        buttons: this.#state.buttons | flag,
      });
      const {buttons, position} = this.#state;
      return this.#client.send('Input.dispatchMouseEvent', {
        type: 'mousePressed',
        modifiers: this.#keyboard._modifiers,
        clickCount,
        buttons,
        button,
        ...position,
      });
    });
  }

  override async up(options: Readonly<MouseOptions> = {}): Promise<void> {
    const {button = MouseButton.Left, clickCount = 1} = options;
    const flag = getFlag(button);
    if (!flag) {
      throw new Error(`Unsupported mouse button: ${button}`);
    }
    if (!(this.#state.buttons & flag)) {
      throw new Error(`'${button}' is not pressed.`);
    }
    await this.#withTransaction(updateState => {
      updateState({
        buttons: this.#state.buttons & ~flag,
      });
      const {buttons, position} = this.#state;
      return this.#client.send('Input.dispatchMouseEvent', {
        type: 'mouseReleased',
        modifiers: this.#keyboard._modifiers,
        clickCount,
        buttons,
        button,
        ...position,
      });
    });
  }

  override async click(
    x: number,
    y: number,
    options: Readonly<MouseClickOptions> = {}
  ): Promise<void> {
    const {delay, count = 1, clickCount = count} = options;
    if (count < 1) {
      throw new Error('Click must occur a positive number of times.');
    }
    const actions: Array<Promise<void>> = [this.move(x, y)];
    if (clickCount === count) {
      for (let i = 1; i < count; ++i) {
        actions.push(
          this.down({...options, clickCount: i}),
          this.up({...options, clickCount: i})
        );
      }
    }
    actions.push(this.down({...options, clickCount}));
    if (typeof delay === 'number') {
      await Promise.all(actions);
      actions.length = 0;
      await new Promise(resolve => {
        setTimeout(resolve, delay);
      });
    }
    actions.push(this.up({...options, clickCount}));
    await Promise.all(actions);
  }

  override async wheel(
    options: Readonly<MouseWheelOptions> = {}
  ): Promise<void> {
    const {deltaX = 0, deltaY = 0} = options;
    const {position, buttons} = this.#state;
    await this.#client.send('Input.dispatchMouseEvent', {
      type: 'mouseWheel',
      pointerType: 'mouse',
      modifiers: this.#keyboard._modifiers,
      deltaY,
      deltaX,
      buttons,
      ...position,
    });
  }

  override async drag(
    start: Point,
    target: Point
  ): Promise<Protocol.Input.DragData> {
    const promise = new Promise<Protocol.Input.DragData>(resolve => {
      this.#client.once('Input.dragIntercepted', event => {
        return resolve(event.data);
      });
    });
    await this.move(start.x, start.y);
    await this.down();
    await this.move(target.x, target.y);
    return await promise;
  }

  override async dragEnter(
    target: Point,
    data: Protocol.Input.DragData
  ): Promise<void> {
    await this.#client.send('Input.dispatchDragEvent', {
      type: 'dragEnter',
      x: target.x,
      y: target.y,
      modifiers: this.#keyboard._modifiers,
      data,
    });
  }

  override async dragOver(
    target: Point,
    data: Protocol.Input.DragData
  ): Promise<void> {
    await this.#client.send('Input.dispatchDragEvent', {
      type: 'dragOver',
      x: target.x,
      y: target.y,
      modifiers: this.#keyboard._modifiers,
      data,
    });
  }

  override async drop(
    target: Point,
    data: Protocol.Input.DragData
  ): Promise<void> {
    await this.#client.send('Input.dispatchDragEvent', {
      type: 'drop',
      x: target.x,
      y: target.y,
      modifiers: this.#keyboard._modifiers,
      data,
    });
  }

  override async dragAndDrop(
    start: Point,
    target: Point,
    options: {delay?: number} = {}
  ): Promise<void> {
    const {delay = null} = options;
    const data = await this.drag(start, target);
    await this.dragEnter(target, data);
    await this.dragOver(target, data);
    if (delay) {
      await new Promise(resolve => {
        return setTimeout(resolve, delay);
      });
    }
    await this.drop(target, data);
    await this.up();
  }
}

/**
 * @internal
 */
export class CdpTouchscreen extends Touchscreen {
  #client: CDPSession;
  #keyboard: CdpKeyboard;

  constructor(client: CDPSession, keyboard: CdpKeyboard) {
    super();
    this.#client = client;
    this.#keyboard = keyboard;
  }

  updateClient(client: CDPSession): void {
    this.#client = client;
  }

  override async touchStart(x: number, y: number): Promise<void> {
    await this.#client.send('Input.dispatchTouchEvent', {
      type: 'touchStart',
      touchPoints: [
        {
          x: Math.round(x),
          y: Math.round(y),
          radiusX: 0.5,
          radiusY: 0.5,
          force: 0.5,
        },
      ],
      modifiers: this.#keyboard._modifiers,
    });
  }

  override async touchMove(x: number, y: number): Promise<void> {
    await this.#client.send('Input.dispatchTouchEvent', {
      type: 'touchMove',
      touchPoints: [
        {
          x: Math.round(x),
          y: Math.round(y),
          radiusX: 0.5,
          radiusY: 0.5,
          force: 0.5,
        },
      ],
      modifiers: this.#keyboard._modifiers,
    });
  }

  override async touchEnd(): Promise<void> {
    await this.#client.send('Input.dispatchTouchEvent', {
      type: 'touchEnd',
      touchPoints: [],
      modifiers: this.#keyboard._modifiers,
    });
  }
}