Class: Tuile::Screen

Inherits:
Object
  • Object
show all
Defined in:
lib/tuile/screen.rb

Overview

The TTY screen. There is exactly one screen per app.

A screen runs the event loop; call #run_event_loop to do that.

A screen holds the screen lock; any UI modifications must be called from the event queue.

All UI lives under a single ScreenPane owned by the screen. Set tiled content via #content=; the pane fills the entire terminal and is responsible for laying out its children.

Modal popups are supported too, via Component::Popup#open. They auto-size to their wrapped content and are drawn centered over the tiled content.

The drawing procedure is very simple: when a window needs repaint, it invalidates itself, but won’t draw immediately. After the keyboard press event processing is done in the event loop, #repaint is called which then repaints all invalidated windows. This prevents repeated paintings.

Direct Known Subclasses

FakeScreen

Constant Summary collapse

@@instance =

Class variable (not class instance var) so the singleton survives subclassing — ‘FakeScreen < Screen` and `Screen.instance` see the same slot.

nil

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeScreen

rubocop:disable Style/ClassVars



28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/tuile/screen.rb', line 28

def initialize
  @@instance = self # rubocop:disable Style/ClassVars
  @event_queue = EventQueue.new
  @size = EventQueue::TTYSizeEvent.create.size
  @invalidated = Set.new
  # Components being repainted right now. A component may invalidate its
  # children during its repaint phase; this prevents double-draw.
  @repainting = Set.new
  # Until the event loop is run, we pretend we're in the UI thread.
  @pretend_ui_lock = true
  @scheme = detect_scheme
  @theme_def = ThemeDef.default
  @theme = @theme_def.for(@scheme)
  # Structural root of the component tree: holds tiled content, popup
  # stack and status bar.
  @pane = ScreenPane.new
  @on_error = ->(e) { raise e }
  # App-level keyboard shortcuts dispatched by {#handle_key} before keys
  # reach the pane. See {#register_global_shortcut}.
  @global_shortcuts = {}
end

Instance Attribute Details

#event_queueEventQueue (readonly)

Returns the event queue.

Returns:



164
165
166
# File 'lib/tuile/screen.rb', line 164

def event_queue
  @event_queue
end

#focusedComponent?

Returns currently focused component.

Returns:

  • (Component, nil)

    currently focused component.



195
196
197
# File 'lib/tuile/screen.rb', line 195

def focused
  @focused
end

#on_errorProc

Handler invoked when a StandardError escapes an event handler inside the event loop (e.g. a Component::TextField‘s `on_change` raises).

The default re-raises, so the exception propagates out of #run_event_loop and crashes the script with a stacktrace — unhandled exceptions are bugs and should be surfaced loudly.

Replace it when the host has somewhere visible to put errors, e.g. a Component::LogWindow wired to Tuile.logger:

screen.on_error = lambda do |e|
  Tuile.logger.error("#{e.class}: #{e.message}\n#{e.backtrace&.join("\n")}")
end

The handler runs on the event-loop thread with the UI lock held. Returning normally keeps the loop alive; raising from within the handler tears the loop down and propagates out of #run_event_loop.

Returns:

  • (Proc)

    one-arg callable receiving the StandardError instance.



77
78
79
# File 'lib/tuile/screen.rb', line 77

def on_error
  @on_error
end

#paneScreenPane (readonly)

Returns the structural root of the component tree.

Returns:

  • (ScreenPane)

    the structural root of the component tree.



57
58
59
# File 'lib/tuile/screen.rb', line 57

def pane
  @pane
end

#sizeSize (readonly)

Returns current screen size.

Returns:

  • (Size)

    current screen size.



97
98
99
# File 'lib/tuile/screen.rb', line 97

def size
  @size
end

#themeTheme

The color Theme built-in components read at paint time: the member of #theme_def matching the terminal background detected at construction (see TerminalBackground.detect; inconclusive means dark). While the event loop runs, terminals supporting mode 2031 push OS appearance changes (EventQueue::ColorSchemeEvent) and the screen re-picks from #theme_def.

Returns:



106
107
108
# File 'lib/tuile/screen.rb', line 106

def theme
  @theme
end

#theme_defThemeDef

The app’s ThemeDef — the dark/light Theme pair the screen picks #theme from, at startup and on every OS appearance flip. Starts as ThemeDef.default (ThemeDef::DEFAULT unless reassigned — tests do, see ThemeDef.default=). Assigning a custom definition is the durable way to theme an app: unlike a bare #theme=, it survives the user toggling the OS appearance.

Returns:



115
116
117
# File 'lib/tuile/screen.rb', line 115

def theme_def
  @theme_def
end

Class Method Details

.closevoid

This method returns an undefined value.



435
436
437
# File 'lib/tuile/screen.rb', line 435

def self.close
  @@instance&.close
end

.fakeFakeScreen

Testing only — creates new screen, locks the UI, and prevents any redraws, so that test TTY is not painted over. FakeScreen#initialize self-installs as the singleton, so subsequent instance calls return the same object.

Returns:



425
# File 'lib/tuile/screen.rb', line 425

def self.fake = FakeScreen.new

.instanceScreen

Returns the singleton instance.

Returns:

  • (Screen)

    the singleton instance.

Raises:



80
81
82
83
84
# File 'lib/tuile/screen.rb', line 80

def self.instance
  raise Tuile::Error, "Screen not initialized; call Screen.new first" if @@instance.nil?

  @@instance
end

Instance Method Details

#active_windowComponent?

Returns current active tiled component.

Returns:

  • (Component, nil)

    current active tiled component.



391
392
393
394
395
396
# File 'lib/tuile/screen.rb', line 391

def active_window
  check_locked
  result = nil
  @pane.content&.on_tree { result = it if it.is_a?(Component::Window) && it.active? }
  result
end

#add_popup(window) ⇒ void

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.

This method returns an undefined value.

Internal — use Component::Popup#open instead. Adds the popup to #pane, centers and focuses it.

Parameters:



268
269
270
271
272
273
# File 'lib/tuile/screen.rb', line 268

def add_popup(window)
  check_locked
  @pane.add_popup(window)
  # No need to fully repaint the scene: a popup simply paints over the
  # current screen contents.
end

#check_lockedvoid

This method returns an undefined value.

Checks that the UI lock is held and the current code runs in the “UI thread”.

Raises:



169
170
171
172
173
174
175
# File 'lib/tuile/screen.rb', line 169

def check_locked
  return if @pretend_ui_lock || @event_queue.locked?

  raise Tuile::Error,
        "UI lock not held: UI mutations must run on the event-loop thread; " \
        "marshal via screen.event_queue.submit { ... }"
end

#clearvoid

This method returns an undefined value.

Clears the TTY screen.



179
180
181
# File 'lib/tuile/screen.rb', line 179

def clear
  print TTY::Cursor.move_to(0, 0), TTY::Cursor.clear_screen
end

#closevoid

This method returns an undefined value.



428
429
430
431
432
# File 'lib/tuile/screen.rb', line 428

def close
  clear
  @pane = nil
  @@instance = nil # rubocop:disable Style/ClassVars
end

#contentComponent?

Returns tiled content (forwarded to Tuile::ScreenPane).

Returns:



87
# File 'lib/tuile/screen.rb', line 87

def content = @pane.content

#content=(content) ⇒ void

This method returns an undefined value.

Parameters:



91
92
93
94
# File 'lib/tuile/screen.rb', line 91

def content=(content)
  @pane.content = content
  layout
end

#cursor_positionPoint?

Returns the absolute screen coordinates where the hardware cursor should sit, or nil if it should be hidden. Only the #focused component owns the cursor: there can be multiple active components (the focus path), but only one focused.

Returns:



544
# File 'lib/tuile/screen.rb', line 544

def cursor_position = @focused&.cursor_position

#focus_nextBoolean

Advances focus to the next Component#tab_stop? in tree order, wrapping around. Scope is the topmost popup if one is open, otherwise #content — this keeps Tab confined inside a modal popup. No-op (returns false) if the modal scope has no tab stops or no content at all.

Returns:

  • (Boolean)

    true if focus moved.



309
# File 'lib/tuile/screen.rb', line 309

def focus_next = cycle_focus(forward: true)

#focus_previousBoolean

Mirror of #focus_next that walks backwards through the tab order.

Returns:

  • (Boolean)

    true if focus moved.



313
# File 'lib/tuile/screen.rb', line 313

def focus_previous = cycle_focus(forward: false)

#has_popup?(window) ⇒ Boolean

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.

Internal — use Component::Popup#open? instead.

Parameters:

Returns:

  • (Boolean)

    true if this popup is currently mounted.



415
416
417
418
# File 'lib/tuile/screen.rb', line 415

def has_popup?(window) # rubocop:disable Naming/PredicatePrefix
  check_locked
  @pane.has_popup?(window)
end

#invalidate(component) ⇒ void

This method returns an undefined value.

Invalidates a component: causes the component to be repainted on next call to #repaint.

Parameters:

Raises:

  • (TypeError)


187
188
189
190
191
192
# File 'lib/tuile/screen.rb', line 187

def invalidate(component)
  check_locked
  raise TypeError, "expected Component, got #{component.inspect}" unless component.is_a? Component

  @invalidated << component unless @repainting.include? component
end

#popupsArray<Component>

Returns currently active popup components (forwarded to Tuile::ScreenPane). The array must not be modified!.

Returns:



161
# File 'lib/tuile/screen.rb', line 161

def popups = @pane.popups

This method returns an undefined value.

Prints given strings. While #repaint is running, writes are accumulated into a frame buffer and flushed to the terminal as a single ‘$stdout.write` at the end of the cycle. This stops the emulator from rendering half-finished frames (e.g. a layout’s clear-background pass before its children have re-painted), which was visible as a brief flicker when the auto-clear path triggers.

