Open History to see the last commit
1import { crc32, inflateSync } from 'node:zlib'
2import { afterEach, describe, expect, it } from 'vitest'
3import { localComputer } from '../src/index'
4import type { RobotLike } from '../src/index'
5
6type Size = { width: number; height: number }
7type Rgb = readonly [number, number, number]
8
9const RED: Rgb = [255, 0, 0]
10const BLACK: Rgb = [0, 0, 0]
11const BLUE: Rgb = [0, 0, 255]
12
13/** Extra bytes at the end of each bitmap row, as macOS adds. */
14const ROW_PADDING = 4
15
16/** A 4 x 2 screen: red over black on the left half, blue on the right half. */
17function testColor(x: number, y: number) {
18 if (x >= 2) return BLUE
19 return y === 0 ? RED : BLACK
20}
21
22/** A robotjs bitmap of one screen region: blue, green, red, unused, with padded rows. */
23function capture(
24 color: (x: number, y: number) => Rgb,
25 region: { x: number; y: number } & Size,
26) {
27 const byteWidth = region.width * 4 + ROW_PADDING
28 const image = new Uint8Array(byteWidth * region.height).fill(99)
29 for (let y = 0; y < region.height; y++) {
30 for (let x = 0; x < region.width; x++) {
31 const [red, green, blue] = color(region.x + x, region.y + y)
32 image.set([blue, green, red, 255], y * byteWidth + x * 4)
33 }
34 }
35 return { ...region, byteWidth, bytesPerPixel: 4, image }
36}
37
38/** A fake robot on a screen of the given size. Each call adds one line to `calls`. */
39function fakeRobot(screen: Size = { width: 2560, height: 1440 }) {
40 const calls: Array<string> = []
41 const record =
42 (name: string) =>
43 (...args: Array<string | number | boolean | undefined>) => {
44 calls.push([name, ...args].join(' ').trim())
45 }
46 const robot: RobotLike = {
47 getScreenSize: () => screen,
48 getMousePos: () => ({ x: 640, y: 360 }),
49 moveMouse: record('moveMouse'),
50 mouseClick: record('mouseClick'),
51 mouseToggle: record('mouseToggle'),
52 scrollMouse: record('scrollMouse'),
53 keyToggle: record('keyToggle'),
54 typeString: record('typeString'),
55 screen: {
56 capture: (x = 0, y = 0, width = screen.width, height = screen.height) => {
57 record('capture')(x, y, width, height)
58 return capture(testColor, { x, y, width, height })
59 },
60 },
61 }
62 return { robot, calls }
63}
64
65/** Decode a PNG. Checks the signature and the CRC of each chunk. */
66function readPng(png: Uint8Array) {
67 const bytes = Buffer.from(png)
68 expect([...bytes.subarray(0, 8)]).toEqual([137, 80, 78, 71, 13, 10, 26, 10])
69 const chunks = new Map<string, Buffer>()
70 let offset = 8
71 while (offset < bytes.length) {
72 const length = bytes.readUInt32BE(offset)
73 const end = offset + 8 + length
74 expect(bytes.readUInt32BE(end)).toBe(crc32(bytes.subarray(offset + 4, end)))
75 chunks.set(
76 bytes.toString('latin1', offset + 4, offset + 8),
77 bytes.subarray(offset + 8, end),
78 )
79 offset = end + 4
80 }
81 const header = chunks.get('IHDR') ?? Buffer.alloc(13)
82 return {
83 width: header.readUInt32BE(0),
84 height: header.readUInt32BE(4),
85 colorType: header[9],
86 rows: [...inflateSync(chunks.get('IDAT') ?? Buffer.alloc(0))],
87 }
88}
89
90const realPlatform = Object.getOwnPropertyDescriptor(process, 'platform')
91
92function setPlatform(platform: NodeJS.Platform) {
93 Object.defineProperty(process, 'platform', { value: platform })
94}
95
96afterEach(() => {
97 if (realPlatform) Object.defineProperty(process, 'platform', realPlatform)
98})
99
100describe('localComputer display', () => {
101 it('scales a big screen down to fit in 1280 x 800', () => {
102 const { robot } = fakeRobot({ width: 2560, height: 1440 })
103 expect(localComputer({ robot }).display).toEqual({
104 width: 1280,
105 height: 720,
106 })
107 })
108
109 it('keeps a small screen at its own size', () => {
110 const { robot } = fakeRobot({ width: 1024, height: 768 })
111 expect(localComputer({ robot }).display).toEqual({
112 width: 1024,
113 height: 768,
114 })
115 })
116
117 it.each([
118 ['win32', 'windows'],
119 ['darwin', 'mac'],
120 ['linux', 'linux'],
121 ] as const)('reports %s as %s', (platform, environment) => {
122 setPlatform(platform)
123 expect(localComputer({ robot: fakeRobot().robot }).environment).toBe(
124 environment,
125 )
126 })
127})
128
129describe('localComputer mouse', () => {
130 it('clicks at the screen point, scaled up from the display', async () => {
131 const { robot, calls } = fakeRobot()
132 await localComputer({ robot }).click(100, 50, { button: 'left', count: 1 })
133 expect(calls).toEqual(['moveMouse 200 100', 'mouseClick left'])
134 })
135
136 it('sends a double click as one robotjs double click', async () => {
137 const { robot, calls } = fakeRobot()
138 await localComputer({ robot }).click(100, 50, { button: 'right', count: 2 })
139 expect(calls).toEqual(['moveMouse 200 100', 'mouseClick right true'])
140 })
141
142 it('sends a triple click as three clicks', async () => {
143 const { robot, calls } = fakeRobot()
144 await localComputer({ robot }).click(100, 50, { button: 'left', count: 3 })
145 expect(calls).toEqual([
146 'moveMouse 200 100',
147 'mouseClick left',
148 'mouseClick left',
149 'mouseClick left',
150 ])
151 })
152
153 it('rejects the back button before the mouse moves', async () => {
154 const { robot, calls } = fakeRobot()
155 const click = localComputer({ robot }).click(1, 1, {
156 button: 'back',
157 count: 1,
158 })
159 await expect(click).rejects.toThrow(
160 'The local computer has no "back" mouse button.',
161 )
162 expect(calls).toEqual([])
163 })
164
165 it('holds and releases a mouse button', async () => {
166 const { robot, calls } = fakeRobot()
167 const driver = localComputer({ robot })
168 await driver.mouseDown('middle')
169 await driver.mouseUp('middle')
170 expect(calls).toEqual(['mouseToggle down middle', 'mouseToggle up middle'])
171 })
172
173 it('reports the mouse position in display space', async () => {
174 const { robot } = fakeRobot()
175 expect(await localComputer({ robot }).cursorPosition()).toEqual({
176 x: 320,
177 y: 180,
178 })
179 })
180
181 it.each([
182 ['darwin', 0, 120, 'scrollMouse 0 -120'],
183 ['darwin', 40, 0, 'scrollMouse -40 0'],
184 ['win32', 0, 100, 'scrollMouse 0 -120'],
185 ['win32', -50, 0, 'scrollMouse 60 0'],
186 ['linux', 0, 250, 'scrollMouse 0 -3'],
187 ['linux', 0, 30, 'scrollMouse 0 -1'],
188 ] as const)(
189 'on %s, scrolls %i, %i px as "%s"',
190 async (platform, deltaX, deltaY, expected) => {
191 setPlatform(platform)
192 const { robot, calls } = fakeRobot({ width: 1280, height: 800 })
193 await localComputer({ robot }).scroll(10, 20, deltaX, deltaY)
194 expect(calls).toEqual(['moveMouse 10 20', expected])
195 },
196 )
197})
198
199describe('localComputer keyboard', () => {
200 it('presses a combo in order, then releases it in reverse', async () => {
201 const { robot, calls } = fakeRobot()
202 await localComputer({ robot }).press(['Control', 'Shift', 'ArrowLeft'])
203 expect(calls).toEqual([
204 'keyToggle control down',
205 'keyToggle shift down',
206 'keyToggle left down',
207 'keyToggle left up',
208 'keyToggle shift up',
209 'keyToggle control up',
210 ])
211 })
212
213 it('releases the pressed keys when a later key is not valid', async () => {
214 const { robot, calls } = fakeRobot()
215 const keyToggle = robot.keyToggle
216 robot.keyToggle = (key, down) => {
217 if (key === 'not_a_key') throw new Error('Invalid key code specified.')
218 keyToggle(key, down)
219 }
220 const press = localComputer({ robot }).press([
221 'Control',
222 'Shift',
223 'NOT_A_KEY',
224 ])
225 await expect(press).rejects.toThrow('Invalid key code specified.')
226 expect(calls).toEqual([
227 'keyToggle control down',
228 'keyToggle shift down',
229 'keyToggle shift up',
230 'keyToggle control up',
231 ])
232 })
233
234 it('sends robotjs key names', async () => {
235 const { robot, calls } = fakeRobot()
236 const driver = localComputer({ robot })
237 const keys = [
238 'Meta',
239 ' ',
240 'Enter',
241 'F5',
242 'PageDown',
243 'ContextMenu',
244 'a',
245 'A',
246 ]
247 for (const key of keys) await driver.keyDown(key)
248 expect(calls).toEqual([
249 'keyToggle command down',
250 'keyToggle space down',
251 'keyToggle enter down',
252 'keyToggle f5 down',
253 'keyToggle pagedown down',
254 'keyToggle menu down',
255 'keyToggle a down',
256 'keyToggle A down',
257 ])
258 })
259
260 it('types the text', async () => {
261 const { robot, calls } = fakeRobot()
262 await localComputer({ robot }).type('hello world')
263 expect(calls).toEqual(['typeString hello world'])
264 })
265})
266
267describe('localComputer screen', () => {
268 it('takes a screenshot at the display size, with each pixel the average of the pixels it covers', async () => {
269 const { robot } = fakeRobot({ width: 4, height: 2 })
270 const png = readPng(
271 await localComputer({
272 robot,
273 display: { width: 2, height: 1 },
274 }).screenshot(),
275 )
276 expect(png).toEqual({
277 width: 2,
278 height: 1,
279 colorType: 2,
280 rows: [0, 128, 0, 0, 0, 0, 255],
281 })
282 })
283
284 it('zooms into a region at the full screen size', async () => {
285 const { robot, calls } = fakeRobot({ width: 4, height: 2 })
286 const driver = localComputer({ robot, display: { width: 2, height: 1 } })
287 const png = readPng(await driver.zoom({ x: 1, y: 0, width: 1, height: 1 }))
288 expect(calls).toEqual(['capture 2 0 2 2'])
289 expect(png).toEqual({
290 width: 2,
291 height: 2,
292 colorType: 2,
293 rows: [0, 0, 0, 255, 0, 0, 255, 0, 0, 0, 255, 0, 0, 255],
294 })
295 })
296
297 it.each([
298 [
299 'past the bottom right',
300 { x: 1, y: 0, width: 5, height: 3 },
301 'capture 2 0 2 2',
302 ],
303 [
304 'before the top left',
305 { x: -3, y: -1, width: 1, height: 1 },
306 'capture 0 0 1 1',
307 ],
308 ])('keeps a zoom region %s on the screen', async (_, region, expected) => {
309 const { robot, calls } = fakeRobot({ width: 4, height: 2 })
310 await localComputer({ robot, display: { width: 2, height: 1 } }).zoom(
311 region,
312 )
313 expect(calls).toEqual([expected])
314 })
315})