Module: Plushie::Protocol::Decode

Defined in:
lib/plushie/protocol/decode.rb

Overview

Inbound message decoding from the wire protocol.

Handles all response types and event families as defined in the wire protocol (~/projects/plushie-rust/docs/protocol.md).

Class Method Summary collapse

Class Method Details

.atomize_data(data) ⇒ Hash?

Convert string-keyed wire data to symbol-keyed hash.

Parameters:

  • data (Hash, nil)

Returns:

  • (Hash, nil)


1007
1008
1009
1010
1011
# File 'lib/plushie/protocol/decode.rb', line 1007

def atomize_data(data)
  return nil unless data.is_a?(Hash)

  data.transform_keys(&:to_sym)
end

.decode(data, format = :msgpack) ⇒ Hash

Deserialize raw wire bytes into a Ruby hash.

Parameters:

  • data (String)

    raw wire bytes

  • format (:msgpack, :json) (defaults to: :msgpack)

Returns:

  • (Hash)


19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/plushie/protocol/decode.rb', line 19

def decode(data, format = :msgpack)
  case format
  when :json
    JSON.parse(data)
  when :msgpack
    require "msgpack"
    MessagePack.unpack(data)
  else
    raise ArgumentError, "unsupported protocol format: #{format.inspect}"
  end
rescue JSON::ParserError, MessagePack::MalformedFormatError,
  MessagePack::UnpackError, MessagePack::TypeError => e
  {"error" => e.message}
rescue ArgumentError => e
  # msgpack gem raises ArgumentError for some malformed inputs
  {"error" => e.message}
end

.decode_diagnostic(msg) ⇒ Event::DiagnosticMessage

Decode a top-level diagnostic message.

Wire shape: "diagnostic":{"kind":"...", ...variant fields}

Returns a typed Event::DiagnosticMessage carrying one of the variants declared in Plushie::Event::Diagnostic.

Parameters:

  • msg (Hash)

Returns:



87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/plushie/protocol/decode.rb', line 87

def decode_diagnostic(msg)
  diag = msg["diagnostic"] || {}
  level_str = msg["level"] || "warn"
  level = case level_str
  when "info", "warn", "error" then level_str.to_sym
  else :warn
  end

  Event::DiagnosticMessage.new(
    session: msg["session"].to_s,
    level: level,
    diagnostic: Event::Diagnostic.decode(diag)
  )
end

.decode_effect_response(msg) ⇒ Hash

Decode an effect response (file dialog result, clipboard, etc.). Uses the status field per protocol.md: "ok", "cancelled", "error".

Returns a hash with the wire ID, the raw wire status, and the decoded payload (ok result or error reason). The runtime resolves the tag and effect kind from its pending-effects map and calls Event::Effect::Result.decode to build the typed outcome before delivering to the app.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :wire_id, :status, :payload



775
776
777
778
779
780
781
782
783
784
785
# File 'lib/plushie/protocol/decode.rb', line 775

def decode_effect_response(msg)
  status = msg["status"]
  payload = case status
  when "ok" then msg["result"]
  when "error" then msg["error"]
  when "cancelled", "unsupported" then nil
  else
    raise ArgumentError, "unknown effect_response status: #{status.inspect}"
  end
  {type: :effect_response, wire_id: msg["id"], status: status, payload: payload}
end

.decode_event(msg, require_window_id: true) ⇒ Event::*?

Decode an event message into the appropriate Event struct.