Outside repaint, writes go straight to stdout. We deliberately don’t raise on a “print outside repaint” — that would be a useful guardrail against components painting outside the repaint loop, but it’d force terminal-housekeeping writes (‘Screen#clear`, mouse-tracking start/stop, cursor-show on teardown) to bypass this method entirely and write directly to `$stdout`. FakeScreen overrides `print` to capture every byte into its `@prints` array, and tests that exercise `run_event_loop` against a real Tuile::Screen would otherwise leak escape sequences to the test runner’s stdout. Keeping ‘print` as the single sink preserves that override seam.

Parameters:

  • args (String)

    stuff to print.



458
459
460
461
462
463
464
# File 'lib/tuile/screen.rb', line 458

def print(*args)
  if @frame_buffer
    args.each { |s| @frame_buffer << s.to_s }
  else
    Kernel.print(*args)
  end
end

#register_global_shortcut(key, over_popups: false, hint: nil) { ... } ⇒ void

This method returns an undefined value.

Registers an app-level keyboard shortcut. When ‘key` arrives, the block is invoked on the event-loop thread (so it may freely mutate UI) before the key reaches any component. Re-registering the same key replaces the previous binding; use #unregister_global_shortcut to remove one.

Only unprintable keys are accepted — control characters (Ctrl+letter, ESC, BACKSPACE, ENTER, …) and multi-character escape sequences (arrows, F-keys, …). Printable keys raise ArgumentError: they’d hijack typing into a Component::TextField and should be expressed as Component#key_shortcut instead, which the dispatcher suppresses while a text widget owns the hardware cursor. TAB and SHIFT_TAB are also rejected because #handle_key intercepts them for focus navigation before the global registry is consulted, so a binding on them would silently never fire.

Pass ‘hint:` to surface the shortcut in the status bar. It’s a preformatted string the caller fully owns (so colors and the key label style stay consistent with whatever the host app uses elsewhere). The framework splices it in like any other status hint: in the tiled case, right after ‘q quit` and before the active window’s own hint; while a popup is open, only hints from ‘over_popups: true` shortcuts are shown, and they’re prepended before the popup’s ‘q Close`.

Example — open a log popup with Ctrl+L from anywhere, even while a popup is already on screen:

screen.register_global_shortcut(Keys::CTRL_L,
                                over_popups: true,
                                hint: "^L #{screen.theme.hint("log")}") do
  log_popup.open
end

Parameters:

  • key (String)

    unprintable key (e.g. Keys::CTRL_L, Keys::ESC, Keys::PAGE_UP).

  • over_popups (Boolean) (defaults to: false)

    when true, fires even while a modal popup is open (pre-empting the popup’s own key handling). When false (default), the shortcut is suppressed while any popup is open and the popup gets the key instead.

  • hint (String, nil) (defaults to: nil)

    preformatted status-bar hint (e.g. ‘“^L #Tuile::Screen.screenscreen.themescreen.theme.hint(”log“)”`). When nil (default) the shortcut is silent in the status bar. The colors are baked into the string, so a later #theme= does not restyle it — re-register if needed.

