@sdeck/core 0.4.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdeck/core",
3
- "version": "0.4.0",
3
+ "version": "0.5.1",
4
4
  "description": "Device-independent core for driving Elgato Stream Decks: transport, images, layouts, reconnecting.",
5
5
  "license": "MIT",
6
6
  "type": "module",
package/src/deck.ts CHANGED
@@ -7,9 +7,9 @@ import {
7
7
  type Size,
8
8
  } from "./element.ts";
9
9
  import { Framebuffer, type Rect, type RGB, solidRgb } from "./framebuffer.ts";
10
- import { encodeJpeg, type ImageOptions, type ImageSource, toRgb } from "./image.ts";
10
+ import { encodeJpeg, type ImageOptions, type ImageSource, type Rotation, toRgb } from "./image.ts";
11
11
  import type { Renderable } from "./index.ts";
12
- import { composeScreenRaw, type DeckLayout, type ScreenLayout } from "./layout.ts";
12
+ import { composeScreenRaw, type DeckLayout, type ScreenLayout, slotRect } from "./layout.ts";
13
13
  import type { HidTransport } from "./transport.ts";
14
14
 
15
15
  /** Static description of a Stream Deck model. */
@@ -27,11 +27,30 @@ export interface DeckModel {
27
27
  * content larger; the extra room along one side is layout space. Without this, elements are
28
28
  * laid out at the slot's own pixels.
29
29
  */
30
- design?: Readonly<{ key?: Size; sensor?: Size; window?: Size }>;
31
- /** Rotation the device expects images in. */
32
- rotation: 0 | 180;
30
+ design?: Readonly<{ key?: Size; sensor?: Size; dial?: Size; window?: Size }>;
31
+ /** Clockwise rotation the device expects images in. */
32
+ rotation: Rotation;
33
33
  }
34
34
 
