Class: Harnex::SessionState

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

Constant Summary collapse

STATES =
%i[prompt busy blocked unknown].freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter) ⇒ SessionState

Returns a new instance of SessionState.



7
8
9
10
11
12
# File 'lib/harnex/runtime/session_state.rb', line 7

def initialize(adapter)
  @adapter = adapter
  @state = :unknown
  @mutex = Mutex.new
  @condvar = ConditionVariable.new
end

Instance Attribute Details

#stateObject (readonly)

Returns the value of attribute state.



5
6
7
# File 'lib/harnex/runtime/session_state.rb', line 5

def state
  @state
end

Instance Method Details

#force_busy!Object



32
33
34
35
36
37
# File 'lib/harnex/runtime/session_state.rb', line 32

def force_busy!
  @mutex.synchronize do
    @state = :busy
    @condvar.broadcast
  end
end

#to_sObject



51
52
53
# File 'lib/harnex/runtime/session_state.rb', line 51

def to_s
  @mutex.synchronize { @state.to_s }
end

#update(screen_snapshot) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/harnex/runtime/session_state.rb', line 14

def update(screen_snapshot)
  input = @adapter.input_state(screen_snapshot)
  new_state =
    case input[:input_ready]
    when true  then :prompt
    when false then :blocked
    else            :unknown
    end

  @mutex.synchronize do
    old = @state
    @state = new_state
    @condvar.broadcast if old != new_state
  end

  new_state
end

#wait_for_prompt(timeout) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
# File 'lib/harnex/runtime/session_state.rb', line 39

def wait_for_prompt(timeout)
  deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + timeout
  @mutex.synchronize do
    loop do
      return true if @state == :prompt
      remaining = deadline - Process.clock_gettime(Process::CLOCK_MONOTONIC)
      return false if remaining <= 0
      @condvar.wait(@mutex, remaining)
    end
  end
end