Yields:

  • invoked with no arguments when ‘key` is pressed.

Raises:

  • (ArgumentError)


359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/tuile/screen.rb', line 359

def register_global_shortcut(key, over_popups: false, hint: nil, &block)
  raise ArgumentError, "block required" if block.nil?
  raise ArgumentError, "key must be a String, got #{key.inspect}" unless key.is_a?(String)
  raise ArgumentError, "key cannot be empty" if key.empty?
  if Keys.printable?(key)
    raise ArgumentError,
          "global shortcut key must be unprintable; got #{key.inspect}. " \
          "Use Component#key_shortcut for printable keys (it's suppressed " \
          "while a text widget owns the cursor, so it won't hijack typing)."
  end
  if [Keys::TAB, Keys::SHIFT_TAB].include?(key)
    raise ArgumentError,
          "#{key == Keys::TAB ? "TAB" : "SHIFT_TAB"} is reserved for focus navigation"
  end
  unless hint.nil? || hint.is_a?(String)
    raise ArgumentError, "hint must be a String or nil, got #{hint.inspect}"
  end

  @global_shortcuts[key] = Shortcut.new(block: block, over_popups: over_popups, hint: hint)
  refresh_status_bar
end

#remove_popup(window) ⇒ void

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.

This method returns an undefined value.

Internal — use Component::Popup#close instead. Removes the popup from #pane, repairs focus, and repaints the scene.

Does nothing if the window is not open on this screen.

Parameters:



405
406
407
408
409
# File 'lib/tuile/screen.rb', line 405

def remove_popup(window)
  check_locked
  @pane.remove_popup(window)
  needs_full_repaint
end

#repaintvoid

This method returns an undefined value.

Repaints the screen; tries to be as effective as possible, by only considering invalidated windows.



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
# File 'lib/tuile/screen.rb', line 469

def repaint
  check_locked
  # This simple TUI framework doesn't support window clipping since tiled
  # windows are not expected to overlap. If there rarely is a popup, we
  # just repaint all windows in correct order — sure they will paint over
  # other windows, but if this is done in the right order, the final
  # drawing will look okay. Not the most effective algorithm, but very
  # simple and very fast in common cases.

  did_paint = false
  @frame_buffer = +""
  begin
    until @invalidated.empty?
      # Defensive filter: a component can become detached between enqueue
      # and drain (popup close, sibling removed mid-event-handling, focus
      # repair). Detached components have no place on the screen and must
      # never paint, even though Component#invalidate already gates them
      # out — this catches the case where attachment changed since.
      @invalidated.delete_if { |c| !c.attached? }
      break if @invalidated.empty?

      did_paint = true
      popups = @pane.popups

      # Partition invalidated components into tiled vs popup-tree. Sorting
      # by depth across the whole tree would interleave them: a tiled
      # grandchild (depth 3) sorts after a popup's content (depth 2) and
      # overdraws it.
      popup_tree = Set.new
      popups.each { |p| p.on_tree { popup_tree << it } }
      tiled, popup_invalidated = @invalidated.to_a.partition { !popup_tree.include?(it) }

      # Within the tiled tree, paint parents before children.
      tiled.sort_by!(&:depth)

      repaint = if tiled.empty?
                  # Only popups need repaint — paint just their invalidated
                  # components in depth order.
                  popup_invalidated.sort_by(&:depth)
                else
                  # Tiled components may overdraw popups; repaint each open
                  # popup's full subtree on top, in stacking order
                  # (parent-before-child within each popup).
                  tiled + popups.flat_map { |p| collect_subtree(p) }
                end

      @repainting = repaint.to_set
      @invalidated.clear

      # Don't call {#clear} before repaint — causes flickering, and only
      # needed when @content doesn't cover the entire screen.
      repaint.each(&:repaint)

      # Repaint done, mark all components as up-to-date.
      @repainting.clear
    end
    position_cursor if did_paint
    unless @frame_buffer.empty?
      $stdout.write(@frame_buffer)
      $stdout.flush
    end
  ensure
    # Always release the frame buffer, even on exception, so any
    # subsequent {#print} call (e.g. teardown emits during crash unwind)
    # reaches stdout instead of being swallowed by a stranded buffer.
    # The partial frame we hold here is incoherent — discard it.
    @frame_buffer = nil
  end
end

#run_event_loop(capture_mouse: true) ⇒ void

This method returns an undefined value.

Runs event loop – waits for keys and sends them to active window. The function exits when the ‘ESC’ or ‘q’ key is pressed.

Parameters:

  • capture_mouse (Boolean) (defaults to: true)

    when true (default), enables xterm mouse tracking so clicks and scroll wheel arrive as MouseEvents and feed Component#handle_mouse. When false, no tracking escape sequence is written: the terminal keeps its native click handling, which is what you want if the app benefits more from select-to-copy than from click-to-focus. Components’ ‘handle_mouse` is simply never invoked from the loop in that mode (the terminal stops sending the bytes).



286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
# File 'lib/tuile/screen.rb', line 286

def run_event_loop(capture_mouse: true)
  @pretend_ui_lock = false
  $stdin.echo = false
  print MouseEvent.start_tracking if capture_mouse
  # Follow OS light/dark flips live: terminals supporting mode 2031
  # push color-scheme reports that the key thread turns into
  # {EventQueue::ColorSchemeEvent}s.
  print TerminalBackground::NOTIFY_ON
  $stdin.raw do
    event_loop
  end
ensure
  print TerminalBackground::NOTIFY_OFF
  print MouseEvent.stop_tracking if capture_mouse
  print TTY::Cursor.show
  $stdin.echo = true
end

#unregister_global_shortcut(key) ⇒ void

This method returns an undefined value.

Removes a shortcut previously installed by #register_global_shortcut. No-op if ‘key` was not registered.

Parameters:

  • key (String)


385
386
387
388
# File 'lib/tuile/screen.rb', line 385

def unregister_global_shortcut(key)
  @global_shortcuts.delete(key)
  refresh_status_bar
end