Events from the main protocol stream always include window_id. Events embedded in interact_response/interact_step may omit it (the mock renderer doesn't always include it). Pass +require_window_id: false+ when decoding embedded events.

Parameters:

  • msg (Hash)

    deserialized event message

  • require_window_id (Boolean) (defaults to: true)

    raise on missing window_id (default: true)

Returns:



116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/plushie/protocol/decode.rb', line 116

def decode_event(msg, require_window_id: true)
  event = decode_event_inner(msg, require_window_id: require_window_id)

  # Append window_id to scope for widget events that came from a
  # scoped widget ID. Subscription pointer events (id = window_id,
  # scope = []) should NOT get window_id appended since they're
  # global events, not scoped to a widget path.
  if event.is_a?(Event::Widget) && event.window_id &&
      !(event.scope.empty? && (event.id == event.window_id || event.id == "__global__")) && !event.scope.include?(event.window_id)
    event = event.with(scope: event.scope + [event.window_id])
  end

  event
end

.decode_event_inner(msg, require_window_id: true) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Dispatch a wire event message to the matching Event struct.



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
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
# File 'lib/plushie/protocol/decode.rb', line 133

def decode_event_inner(msg, require_window_id: true)
  family = msg["family"]
  # The renderer uses "value" as the canonical event data field.
  # For structured payloads (pointer coords, key data, etc.), value
  # is a Hash. For scalar payloads (input text, slider position),
  # value is a string/number. We extract the Hash form into `data`
  # for field access, and keep `wire_value` for the raw value.
  # Fall back to "data" for renderer versions that haven't adopted
  # the "value" field name yet. Use key? check to avoid false/nil
  # conflation (false is a valid event value for toggles).
  wire_value = msg.key?("value") ? msg["value"] : msg["data"]
  # @type var data: Hash[String, untyped]
  data = wire_value.is_a?(Hash) ? wire_value : {}
  window_id_fn = require_window_id ? method(:require_window_id!) : method(:optional_window_id)

  case family

  # -- Widget events -> Event::Widget -----------------------------------

  when "click", "input", "submit", "toggle", "select",
    "slide", "slide_release", "paste", "option_hovered",
    "open", "close", "key_binding"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: family.to_sym, id: id,
      value: wire_value, window_id: window_id_fn.call(msg, family),
      scope: scope
    )

  when "link_click"
    id, scope = split_scoped_id(msg["id"])
    link = data["link"].is_a?(String) ? data["link"] : ""
    Event::Widget.new(
      type: :link_click, id: id,
      value: link, window_id: window_id_fn.call(msg, family),
      scope: scope
    )

  when "sort"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :sort, id: id, window_id: window_id_fn.call(msg, family),
      scope: scope, value: {column: data["column"]}
    )

  when "scrolled"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :scrolled, id: id, window_id: window_id_fn.call(msg, family),
      scope: scope, value: {
        absolute_x: data["absolute_x"], absolute_y: data["absolute_y"],
        relative_x: data["relative_x"], relative_y: data["relative_y"],
        bounds: {width: data["bounds_width"], height: data["bounds_height"]},
        content_bounds: {width: data["content_width"], height: data["content_height"]}
      }
    )

  # -- Unified pointer events -> Event::Widget ----------------------------

  when "press"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :press, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        button: Parsers.parse_mouse_button(data["button"] || "left"),
        pointer: (data["pointer"] || "mouse").to_sym,
        finger: data["finger"],
        modifiers: parse_modifiers(data["modifiers"]),
        captured: data["captured"] || msg["captured"] || false
      }
    )

  when "release"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :release, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        button: Parsers.parse_mouse_button(data["button"] || "left"),
        pointer: (data["pointer"] || "mouse").to_sym,
        finger: data["finger"],
        modifiers: parse_modifiers(data["modifiers"]),
        captured: data["captured"] || msg["captured"] || false,
        lost: data["lost"]
      }
    )

  when "move"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :move, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        pointer: (data["pointer"] || "mouse").to_sym,
        finger: data["finger"],
        modifiers: parse_modifiers(data["modifiers"]),
        captured: data["captured"] || msg["captured"] || false
      }
    )

  when "scroll"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :scroll, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        delta_x: data["delta_x"], delta_y: data["delta_y"],
        unit: data["unit"] ? Parsers.parse_scroll_unit(data["unit"]) : nil,
        pointer: (data["pointer"] || "mouse").to_sym,
        modifiers: parse_modifiers(data["modifiers"]),
        captured: data["captured"] || msg["captured"] || false
      }
    )

  when "enter"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :enter, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        captured: data["captured"] || msg["captured"] || false
      }
    )

  when "exit"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :exit, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        captured: data["captured"] || msg["captured"] || false
      }
    )

  when "double_click"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :double_click, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        x: data["x"], y: data["y"],
        pointer: (data["pointer"] || "mouse").to_sym,
        modifiers: parse_modifiers(data["modifiers"])
      }
    )

  when "resize"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :resize, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {width: data["width"], height: data["height"]}
    )

  # -- Generic element events -> Event::Widget ----------------------------

  when "focused"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :focused, id: id, window_id: window_id_fn.call(msg, family), scope: scope
    )

  when "blurred"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :blurred, id: id, window_id: window_id_fn.call(msg, family), scope: scope
    )

  when "status"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :status, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: wire_value
    )

  when "drag"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :drag, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {x: data["x"], y: data["y"], delta_x: data["delta_x"], delta_y: data["delta_y"]}
    )

  when "drag_end"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :drag_end, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: atomize_data(data)
    )

  # -- Pane events -> Event::Widget --------------------------------------

  when "pane_resized"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :pane_resized, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {split: data["split"], ratio: data["ratio"]}
    )

  when "pane_dragged"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :pane_dragged, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {
        pane: data["pane"], target: data["target"],
        action: Parsers.parse_pane_action(data["action"]),
        region: Parsers.parse_pane_region(data["region"]),
        edge: Parsers.parse_pane_region(data["edge"])
      }
    )

  when "pane_clicked"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :pane_clicked, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {pane: data["pane"]}
    )

  when "pane_focus_cycle"
    id, scope = split_scoped_id(msg["id"])
    Event::Widget.new(
      type: :pane_focus_cycle, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
      value: {pane: data["pane"]}
    )

  # -- Animation events -> Event::Widget ----------------------------------

  when "transition_complete"
    id, scope = split_scoped_id(msg["id"])
    tag = data["tag"]&.to_sym
    Event::Widget.new(
      type: :transition_complete, id: id,
      window_id: window_id_fn.call(msg, family),
      scope: scope, value: {tag: tag, prop: data["prop"]}
    )

  # -- Keyboard events -----------------------------------------------------

  when "key_press"
    if msg["id"] && !msg["id"].empty?
      id, scope = split_scoped_id(msg["id"])
      Event::Widget.new(
        type: :key_press, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
        value: {
          key: Keys.parse_key(data["key"]),
          modified_key: Keys.parse_key(data["modified_key"]),
          physical_key: Keys.parse_physical_key(data["physical_key"]),
          location: Keys.parse_location(data["location"]),
          modifiers: parse_modifiers(data["modifiers"]),
          text: data["text"],
          repeat: data["repeat"] || false
        }
      )
    else
      # Subscription form: the renderer writes the structured key
      # payload (key, modified_key, physical_key, location, text,
      # repeat) under `value`, with `modifiers` and `captured` as
      # top-level envelope siblings.
      Event::Key.new(
        type: :press,
        key: Keys.parse_key(data["key"]),
        modified_key: Keys.parse_key(data["modified_key"] || data["key"]),
        physical_key: Keys.parse_physical_key(data["physical_key"]),
        location: Keys.parse_location(data["location"]),
        modifiers: parse_modifiers(msg["modifiers"]),
        text: data["text"],
        repeat: data["repeat"] || false,
        captured: msg["captured"] || false,
        window_id: msg["window_id"]
      )
    end

  when "key_release"
    if msg["id"] && !msg["id"].empty?
      id, scope = split_scoped_id(msg["id"])
      Event::Widget.new(
        type: :key_release, id: id, window_id: window_id_fn.call(msg, family), scope: scope,
        value: {
          key: Keys.parse_key(data["key"]),
          modified_key: Keys.parse_key(data["modified_key"]),
          physical_key: Keys.parse_physical_key(data["physical_key"]),
          location: Keys.parse_location(data["location"]),
          modifiers: parse_modifiers(data["modifiers"])
        }
      )
    else
      # Subscription form: see key_press above for the wire shape.
      Event::Key.new(
        type: :release,
        key: Keys.parse_key(data["key"]),
        modified_key: Keys.parse_key(data["modified_key"] || data["key"]),
        physical_key: Keys.parse_physical_key(data["physical_key"]),
        location: Keys.parse_location(data["location"]),
        modifiers: parse_modifiers(msg["modifiers"]),
        text: nil,
        repeat: false,
        captured: msg["captured"] || false,
        window_id: msg["window_id"]
      )
    end

  # -- Modifier events -> Event::Modifiers ------------------------------

  when "modifiers_changed"
    Event::Modifiers.new(
      modifiers: parse_modifiers(msg["modifiers"] || data["modifiers"] || {}),
      captured: msg["captured"] || false,
      window_id: msg["window_id"]
    )

  # -- Subscription pointer events -> Event::Widget ----------------------

  when "cursor_moved"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :move,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        x: data["x"], y: data["y"],
        pointer: :mouse,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "cursor_entered"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :enter,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {captured: msg["captured"] || false}
    )

  when "cursor_left"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :exit,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {captured: msg["captured"] || false}
    )

  when "button_pressed"
    window_id = msg["window_id"]
    btn_value = wire_value.is_a?(String) ? wire_value : data["button"]
    Event::Widget.new(
      type: :press,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        button: Parsers.parse_mouse_button(btn_value),
        pointer: :mouse, x: nil, y: nil,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "button_released"
    window_id = msg["window_id"]
    btn_value = wire_value.is_a?(String) ? wire_value : data["button"]
    Event::Widget.new(
      type: :release,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        button: Parsers.parse_mouse_button(btn_value),
        pointer: :mouse, x: nil, y: nil,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "wheel_scrolled"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :scroll,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        delta_x: data["delta_x"], delta_y: data["delta_y"],
        unit: Parsers.parse_scroll_unit(data["unit"]),
        pointer: :mouse,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  # -- Touch subscription events -> Event::Widget ----------------------

  when "finger_pressed"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :press,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        pointer: :touch, finger: data["id"],
        x: data["x"], y: data["y"], button: :left,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "finger_moved"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :move,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        pointer: :touch, finger: data["id"],
        x: data["x"], y: data["y"],
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "finger_lifted"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :release,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        pointer: :touch, finger: data["id"],
        x: data["x"], y: data["y"], lost: false,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  when "finger_lost"
    window_id = msg["window_id"]
    Event::Widget.new(
      type: :release,
      id: window_id || "__global__", scope: [], window_id: window_id,
      value: {
        pointer: :touch, finger: data["id"],
        x: data["x"], y: data["y"], lost: true,
        captured: msg["captured"] || false,
        modifiers: parse_modifiers(msg["modifiers"])
      }
    )

  # -- IME events -> Event::Ime -----------------------------------------

  when "ime_opened"
    id, scope = split_scoped_id(msg["id"])
    Event::Ime.new(type: :opened, id: id, scope: scope,
      captured: msg["captured"] || false, window_id: msg["window_id"])

  when "ime_preedit"
    # Renderer writes {"text": string, "cursor": {start,end}|null}
    # to value. A missing or non-Hash value is a wire-shape bug, not
    # a user-input bug; raise so it surfaces instead of producing
    # an Event::Ime with nil text and cursor.
    require_hash_value!(wire_value, family)
    id, scope = split_scoped_id(msg["id"])
    Event::Ime.new(
      type: :preedit, id: id, scope: scope,
      text: wire_value["text"],
      cursor: parse_ime_cursor(wire_value["cursor"]),
      captured: msg["captured"] || false,
      window_id: msg["window_id"]
    )

  when "ime_commit"
    # Renderer writes {"text": string} to value. Missing or
    # non-Hash value is a wire-shape bug; see ime_preedit above.
    require_hash_value!(wire_value, family)
    id, scope = split_scoped_id(msg["id"])
    Event::Ime.new(
      type: :commit, id: id, scope: scope,
      text: wire_value["text"],
      captured: msg["captured"] || false,
      window_id: msg["window_id"]
    )

  when "ime_closed"
    id, scope = split_scoped_id(msg["id"])
    Event::Ime.new(type: :closed, id: id, scope: scope,
      captured: msg["captured"] || false, window_id: msg["window_id"])

  # -- Window subscription events -> Event::Window ----------------------

  when "window_opened"
    Event::Window.new(
      type: :opened, window_id: data["window_id"],
      x: data["x"], y: data["y"],
      width: data["width"], height: data["height"],
      scale_factor: data["scale_factor"]
    )

  when "window_closed"
    Event::Window.new(type: :closed, window_id: data["window_id"])

  when "window_close_requested"
    Event::Window.new(type: :close_requested, window_id: data["window_id"])

  when "window_moved"
    Event::Window.new(
      type: :moved, window_id: data["window_id"],
      x: data["x"], y: data["y"]
    )

  when "window_resized"
    Event::Window.new(
      type: :resized, window_id: data["window_id"],
      width: data["width"], height: data["height"]
    )

  when "window_focused"
    Event::Window.new(type: :focused, window_id: data["window_id"])

  when "window_unfocused"
    Event::Window.new(type: :unfocused, window_id: data["window_id"])

  when "window_rescaled"
    Event::Window.new(
      type: :rescaled, window_id: data["window_id"],
      scale_factor: data["scale_factor"]
    )

  when "file_hovered"
    Event::Window.new(
      type: :file_hovered, window_id: data["window_id"],
      path: data["path"]
    )

  when "file_dropped"
    Event::Window.new(
      type: :file_dropped, window_id: data["window_id"],
      path: data["path"]
    )

  when "files_hovered_left"
    Event::Window.new(type: :files_hovered_left, window_id: data["window_id"])

  # -- System events -> Event::System -----------------------------------

  when "animation_frame"
    # Renderer writes {"timestamp": u64} to value.
    Event::System.new(type: :animation_frame, value: data["timestamp"])

  when "theme_changed"
    # Renderer writes the mode name as a scalar string in value.
    Event::System.new(type: :theme_changed, value: wire_value)

  when "all_windows_closed"
    Event::System.new(type: :all_windows_closed)

  when "error"
    error_kind = data.is_a?(Hash) ? data["kind"] : nil
    if error_kind == "command" || msg["id"] == "command" || msg["id"] == "extension_command"
      Event::CommandError.new(
        reason: data["reason"] || "",
        id: data["id"] || data["node_id"],
        family: data["family"] || data["op"],
        widget_type: data["widget_type"] || data["extension"],
        message: data["message"]
      )
    else
      error_data =
        if data.is_a?(Hash)
          data.merge("id" => msg["id"])
        else
          {"id" => msg["id"], "details" => data}
        end
      Event::System.new(type: :error, value: error_data)
    end

  when "announce"
    Event::System.new(type: :announce, value: data["text"])

  when "session_error"
    Event::SessionError.new(
      session: msg["session"].to_s,
      code: data["code"].is_a?(String) ? data["code"] : "",
      error: data["error"].is_a?(String) ? data["error"] : ""
    )

  when "session_closed"
    Event::SessionClosed.new(
      session: msg["session"].to_s,
      reason: data["reason"].is_a?(String) ? data["reason"] : ""
    )

  # -- Diagnostic events -> Event::System ---------------------------------

  when "diagnostic"
    Event::System.new(type: :diagnostic, value: data)

  # -- Fallback: unknown events -> Event::Widget --------------------------

  else
    if msg["id"]
      id, scope = split_scoped_id(msg["id"])
      # Renderer-internal events (e.g. prop_validation in debug
      # builds) may omit window_id, so unknown families always use
      # the optional lookup rather than raising.
      Event::Widget.new(
        type: family&.to_sym, id: id,
        value: wire_value, window_id: optional_window_id(msg, family),
        scope: scope
      )
    end
  end
end

.decode_hello(msg) ⇒ Hash

Decode the hello handshake message.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :protocol, :version, :name, :mode, :backend, :transport, :native_widgets, :widgets



741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
# File 'lib/plushie/protocol/decode.rb', line 741

def decode_hello(msg)
  required = %w[protocol version]
  missing = required.reject { |k| msg.key?(k) && !msg[k].nil? }
  unless missing.empty?
    raise Plushie::Error,
      "hello message missing required fields: #{missing.join(", ")}. Got: #{msg.keys.sort.join(", ")}"
  end

  {
    type: :hello,
    session: msg["session"],
    protocol: msg["protocol"],
    version: msg["version"],
    name: msg["name"],
    mode: msg["mode"],
    backend: msg["backend"],
    transport: msg["transport"],
    native_widgets: msg["native_widgets"] || [],
    widgets: msg["widgets"] || [],
    widget_sets: msg["widget_sets"] || []
  }
end

.decode_interact_response(msg) ⇒ Hash

Decode an interact response (final response after all steps). Embedded events are decoded recursively.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :session, :events



820
821
822
823
824
825
826
827
828
# File 'lib/plushie/protocol/decode.rb', line 820

def decode_interact_response(msg)
  events = (msg["events"] || []).filter_map { |e| decode_event(e, require_window_id: false) }
  {
    type: :interact_response,
    id: msg["id"],
    session: msg["session"],
    events: events
  }
end

.decode_interact_step(msg) ⇒ Hash

Decode an interact step (intermediate events from headless mode). Embedded events are decoded recursively.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :session, :events



835
836
837
838
839
840
841
842
843
# File 'lib/plushie/protocol/decode.rb', line 835

def decode_interact_step(msg)
  events = (msg["events"] || []).filter_map { |e| decode_event(e, require_window_id: false) }
  {
    type: :interact_step,
    id: msg["id"],
    session: msg["session"],
    events: events
  }
end

.decode_message(data, format = :msgpack) ⇒ Event::*, ...

Decode a wire message into a typed Ruby struct or hash.

Dispatches on the "type" field to the appropriate decoder. Returns nil for decode errors.

Parameters:

  • data (String)

    raw wire bytes

  • format (:msgpack, :json) (defaults to: :msgpack)

Returns:



45
46
47
48
49
50
51
# File 'lib/plushie/protocol/decode.rb', line 45

def decode_message(data, format = :msgpack)
  msg = decode(data, format)
  return nil if msg.key?("error")

  result = dispatch_message(msg)
  normalize_binary_fields(result, format)
end

.decode_op_query_response(msg) ⇒ Hash

Decode an op query response (tree_hash, find_focused, system_theme, etc.).

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :kind, :tag, :data



805
806
807
808
809
810
811
812
813
# File 'lib/plushie/protocol/decode.rb', line 805

def decode_op_query_response(msg)
  {
    type: :op_query_response,
    session: msg["session"],
    kind: msg["kind"]&.to_sym,
    tag: msg["tag"],
    data: msg["data"]
  }
end

.decode_query_response(msg) ⇒ Hash

Decode a query response (find, tree).

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :target, :data



791
792
793
794
795
796
797
798
799
# File 'lib/plushie/protocol/decode.rb', line 791

def decode_query_response(msg)
  {
    type: :query_response,
    session: msg["session"],
    id: msg["id"],
    target: msg["target"],
    data: msg["data"]
  }
end

.decode_reset_response(msg) ⇒ Hash

Decode a reset response.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :status



880
881
882
883
884
885
886
887
# File 'lib/plushie/protocol/decode.rb', line 880

def decode_reset_response(msg)
  {
    type: :reset_response,
    session: msg["session"],
    id: msg["id"],
    status: msg["status"]
  }
end

.decode_screenshot_response(msg) ⇒ Hash

Decode a screenshot response.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :name, :hash, :width, :height, :rgba



863
864
865
866
867
868
869
870
871
872
873
874
# File 'lib/plushie/protocol/decode.rb', line 863

def decode_screenshot_response(msg)
  {
    type: :screenshot_response,
    session: msg["session"],
    id: msg["id"],
    name: msg["name"],
    hash: msg["hash"],
    width: msg["width"],
    height: msg["height"],
    rgba: msg["rgba"]
  }
end

.decode_tree_hash_response(msg) ⇒ Hash

Decode a tree hash response.

Parameters:

  • msg (Hash)

Returns:

  • (Hash)

    with :type, :id, :name, :hash



849
850
851
852
853
854
855
856
857
# File 'lib/plushie/protocol/decode.rb', line 849

def decode_tree_hash_response(msg)
  {
    type: :tree_hash_response,
    session: msg["session"],
    id: msg["id"],
    name: msg["name"],
    hash: msg["hash"]
  }
end

.dispatch_message(msg) ⇒ Event::*, ...

Dispatch an already-deserialized message hash.

Parameters:

  • msg (Hash)

    deserialized message with string keys

Returns:



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/plushie/protocol/decode.rb', line 57

def dispatch_message(msg)
  case msg["type"]
  when "event" then decode_event(msg)
  when "hello" then decode_hello(msg)
  when "diagnostic" then decode_diagnostic(msg)
  when "effect_response" then decode_effect_response(msg)
  when "query_response" then decode_query_response(msg)
  when "op_query_response" then decode_op_query_response(msg)
  when "interact_response" then decode_interact_response(msg)
  when "interact_step" then decode_interact_step(msg)
  when "tree_hash_response" then decode_tree_hash_response(msg)
  when "screenshot_response" then decode_screenshot_response(msg)
  when "reset_response" then decode_reset_response(msg)
  when "effect_stub_register_ack", "effect_stub_unregister_ack"
    {type: :effect_stub_ack, kind: msg["kind"]}
  else msg
  end
end

.normalize_binary_fields(message, format) ⇒ Object

Normalize format-specific binary representations so consumers don't need to know the wire format. JSON encodes raw bytes as base64 strings; this decodes them back to raw binaries after dispatch.



1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
# File 'lib/plushie/protocol/decode.rb', line 1040

def normalize_binary_fields(message, format)
  return message unless format == :json && message.is_a?(Hash)

  if message[:type] == :screenshot_response && message[:rgba].is_a?(String)
    require "base64"
    decoded = Base64.decode64(message[:rgba])
    message.merge(rgba: decoded)
  else
    message
  end
end

.optional_window_id(msg, _family) ⇒ String?

Lenient window_id extraction for events embedded in interact responses where the mock renderer may omit window_id.

Parameters:

  • msg (Hash)
  • _family (String)

Returns:

  • (String, nil)


971
972
973
974
# File 'lib/plushie/protocol/decode.rb', line 971

def optional_window_id(msg, _family)
  window_id = msg["window_id"]
  (window_id.is_a?(String) && !window_id.empty?) ? window_id : nil
end

.parse_canvas_button(button) ⇒ Symbol

Parse a canvas button string to a symbol.

Parameters:

  • button (String, nil)

Returns:

  • (Symbol)


995
996
997
998
999
1000
1001
1002
# File 'lib/plushie/protocol/decode.rb', line 995

def parse_canvas_button(button)
  case button
  when "left", nil then :left
  when "right" then :right
  when "middle" then :middle
  else button.to_sym
  end
end

.parse_canvas_key_data(data, type) ⇒ Hash

Parse canvas element key event data with proper key and modifier types.

Parameters:

  • data (Hash)

    raw wire data

  • type (:press, :release)

Returns:

  • (Hash)

    parsed data with symbol keys



1017
1018
1019
1020
1021
1022
1023
1024
# File 'lib/plushie/protocol/decode.rb', line 1017

def parse_canvas_key_data(data, type)
  {
    type: type,
    element_id: data["element_id"],
    key: Keys.parse_key(data["key"]),
    modifiers: parse_modifiers(data["modifiers"])
  }
end

.parse_ime_cursor(cursor) ⇒ Array(Integer, Integer)?

Parse an IME cursor position from the wire format.

Parameters:

  • cursor (Hash, Array, nil)

    cursor data from the renderer

Returns:

  • (Array(Integer, Integer), nil)

    [start, end] or nil



1029
1030
1031
1032
1033
1034
# File 'lib/plushie/protocol/decode.rb', line 1029

def parse_ime_cursor(cursor)
  case cursor
  when Hash then [cursor["start"], cursor["end"]]
  when Array then [cursor[0], cursor[1]] if cursor.length == 2
  end
end

.parse_modifiers(mods) ⇒ Hash

Parse a modifiers hash from the wire format.

Parameters:

  • mods (Hash)

    wire modifiers (string keys)

Returns:

  • (Hash)

    frozen hash with symbol keys



980
981
982
983
984
985
986
987
988
989
990
# File 'lib/plushie/protocol/decode.rb', line 980

def parse_modifiers(mods)
  return {shift: false, ctrl: false, alt: false, logo: false, command: false}.freeze if mods.nil? || mods.empty?

  {
    shift: mods["shift"] || false,
    ctrl: mods["ctrl"] || false,
    alt: mods["alt"] || false,
    logo: mods["logo"] || false,
    command: mods["command"] || false
  }.freeze
end

.require_hash_value!(value, family) ⇒ Object

Raise unless +value+ is a Hash. Used by event families whose renderer wire shape always carries a structured payload in value; a non-Hash here means the wire shape changed without the decoder catching up, and silently producing an Event with nil fields hides the regression.

Raises:

  • (ArgumentError)


958
959
960
961
962
963
# File 'lib/plushie/protocol/decode.rb', line 958

def require_hash_value!(value, family)
  return if value.is_a?(Hash)

  raise ArgumentError,
    "event family #{family.inspect} expected Hash value, got #{value.class}"
end

.require_window_id!(msg, family) ⇒ Object

Raises:

  • (ArgumentError)


946
947
948
949
950
951
# File 'lib/plushie/protocol/decode.rb', line 946

def require_window_id!(msg, family)
  window_id = msg["window_id"]
  return window_id if window_id.is_a?(String) && !window_id.empty?

  raise ArgumentError, "event family #{family.inspect} is missing required window_id"
end

.split_scoped_id(full_id) ⇒ Array(String, Array<String>)

Split a scoped wire ID into local ID and scope array.

Handles the canonical "window#scope/path/id" format: "main#form/save" -> id: "save", scope: ["form", "main"] "main#save" -> id: "save", scope: ["main"] "save" -> id: "save", scope: []

The window portion (before #) is extracted and placed at the end of the reversed scope array (outermost ancestor). Falls back to the separate window_id field for compatibility.

Parameters:

  • full_id (String, nil)

Returns:

  • (Array(String, Array<String>))


906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
# File 'lib/plushie/protocol/decode.rb', line 906

def split_scoped_id(full_id)
  return [full_id.to_s, []] if full_id.nil?

  # Split window from path on #
  window, path = if full_id.include?("#")
    parts = full_id.split("#", 2)
    (parts[0] && !parts[0].empty?) ? parts : [nil, full_id]
  else
    [nil, full_id]
  end

  # Split path into scope chain
  if path.include?("/")
    parts = path.split("/")
    local = parts.pop.to_s
    scope = parts.reverse
  else
    local = path
    # @type var scope: Array[String]
    scope = []
  end

  # Append window to scope if extracted from the ID
  scope << window if window && !window.empty?

  [local, scope]
end

.split_scoped_id_with_window(full_id, window_id) ⇒ Array(String, Array<String>)

Split scoped ID and append window_id to the scope chain (outermost ancestor, at the end of the reversed list).

Parameters:

  • full_id (String, nil)
  • window_id (String, nil)

Returns:

  • (Array(String, Array<String>))


940
941
942
943
944
# File 'lib/plushie/protocol/decode.rb', line 940

def split_scoped_id_with_window(full_id, window_id)
  id, scope = split_scoped_id(full_id)
  scope += [window_id] if window_id && !window_id.empty?
  [id, scope]
end