Class: Charming::Runtime

Inherits:
Object
  • Object
show all
Defined in:
lib/charming/runtime.rb

Overview

Runtime manages a terminal UI application's lifecycle: setting up an alternative-screen terminal with cursor hiding, running an event loop that reads keyboard, mouse, timer, and task events, dispatching them to controllers, rendering responses, and tearing down cleanly on exit.

Constant Summary collapse

DEFAULT_READ_TIMEOUT =
Internal::EventLoop::DEFAULT_READ_TIMEOUT

Instance Method Summary collapse

Constructor Details

#initialize(application, backend: nil, renderer: nil, clock: nil, task_executor: nil) ⇒ Runtime

Returns a new instance of Runtime.



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/charming/runtime.rb', line 11

def initialize(application, backend: nil, renderer: nil, clock: nil, task_executor: nil)
  @application = application
  @backend = backend || Internal::Terminal::TTYBackend.new
  @renderer = renderer || Internal::Renderer::Differential.new(@backend)
  @clock = clock || -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
  @task_queue = Thread::Queue.new
  @task_executor = build_task_executor(task_executor)
  @application.task_executor = @task_executor
  @route = @application.routes.resolve("/")
  @screen = backend_screen
  @coalesce_input = @application.respond_to?(:coalesce_input?) && @application.coalesce_input?
  @event_loop = build_event_loop
end

Instance Method Details

#runObject

Runs the event loop: enters alt-screen, dispatches incoming events (key, mouse, timer, async task), renders controller responses, and restores terminal state on exit. Unhandled exceptions from controller actions render an ErrorScreen instead of crashing the terminal.



29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/charming/runtime.rb', line 29

def run
  setup_terminal
  install_signal_handlers
  install_exit_hook
  with_raw_input do
    render(initial_response)
    @event_loop.run { |event, more_ready| process(event, flush: !more_ready) }
  ensure
    restore_signal_handlers
    @task_executor&.shutdown(timeout: 2.0)
    @application.save_session if @application.respond_to?(:save_session)
    restore_terminal
  end
end