forked from chrome-php/chrome
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMouse.php
More file actions
441 lines (377 loc) · 13.9 KB
/
Copy pathMouse.php
File metadata and controls
441 lines (377 loc) · 13.9 KB
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
<?php
/*
* This file is part of Chrome PHP.
*
* (c) Soufiane Ghzal <sghzal@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace HeadlessChromium\Input;
use HeadlessChromium\Communication\Message;
use HeadlessChromium\Dom\Selector\CssSelector;
use HeadlessChromium\Dom\Selector\Selector;
use HeadlessChromium\Exception\ElementNotFoundException;
use HeadlessChromium\Exception\JavascriptException;
use HeadlessChromium\Page;
use HeadlessChromium\Utils;
class Mouse
{
public const BUTTON_LEFT = 'left';
public const BUTTON_NONE = 'none';
public const BUTTON_RIGHT = 'right';
public const BUTTON_MIDDLE = 'middle';
/**
* @var Page
*/
protected $page;
protected $x = 0;
protected $y = 0;
protected $button = self::BUTTON_NONE;
/**
* @param Page $page
*/
public function __construct(Page $page)
{
$this->page = $page;
}
/**
* @param int $x
* @param int $y
* @param array|null $options
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*
* @return $this
*/
public function move(int $x, int $y, ?array $options = null)
{
$this->page->assertNotClosed();
// get origin of the move
$originX = $this->x;
$originY = $this->y;
// set new position after move
$this->x = $x;
$this->y = $y;
// number of steps to achieve the move
$steps = $options['steps'] ?? 1;
if ($steps <= 0) {
throw new \InvalidArgumentException('options "steps" for mouse move must be a positive integer');
}
// move
for ($i = 1; $i <= $steps; ++$i) {
$this->page->getSession()->sendMessageSync(new Message('Input.dispatchMouseEvent', [
'x' => $originX + ($this->x - $originX) * ($i / $steps),
'y' => $originY + ($this->y - $originY) * ($i / $steps),
'type' => 'mouseMoved',
]));
}
return $this;
}
/**
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*/
public function press(?array $options = null)
{
$this->page->assertNotClosed();
$this->page->getSession()->sendMessageSync(new Message('Input.dispatchMouseEvent', [
'x' => $this->x,
'y' => $this->y,
'type' => 'mousePressed',
'button' => $options['button'] ?? self::BUTTON_LEFT,
'clickCount' => 1,
]));
return $this;
}
/**
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*/
public function release(?array $options = null)
{
$this->page->assertNotClosed();
$this->page->getSession()->sendMessageSync(new Message('Input.dispatchMouseEvent', [
'x' => $this->x,
'y' => $this->y,
'type' => 'mouseReleased',
'button' => $options['button'] ?? self::BUTTON_LEFT,
'clickCount' => 1,
]));
return $this;
}
/**
* @param array|null $options
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*/
public function click(?array $options = null)
{
$this->press($options);
$this->release($options);
return $this;
}
/**
* Scroll up using the mouse wheel.
*
* @param int $distance Distance in pixels
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
* @throws \HeadlessChromium\Exception\OperationTimedOut
*
* @return $this
*/
public function scrollUp(int $distance)
{
return $this->scroll(-1 * \abs($distance));
}
/**
* Scroll down using the mouse wheel.
*
* @param int $distance Distance in pixels
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
* @throws \HeadlessChromium\Exception\OperationTimedOut
*
* @return $this
*/
public function scrollDown(int $distance)
{
return $this->scroll(\abs($distance));
}
/**
* Scroll a positive or negative distance using the mouseWheel event type.
*
* @param int $distanceY Distance in pixels for the Y axis
* @param int $distanceX (optional) Distance in pixels for the X axis
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
* @throws \HeadlessChromium\Exception\OperationTimedOut
*
* @return $this
*/
private function scroll(int $distanceY, int $distanceX = 0): self
{
$this->page->assertNotClosed();
// make sure the mouse is on the screen
$this->move($this->x, $this->y);
[$distances, $targets] = $this->getScrollDistancesAndTargets($distanceY, $distanceX);
// scroll
$this->sendScrollMessage($distances);
try {
// wait until the scroll is done
Utils::tryWithTimeout(3_000_000, $this->waitForScroll($targets['x'], $targets['y']));
} catch (\HeadlessChromium\Exception\OperationTimedOut $exception) {
// Maybe the possible max scroll distances changed in the meantime.
$prevDistances = $distances;
[$distances, $targets] = $this->getScrollDistancesAndTargets($distanceY, $distanceX);
if ($prevDistances === $distances) {
throw $exception;
}
if (0 !== $distanceY || 0 !== $distanceX) { // Try with the new values.
$this->sendScrollMessage($distances);
// wait until the scroll is done
Utils::tryWithTimeout(3_000_000, $this->waitForScroll($targets['x'], $targets['y']));
}
}
// set new position after move
$this->x += $distances['x'];
$this->y += $distances['y'];
return $this;
}
/**
* @throws \HeadlessChromium\Exception\OperationTimedOut
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\CommunicationException\ResponseHasError
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*
* @return array{ array{ x: int, y: int }, array{ x: int, y: int } }
*/
private function getScrollDistancesAndTargets(int $distanceY, int $distanceX = 0): array
{
$scrollableArea = $this->page->getLayoutMetrics()->getCssContentSize();
$visibleArea = $this->page->getLayoutMetrics()->getCssVisualViewport();
$maximumX = $scrollableArea['width'] - $visibleArea['clientWidth'];
$maximumY = $scrollableArea['height'] - $visibleArea['clientHeight'];
$distanceX = $this->getMaximumDistance($distanceX, $visibleArea['pageX'], $maximumX);
$distanceY = $this->getMaximumDistance($distanceY, $visibleArea['pageY'], $maximumY);
$targetX = $visibleArea['pageX'] + $distanceX;
$targetY = $visibleArea['pageY'] + $distanceY;
return [
['x' => $distanceX, 'y' => $distanceY],
['x' => (int) $targetX, 'y' => (int) $targetY],
];
}
/**
* @param array{ x: int, y: int } $distances
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
*/
private function sendScrollMessage(array $distances): void
{
$this->page->getSession()->sendMessageSync(new Message('Input.dispatchMouseEvent', [
'type' => 'mouseWheel',
'x' => $this->x,
'y' => $this->y,
'deltaX' => $distances['x'],
'deltaY' => $distances['y'],
]));
}
/**
* Scroll in both X and Y axis until the given boundaries fit in the screen.
*
* This method currently scrolls only to right and bottom. If the desired element is outside the visible screen
* to the left or top, thie method will not work. Its visibility will stay private until it works for both cases.
*
* @param int $right The element right boundary
* @param int $bottom The element bottom boundary
*
* @return $this
*/
private function scrollToBoundary(int $right, int $bottom): self
{
$visibleArea = $this->page->getLayoutMetrics()->getCssLayoutViewport();
$distanceX = $distanceY = 0;
if ($right > $visibleArea['clientWidth']) {
$distanceX = $right - $visibleArea['clientWidth'];
}
if ($bottom > $visibleArea['clientHeight']) {
$distanceY = $bottom - $visibleArea['clientHeight'];
}
return $this->scroll($distanceY, $distanceX);
}
/**
* Find an element and move the mouse to a random position over it.
*
* The search could result in several elements. The $position param can be used to select a specific element.
* The given position can only be between 1 and the maximum number or elements. It will be adjusted to the
* minimum and maximum values if needed.
*
* Example:
* $page->mouse()->find('#a'):
* $page->mouse()->find('.a', 2);
*
* @see https://developer.mozilla.org/docs/Web/API/Document/querySelector
*
* @param string $selectors selectors to use with document.querySelector
* @param int $position (optional) which element of the result set should be used
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
* @throws \HeadlessChromium\Exception\ElementNotFoundException
*
* @return $this
*/
public function find(string $selectors, int $position = 1): self
{
$this->findElement(new CssSelector($selectors), $position);
return $this;
}
/**
* Find an element and move the mouse to a random position over it.
*
* The search could result in several elements. The $position param can be used to select a specific element.
* The given position can only be between 1 and the maximum number or elements. It will be adjusted to the
* minimum and maximum values if needed.
*
* Example:
* $page->mouse()->findElement(new CssSelector('#a')):
* $page->mouse()->findElement(new CssSelector('.a'), 2);
* $page->mouse()->findElement(new XPathSelector('//*[@id="a"]'), 2);
*
* @param Selector $selector selector to use
* @param int $position (optional) which element of the result set should be used
*
* @throws \HeadlessChromium\Exception\CommunicationException
* @throws \HeadlessChromium\Exception\NoResponseAvailable
* @throws \HeadlessChromium\Exception\ElementNotFoundException
*
* @return $this
*/
public function findElement(Selector $selector, int $position = 1): self
{
$this->page->assertNotClosed();
try {
$element = Utils::getElementPositionFromPage($this->page, $selector, $position);
} catch (JavascriptException $exception) {
throw new ElementNotFoundException('The search for "'.$selector->expressionCount().'" returned no result.');
}
if (false === \array_key_exists('x', $element)) {
throw new ElementNotFoundException('The search for "'.$selector->expressionFindOne($position).'" returned an element with no position.');
}
$rightBoundary = \floor($element['right']);
$bottomBoundary = \floor($element['bottom']);
$this->scrollToBoundary($rightBoundary, $bottomBoundary);
$visibleArea = $this->page->getLayoutMetrics()->getLayoutViewport();
$offsetX = $visibleArea['pageX'];
$offsetY = $visibleArea['pageY'];
$minX = $element['left'] - $offsetX;
$minY = $element['top'] - $offsetY;
$positionX = \floor($minX + (($rightBoundary - $offsetX) - $minX) / 2);
$positionY = \ceil($minY + (($bottomBoundary - $offsetY) - $minY) / 2);
$this->move($positionX, $positionY);
return $this;
}
/**
* Get the maximum distance to scroll a page.
*
* @param int $distance Distance to scroll, positive or negative
* @param int $current Current position
* @param int $maximum Maximum possible distance
*
* @return int allowed distance to scroll
*/
private function getMaximumDistance(int $distance, int $current, int $maximum): int
{
$result = $current + $distance;
if ($result < 0) {
return $distance + \abs($result);
}
if ($result > $maximum) {
return $maximum - $current;
}
return $distance;
}
/**
* Wait for the browser to process the scroll command.
*
* Return the number of microseconds to wait before trying again or true in case of success.
*
* @see \HeadlessChromium\Utils::tryWithTimeout
*
* @param int $targetX
* @param int $targetY
*
* @throws \HeadlessChromium\Exception\OperationTimedOut
*
* @return bool|\Generator
*/
private function waitForScroll(int $targetX, int $targetY)
{
while (true) {
$visibleArea = $this->page->getLayoutMetrics()->getCssVisualViewport();
if ($visibleArea['pageX'] === $targetX && $visibleArea['pageY'] === $targetY) {
return true;
}
yield 1000;
}
}
/**
* Get the current mouse position.
*
* @return array [x, y]
*/
public function getPosition(): array
{
return [
'x' => $this->x,
'y' => $this->y,
];
}
}