35
+ /** A place on the window, in its own upright pixels. */
36
+ export interface Point {
37
+ x: number;
38
+ y: number;
39
+ }
40
+
41
+ /** What an input report says. */
42
+ export type DeckInput =
43
+ /** Which keys, and after them which sensors, are down now. */
44
+ | { type: "buttons"; pressed: readonly boolean[] }
45
+ /** Which dials are pressed now. */
46
+ | { type: "dials"; pressed: readonly boolean[] }
47
+ /** How far each dial turned since the last report, clockwise being positive. */
48
+ | { type: "turn"; ticks: readonly number[] }
49
+ /** A finger touched the window, and is gone again. */
50
+ | { type: "tap"; at: Point; long: boolean }
51
+ /** A finger slid across the window. */
52
+ | { type: "swipe"; from: Point; to: Point };
53
+
35
54
  export interface DeckEvents {
36
55
  /** A key was pressed. */
37
56
  keyDown: [index: number];
@@ -41,6 +60,18 @@ export interface DeckEvents {
41
60
  sensorDown: [index: number];
42
61
  /** A capacitive sensor was released. */
43
62
  sensorUp: [index: number];
63
+ /** A dial was pressed. */
64
+ dialDown: [index: number];
65
+ /** A dial was released. */
66
+ dialUp: [index: number];
67
+ /** A dial was turned by this many steps, clockwise being positive. */
68
+ dialTurn: [index: number, ticks: number];
69
+ /** The part of the window that belongs to a dial was tapped, or held for a moment. */
70
+ dialTap: [index: number, long: boolean];
71
+ /** The window was tapped, or held for a moment. */
72
+ windowTap: [at: Point, long: boolean];
73
+ /** A finger slid across the window. */
74
+ windowSwipe: [from: Point, to: Point];
44
75
  /** Pixels reached the device: the region (upright screen coordinates) that was written. */
45
76
  draw: [region: Rect];
46
77
  /** The deck is closing. Keys held down get no release. */
@@ -50,14 +81,23 @@ export interface DeckEvents {
50
81
 
51
82
  type Listener<K extends keyof DeckEvents> = (...args: DeckEvents[K]) => void;
52
83
 
53
- /** Options for `mountKey`, `mountSensor`, `mountWindow` and `mountScreen`. */
84
+ /** Options for `mountKey`, `mountSensor`, `mountDial`, `mountWindow` and `mountScreen`. */
54
85
  export type MountOptions = ElementOptions & Pick<ImageOptions, "quality" | "background">;
55
86
 
56
87
  export const toError = (error: unknown): Error =>
57
88
  error instanceof Error ? error : new Error(String(error));
58
89
 
59
- /** Every part of the screen the deck tracks: keys, strips, the window and everything else. */
60
- type Slot = `key:${number}` | `sensor:${number}` | "window" | "rest";
90
+ /**
91
+ * Every part of the screen the deck tracks: keys, strips, the window and everything else. Where
92
+ * there are dials, the window is what their parts of it make up together.
93
+ */
94
+ type Slot =
95
+ | `key:${number}`
96
+ | `sensor:${number}`
97
+ | `dial:${number}`
98
+ | `window:${number}`
99
+ | "window"
100
+ | "rest";
61
101
 
62
102
  interface PendingFrame {
63
103
  quality?: number | undefined;
@@ -69,7 +109,7 @@ const nextTick = () => new Promise<void>((resolve) => setImmediate(resolve));
69
109
  /**
70
110
  * Base class of every supported Stream Deck. A model implements the device protocol (the
71
111
  * `send*` primitives and input parsing); this class provides everything else: events,
72
- * serialised writes, image conversion, sensor strips, full-screen layouts and live elements.
112
+ * serialized writes, image conversion, sensor strips, full-screen layouts and live elements.
73
113
  *
74
114
  * The deck keeps a framebuffer of what is on the LCD. That makes sensor strips cheap (a strip
75
115
  * redraw re-encodes the framebuffer instead of every slot), lets anything drawn survive a strip
@@ -84,20 +124,28 @@ export abstract class StreamDeck {
84
124
  keyUp: new Set(),
85
125
  sensorDown: new Set(),
86
126
  sensorUp: new Set(),
127
+ dialDown: new Set(),
128
+ dialUp: new Set(),
129
+ dialTurn: new Set(),
130
+ dialTap: new Set(),
131
+ windowTap: new Set(),
132
+ windowSwipe: new Set(),
87
133
  draw: new Set(),
88
134
  close: new Set(),
89
135
  error: new Set(),
90
136
  };
91
137
  readonly #unsubscribe: Array<() => void>;
92
- #pressed: boolean[] = [];
138
+ #pressed: readonly boolean[] = [];
139
+ #dials: readonly boolean[] = [];
93
140
  #closed = false;
94
141
  #roots = new Set<ElementRoot>();
95
- /** Serialises writes so multi-packet image uploads never interleave. */
142
+ /** Serializes writes so multi-packet image uploads never interleave. */
96
143
  #queue: Promise<unknown> = Promise.resolve();
97
144
 
98
145
  /** Upright pixels as they are (or, once queued writes finish, will be) on the LCD. */
99
146
  readonly #screen: Framebuffer;
100
147
  readonly #allSlots: readonly Slot[];
148
+ readonly #windowSlots: readonly Slot[];
101
149
  /** Slots whose device pixels are known to match the framebuffer. */
102
150
  readonly #known = new Set<Slot>();
103
151
  /** Bumped whenever a slot's framebuffer pixels change. */
@@ -112,10 +160,16 @@ export abstract class StreamDeck {
112
160
  this.transport = transport;
113
161
  this.model = model;
114
162
  this.#screen = new Framebuffer(model.layout.screen);
163
+ const dials = model.layout.dials ?? [];
164
+ const dialSlots = dials.map((_, i): Slot => `dial:${i}`);
165
+ const shared = dials.length > 0 && !model.layout.separateDials;
166
+ this.#windowSlots = shared ? dialSlots : ["window"];
115
167
  this.#allSlots = [
116
168
  ...model.layout.keys.map((_, i): Slot => `key:${i}`),
117
169
  ...model.layout.sensors.map((_, i): Slot => `sensor:${i}`),
118
- ...(model.layout.window ? (["window"] as const) : []),
170
+ ...(model.layout.window ? this.#windowSlots : []),
171
+ ...(model.layout.separateDials ? dialSlots : []),
172
+ ...(model.layout.windows ?? []).map((_, i): Slot => `window:${i + 1}`),
119
173
  "rest",
120
174
  ];
121
175
  this.#unsubscribe = [
@@ -132,12 +186,19 @@ export abstract class StreamDeck {
132
186
  get sensorCount(): number {
133
187
  return this.model.layout.sensors.length;
134
188
  }
189
+ get dialCount(): number {
190
+ return this.model.layout.dials?.length ?? 0;
191
+ }
135
192
  get keySize(): Size {
136
193
  return this.#size(this.model.layout.keys[0], "keys");
137
194
  }
138
195
  get sensorSize(): Size {
139
196
  return this.#size(this.model.layout.sensors[0], "sensor strips");
140
197
  }
198
+ /** The part of the window that belongs to a dial. */
199
+ get dialSize(): Size {
200
+ return this.#size(this.model.layout.dials?.[0], "dials");
201
+ }
141
202
  get windowSize(): Size {
142
203
  return this.#size(this.model.layout.window, "a window");
143
204
  }
@@ -152,11 +213,14 @@ export abstract class StreamDeck {
152
213
  * How a live element on a slot is drawn: `size` is the room it lays out in, and `scale` how
153
214
  * many times larger that appears (see {@link DeckModel.design}).
154
215
  */
155
- slotDrawing(kind: "key" | "sensor" | "window", index = 0): { size: Size; scale: number } {
216
+ slotDrawing(
217
+ kind: "key" | "sensor" | "dial" | "window",
218
+ index = 0,
219
+ ): { size: Size; scale: number } {
156
220
  const { layout, design } = this.model;
157
- const rect =
158
- kind === "window" ? layout.window : (kind === "key" ? layout.keys : layout.sensors)[index];
159
- const size = this.#size(rect, kind === "window" ? "a window" : `${kind} ${index}`);
221
+ const rect = slotRect(layout, kind, index);
222
+ const what = kind === "window" ? (index ? `window ${index}` : "a window") : `${kind} ${index}`;
223
+ const size = this.#size(rect, what);
160
224
  const base = design?.[kind];
161
225
  if (!base) return { size, scale: 1 };
162
226
  const scale = Math.min(size.width / base.width, size.height / base.height);
@@ -209,26 +273,41 @@ export abstract class StreamDeck {
209
273
  // The `send*` methods are called inside the write queue, in order; they write straight to the
210
274
  // transport and must not enqueue.
211
275
 
212
- /** Parses an input report into pressed states: keys first, then sensors. */
213
- protected abstract parseInput(data: Uint8Array): boolean[] | undefined;
214
- protected abstract sendKeyJpeg(index: number, jpeg: Uint8Array): Promise<void>;
215
- protected abstract sendScreenJpeg(jpeg: Uint8Array): Promise<void>;
216
- protected sendWindowJpeg(_jpeg: Uint8Array): Promise<void> {
276
+ /** What an input report says, or `undefined` for one that says nothing of interest. */
277
+ protected abstract parseInput(data: Uint8Array): DeckInput | undefined;
278
+ protected abstract sendKeyImage(index: number, image: Uint8Array): Promise<void>;
279
+ protected abstract sendScreenImage(image: Uint8Array): Promise<void>;
280
+ protected sendWindowImage(_image: Uint8Array): Promise<void> {
217
281
  return Promise.reject(new Error(`${this.model.name} has no window`));
218
282
  }
219
- /** Sends a JPEG to part of the window; `region` is relative to the window. */
220
- protected sendWindowRegionJpeg(_region: Rect, _jpeg: Uint8Array): Promise<void> {
283
+ /** Sends an image to part of the window; `region` is relative to the window. */
284
+ protected sendWindowRegionImage(_region: Rect, _image: Uint8Array): Promise<void> {
221
285
  return Promise.reject(new Error(`${this.model.name} cannot update part of the window`));
222
286
  }
223
- /** Fills a key with a colour. Override if the model has a command for it. */
287
+ /** Fills a key with a color. Override if the model has a command for it. */
224
288
  protected async sendFillKey(index: number, color: RGB): Promise<void> {
225
289
  const size = this.#size(this.model.layout.keys[index], "keys");
226
- await this.sendKeyJpeg(index, await this.#encode(solidRgb(size, color), size));
290
+ await this.sendKeyImage(index, await this.encodeImage(solidRgb(size, color), size));
227
291
  }
228
- /** Fills the screen with a colour. Override if the model has a command for it. */
292
+ /** Fills the screen with a color. Override if the model has a command for it. */
229
293
  protected async sendFillScreen(color: RGB): Promise<void> {
230
294
  const size = this.screenSize;
231
- await this.sendScreenJpeg(await this.#encode(solidRgb(size, color), size));
295
+ await this.sendScreenImage(await this.encodeImage(solidRgb(size, color), size));
296
+ }
297
+ /**
298
+ * Turns upright RGB pixels into what the device takes: a JPEG, rotated as the model needs.
299
+ * Override if it takes something else.
300
+ */
301
+ protected encodeImage(rgb: Uint8Array, size: Size, quality?: number): Promise<Uint8Array> {
302
+ return encodeJpeg(rgb, size, { quality, rotation: this.model.rotation });
303
+ }
304
+ /**
305
+ * Prepares a frame of the whole screen, and returns what sends it. Override if the model has no
306
+ * command for the whole screen.
307
+ */
308
+ protected prepareFrame(screen: Framebuffer, quality?: number): () => Promise<void> {
309
+ const image = this.#encode(screen.data.slice(), this.screenSize, quality);
310
+ return async () => this.sendScreenImage(await image);
232
311
  }
233
312
  /** Runs (queued, before the transport closes) when `close()` is called, e.g. to show a logo. */
234
313
  protected async onClosing(): Promise<void> {}
@@ -260,20 +339,63 @@ export abstract class StreamDeck {
260
339
  const rgb = await toRgb(image, rect, options);
261
340
  if (!current()) return;
262
341
  await this.#commit([slot], rect, rgb, () => {
263
- const jpeg = this.#encode(rgb, rect, options?.quality);
264
- return async () => this.sendKeyJpeg(index, await jpeg);
342
+ const encoded = this.#encode(rgb, rect, options?.quality);
343
+ return async () => this.sendKeyImage(index, await encoded);
265
344
  });
266
345
  }
267
346
 
268
347
  /** Sets the window image (scaled to the window size). */
269
348
  async setWindowImage(image: ImageSource, options?: ImageOptions): Promise<void> {
270
349
  const rect = this.#windowRect();
271
- const current = this.#claim(["window"]);
350
+ const current = this.#claim(this.#windowSlots);
272
351
  const rgb = await toRgb(image, rect, options);
273
352
  if (!current()) return;
274
- await this.#commit(["window"], rect, rgb, () => {
275
- const jpeg = this.#encode(rgb, rect, options?.quality);
276
- return async () => this.sendWindowJpeg(await jpeg);
353
+ await this.#commit(this.#windowSlots, rect, rgb, () => {
354
+ const encoded = this.#encode(rgb, rect, options?.quality);
355
+ return async () => this.sendWindowImage(await encoded);
356
+ });
357
+ }
358
+
359
+ /** Sets one of the windows after the first (scaled to its size). */
360
+ async setExtraWindowImage(
361
+ index: number,
362
+ image: ImageSource,
363
+ options?: ImageOptions,
364
+ ): Promise<void> {
365
+ const rect = slotRect(this.model.layout, "window", index);
366
+ if (index < 1 || !rect) throw new RangeError(`${this.model.name} has no window ${index}`);
367
+ await this.#setOwnPlace(`window:${index}`, rect, image, options);
368
+ }
369
+
370
+ /** Draws a slot that is none of the hardware's own: it goes out with the next whole frame. */
371
+ async #setOwnPlace(
372
+ slot: Slot,
373
+ rect: Rect,
374
+ image: ImageSource,
375
+ options?: ImageOptions,
376
+ ): Promise<void> {
377
+ const current = this.#claim([slot]);
378
+ const rgb = await toRgb(image, rect, options);
379
+ if (!current() || this.#unchanged([slot], rect, rgb)) return;
380
+ this.#screen.blit(rect, rgb);
381
+ this.#touch([slot]);
382
+ await this.#requestFrame(options?.quality);
383
+ }
384
+
385
+ /** Sets the part of the window that belongs to a dial (scaled to its size). */
386
+ async setDialImage(index: number, image: ImageSource, options?: ImageOptions): Promise<void> {
387
+ this.assertDial(index);
388
+ const slot: Slot = `dial:${index}`;
389
+ const rect = this.model.layout.dials?.[index] as Rect;
390
+ if (this.model.layout.separateDials) return this.#setOwnPlace(slot, rect, image, options);
391
+ const win = this.#windowRect();
392
+ const current = this.#claim([slot]);
393
+ const rgb = await toRgb(image, rect, options);
394
+ if (!current()) return;
395
+ await this.#commit([slot], rect, rgb, () => {
396
+ const encoded = this.#encode(rgb, rect, options?.quality);
397
+ const region = { ...rect, x: rect.x - win.x, y: rect.y - win.y };
398
+ return async () => this.sendWindowRegionImage(region, await encoded);
277
399
  });
278
400
  }
279
401
 
@@ -288,9 +410,9 @@ export abstract class StreamDeck {
288
410
  ): Promise<void> {
289
411
  const rect = this.#windowRegion(region);
290
412
  const rgb = await toRgb(image, rect, options);
291
- await this.#commit(["window"], rect, rgb, () => {
292
- const jpeg = this.#encode(rgb, rect, options?.quality);
293
- return async () => this.sendWindowRegionJpeg(region, await jpeg);
413
+ await this.#commit(this.#windowSlots, rect, rgb, () => {
414
+ const encoded = this.#encode(rgb, rect, options?.quality);
415
+ return async () => this.sendWindowRegionImage(region, await encoded);
294
416
  });
295
417
  }
296
418
 
@@ -320,7 +442,7 @@ export abstract class StreamDeck {
320
442
 
321
443
  /**
322
444
  * Draws keys, sensor strips and the window in a single full-screen update. Anything omitted
323
- * becomes the background colour.
445
+ * becomes the background color.
324
446
  */
325
447
  async setScreenLayout(layout: ScreenLayout, options?: ImageOptions): Promise<void> {
326
448
  const current = this.#claim(this.#allSlots);
@@ -328,7 +450,7 @@ export abstract class StreamDeck {
328
450
  if (current()) await this.#drawScreen(data, options?.quality);
329
451
  }
330
452
 
331
- /** Fills a key with a solid colour. */
453
+ /** Fills a key with a solid color. */
332
454
  fillKey(index: number, color: RGB): Promise<void> {
333
455
  this.assertKey(index);
334
456
  const slot: Slot = `key:${index}`;
@@ -342,7 +464,7 @@ export abstract class StreamDeck {
342
464
  );
343
465
  }
344
466
 
345
- /** Fills the whole LCD with a solid colour. */
467
+ /** Fills the whole LCD with a solid color. */
346
468
  fillScreen(color: RGB): Promise<void> {
347
469
  this.#claim(this.#allSlots);
348
470
  const rect = this.#screenRect;
@@ -354,30 +476,30 @@ export abstract class StreamDeck {
354
476
  );
355
477
  }
356
478
 
357
- // Low-level variants: send a JPEG that is already the exact size and device rotation. They are
358
- // not decoded, so the deck does not know these pixels: a later strip redraw replaces them with
479
+ // Low-level variants: send a JPEG that is already the exact size and device rotation (a deck of
480
+ // the older kind, such as the Mini, takes a BMP instead). They are not decoded, so the deck does not know these pixels: a later strip redraw replaces them with
359
481
  // what was last drawn there through the other methods.
360
482
 
361
483
  /** Sends a JPEG that is already key-sized (and rotated as the device needs) to a key. */
362
484
  setKeyJpeg(index: number, jpeg: Uint8Array): Promise<void> {
363
485
  this.assertKey(index);
364
- return this.#raw([`key:${index}`], () => this.sendKeyJpeg(index, jpeg));
486
+ return this.#raw([`key:${index}`], () => this.sendKeyImage(index, jpeg));
365
487
  }
366
488
 
367
489
  /** Sends a screen-sized, device-rotated JPEG to the LCD as-is. */
368
490
  setScreenJpeg(jpeg: Uint8Array): Promise<void> {
369
- return this.#raw(this.#allSlots, () => this.sendScreenJpeg(jpeg));
491
+ return this.#raw(this.#allSlots, () => this.sendScreenImage(jpeg));
370
492
  }
371
493
 
372
494
  /** Sends a window-sized, device-rotated JPEG to the window as-is. */
373
495
  setWindowJpeg(jpeg: Uint8Array): Promise<void> {
374
- return this.#raw(["window"], () => this.sendWindowJpeg(jpeg));
496
+ return this.#raw(this.#windowSlots, () => this.sendWindowImage(jpeg));
375
497
  }
376
498
 
377
499
  /** Sends a `region.width`×`region.height`, device-rotated JPEG to part of the window as-is. */
378
500
  setWindowRegionJpeg(region: Rect, jpeg: Uint8Array): Promise<void> {
379
501
  this.#windowRegion(region);
380
- return this.#raw(["window"], () => this.sendWindowRegionJpeg(region, jpeg));
502
+ return this.#raw(this.#windowSlots, () => this.sendWindowRegionImage(region, jpeg));
381
503
  }
382
504
 
383
505
  // -- Reading back ------------------------------------------------------------
@@ -399,9 +521,9 @@ export abstract class StreamDeck {
399
521
  // -- Drawing internals -------------------------------------------------------
400
522
 
401
523
  #encode(rgb: Uint8Array, size: Size, quality?: number): Promise<Uint8Array> {
402
- const jpeg = encodeJpeg(rgb, size, { quality, rotation: this.model.rotation });
403
- jpeg.catch(() => {}); // awaited inside the queue; never an unhandled rejection
404
- return jpeg;
524
+ const image = this.encodeImage(rgb, size, quality);
525
+ image.catch(() => {}); // awaited inside the queue; never an unhandled rejection
526
+ return image;
405
527
  }
406
528
 
407
529
  #windowRegion(region: Rect): Rect {
@@ -453,7 +575,7 @@ export abstract class StreamDeck {
453
575
  }
454
576
 
455
577
  /**
456
- * Waits for a queued write. Afterwards the device holds the framebuffer's pixels for every
578
+ * Waits for a queued write. Afterward the device holds the framebuffer's pixels for every
457
579
  * slot that has not changed since `gens` was taken; if it failed, they are unknown.
458
580
  */
459
581
  async #settle(write: Promise<void>, gens: Map<Slot, number>, region: Rect): Promise<void> {
@@ -516,8 +638,7 @@ export abstract class StreamDeck {
516
638
  const frame = this.#frame;
517
639
  this.#frame = undefined;
518
640
  const gens = this.#gens(this.#allSlots);
519
- const jpeg = this.#encode(this.#screen.data.slice(), this.screenSize, frame.quality);
520
- const write = this.enqueue(async () => this.sendScreenJpeg(await jpeg));
641
+ const write = this.enqueue(this.prepareFrame(this.#screen, frame.quality));
521
642
  try {
522
643
  await this.#settle(write, gens, this.#screenRect);
523
644
  for (const waiter of frame.waiters) waiter.resolve();
@@ -564,6 +685,18 @@ export abstract class StreamDeck {
564
685
  );
565
686
  }
566
687
 
688
+ /** Mounts a live element tree on the part of the window that belongs to a dial. See `mountKey`. */
689
+ mountDial(index: number, element: Renderable, options?: MountOptions): Promise<ElementRoot> {
690
+ this.assertDial(index);
691
+ return this.#mount(
692
+ "dial",
693
+ index,
694
+ (frame) => this.setDialImage(index, frame, { ...options, fit: "fill" }),
695
+ element,
696
+ options,
697
+ );
698
+ }
699
+
567
700
  /** Mounts a live element tree on the window. See `mountKey`. */
568
701
  mountWindow(element: Renderable, options?: MountOptions): Promise<ElementRoot> {
569
702
  return this.#mount(
@@ -575,6 +708,24 @@ export abstract class StreamDeck {
575
708
  );
576
709
  }
577
710
 
711
+ /** Mounts a live element tree on one of the windows after the first. See `mountKey`. */
712
+ mountExtraWindow(
713
+ index: number,
714
+ element: Renderable,
715
+ options?: MountOptions,
716
+ ): Promise<ElementRoot> {
717
+ if (index < 1 || !slotRect(this.model.layout, "window", index)) {
718
+ throw new RangeError(`${this.model.name} has no window ${index}`);
719
+ }
720
+ return this.#mount(
721
+ "window",
722
+ index,
723
+ (frame) => this.setExtraWindowImage(index, frame, { ...options, fit: "fill" }),
724
+ element,
725
+ options,
726
+ );
727
+ }
728
+
578
729
  /**
579
730
  * Mounts a live element tree on the whole screen (keys, sensor strips and window in one
580
731
  * layout). Full-screen updates are device-bound at about 26 fps, so prefer `mountKey` /
@@ -591,7 +742,7 @@ export abstract class StreamDeck {
591
742
  }
592
743
 
593
744
  async #mount(
594
- kind: "key" | "sensor" | "window" | "screen",
745
+ kind: "key" | "sensor" | "dial" | "window" | "screen",
595
746
  index: number,
596
747
  send: (frame: RawImage) => Promise<void>,
597
748
  element: Renderable,
@@ -665,6 +816,12 @@ export abstract class StreamDeck {
665
816
  }
666
817
  }
667
818
 
819
+ protected assertDial(index: number): void {
820
+ if (!Number.isInteger(index) || index < 0 || index >= this.dialCount) {
821
+ throw new RangeError(`dial index must be 0–${Math.max(0, this.dialCount - 1)}, got ${index}`);
822
+ }
823
+ }
824
+
668
825
  /** Runs `task` after every earlier write, so multi-packet uploads never interleave. */
669
826
  protected enqueue<T>(task: () => Promise<T>): Promise<T> {
670
827
  if (this.#closed) return Promise.reject(new Error(`${this.model.name} is closed`));
@@ -678,20 +835,50 @@ export abstract class StreamDeck {
678
835
  }
679
836
 
680
837
  #handleInput(data: Uint8Array): void {
681
- const states = this.parseInput(data);
682
- if (!states) return;
683
-
684
- const keys = this.keyCount;
685
- for (let i = 0; i < states.length; i++) {
686
- const pressed = states[i] === true;
687
- if (pressed === (this.#pressed[i] === true)) continue;
688
-
689
- if (i < keys) {
690
- this.emit(pressed ? "keyDown" : "keyUp", i);
691
- } else {
692
- this.emit(pressed ? "sensorDown" : "sensorUp", i - keys);
838
+ const input = this.parseInput(data);
839
+ switch (input?.type) {
840
+ case "buttons": {
841
+ const before = this.#pressed;
842
+ this.#pressed = input.pressed;
843
+ changes(before, input.pressed, (i, down) => {
844
+ if (i < this.keyCount) this.emit(down ? "keyDown" : "keyUp", i);
845
+ else this.emit(down ? "sensorDown" : "sensorUp", i - this.keyCount);
846
+ });
847
+ break;
693
848
  }
849
+ case "dials": {
850
+ const before = this.#dials;
851
+ this.#dials = input.pressed;
852
+ changes(before, input.pressed, (i, down) => this.emit(down ? "dialDown" : "dialUp", i));
853
+ break;
854
+ }
855
+ case "turn":
856
+ input.ticks.forEach((ticks, i) => {
857
+ if (ticks !== 0) this.emit("dialTurn", i, ticks);
858
+ });
859
+ break;
860
+ case "tap": {
861
+ this.emit("windowTap", input.at, input.long);
862
+ const { dials = [], window } = this.model.layout;
863
+ const x = (window?.x ?? 0) + input.at.x;
864
+ const dial = dials.findIndex((r) => x >= r.x && x < r.x + r.width);
865
+ if (dial >= 0) this.emit("dialTap", dial, input.long);
866
+ break;
867
+ }
868
+ case "swipe":
869
+ this.emit("windowSwipe", input.from, input.to);
870
+ break;
694
871
  }
695
- this.#pressed = states;
696
872
  }
697
873
  }
874
+
875
+ /** Calls `changed` for everything that was pressed or released. */
876
+ function changes(
877
+ before: readonly boolean[],
878
+ now: readonly boolean[],
879
+ changed: (index: number, down: boolean) => void,
880
+ ): void {
881
+ now.forEach((down, i) => {
882
+ if (down !== (before[i] === true)) changed(i, down);
883
+ });
884
+ }
package/src/detect.ts CHANGED
@@ -17,7 +17,7 @@ export interface HidBackend {
17
17
  HID: new (path: string) => NodeHidDevice;
18
18
  }
19
19
 
20
- /** Knows how to recognise one Stream Deck model on USB and drive it. */
20
+ /** Knows how to recognize one Stream Deck model on USB and drive it. */
21
21
  export interface DeckDriver<D extends StreamDeck = StreamDeck> {
22
22
  readonly model: Pick<DeckModel, "id" | "name" | "vendorId" | "productId">;
23
23
  create(transport: HidTransport): D;
@@ -150,9 +150,8 @@ export async function openDeck<D extends StreamDeck>(
150
150
  await sleep(Math.min(pollIntervalMs, remaining), signal);
151
151
  }
152
152
 
153
- const names = asArray(drivers)
154
- .map(({ model }) => model.name)
155
- .join(" or ");
153
+ const all = asArray(drivers).map(({ model }) => model.name);
154
+ const names = all.length > 3 ? "deck" : all.join(" or ");
156
155
  const filtered = options.path !== undefined || options.serialNumber !== undefined;
157
156
  throw new Error(`No ${names} found${filtered ? " matching the given path/serialNumber" : ""}`, {
158
157
  cause: lastError,
@@ -70,7 +70,7 @@ export class Framebuffer {
70
70
  }
71
71
  }
72
72
 
73
- /** Fills `rect` (default: everything) with one colour. */
73
+ /** Fills `rect` (default: everything) with one color. */
74
74
  fill(color: RGB, rect: Rect = { x: 0, y: 0, width: this.width, height: this.height }): void {
75
75
  this.blit(rect, solidRgb(rect, color));
76
76
  }
@@ -91,7 +91,7 @@ export class Framebuffer {
91
91
  }
92
92
  }
93
93
 
94
- /** `size` of a single colour, as RGB. */
94
+ /** `size` of a single color, as RGB. */
95
95
  export function solidRgb(size: Size, [r, g, b]: RGB): Uint8Array {
96
96
  const out = new Uint8Array(size.width * size.height * 3);
97
97
  for (let i = 0; i < out.length; i += 3) {
@@ -102,7 +102,7 @@ export function solidRgb(size: Size, [r, g, b]: RGB): Uint8Array {
102
102
  return out;
103
103
  }
104
104
 
105
- /** Parses `#rgb` / `#rrggbb`; `undefined` for anything else (named colours, `rgb()`, ...). */
105
+ /** Parses `#rgb` / `#rrggbb`; `undefined` for anything else (named colors, `rgb()`, ...). */
106
106
  export function parseHexColor(color: string): RGB | undefined {
107
107
  const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())?.[1];
108
108
  if (!hex) return undefined;
package/src/image.ts CHANGED
@@ -24,7 +24,7 @@ export interface ImageOptions {
24
24
  * `cover` fills and crops, `contain` letterboxes, `fill` stretches.
25
25
  */
26
26
  fit?: "cover" | "contain" | "fill";
27
- /** Colour used for letterboxing and for flattening transparency (default black). */
27
+ /** Color used for letterboxing and for flattening transparency (default black). */
28
28
  background?: string;
29
29
  /** JPEG quality, 1–100 (default 90). */
30
30
  quality?: number;
@@ -69,9 +69,12 @@ export async function prepareImage(
69
69
  .flatten({ background });
70
70
  }
71
71
 
72
+ /** Degrees clockwise. */
73
+ export type Rotation = 0 | 90 | 180 | 270;
74
+
72
75
  export interface DeviceImageOptions extends ImageOptions {
73
- /** Rotation the device expects (default 0). The Stream Deck Neo needs 180. */
74
- rotation?: 0 | 180;
76
+ /** Rotation the device expects (default 0). Most Stream Decks need 180. */
77
+ rotation?: Rotation;
75
78
  }
76
79
 
77
80
  /**
@@ -89,7 +92,7 @@ export async function toDeviceJpeg(
89
92
  /**
90
93
  * Converts an image to upright RGB pixels of exactly `size` (`width * height * 3` bytes).
91
94
  * Exact-size raw pixels, such as rendered elements, skip sharp entirely; RGBA is flattened onto
92
- * `background` in JS when it is a hex colour.
95
+ * `background` in JS when it is a hex color.
93
96
  */
94
97
  export async function toRgb(
95
98
  source: ImageSource,
@@ -125,7 +128,7 @@ export async function encodeJpeg(
125
128
  ): Promise<Uint8Array> {
126
129
  const { quality = 90, rotation = 0 } = options;
127
130
  let pipeline = sharp(rgb, { raw: { width: size.width, height: size.height, channels: 3 } });
128
- if (rotation === 180) pipeline = pipeline.rotate(180);
131
+ if (rotation !== 0) pipeline = pipeline.rotate(rotation);
129
132
  const jpeg = await pipeline
130
133
  .jpeg({ quality, progressive: false, chromaSubsampling: "4:4:4" })
131
134
  .toBuffer();