Module: Lich::Common::Frontend

Defined in:
documented/common/frontend.rb,
documented/common/frontend.rb

Overview

Catalog and capabilities interface for game frontends.

Manages frontend definitions and capabilities (xml, gsl, streams, mono, etc.), maintaining both built-in defaults (wrayth, stormfront, genie, etc.) and user-defined custom frontends from settings. The registry is thread-safe and snapshot-backed for atomic reloads.

Script authors query capabilities via Frontend.supports_xml?, Frontend.supports_streams?, Frontend.has_capability?, and retrieval via Frontend.definition_for. Frontend detection and launch fall to the bootstrapping layer.

Constant Summary collapse

PLATFORM_KEYS =

Canonical platform identifiers recognized by frontend discovery and launch plans.

Returns:

  • (Array<Symbol>)

See Also:

%i[darwin linux windows unsupported].freeze
CAPABILITY_VOCABULARY =

Capabilities that may be declared by custom frontends.

Runtime-only implementation details (e.g., negotiated during login) are deliberately excluded from this public vocabulary.

Returns:

  • (Array<Symbol>)

See Also:

%i[xml gsl streams mono room_window sentinel room_element game_links double_bold].freeze
BUILT_IN_DEFINITION_FILES =

Manifest of shipped frontend definitions paired with their file paths.

Each entry is [canonical_id, file_name]: the id is lowercased and used for canonical lookup and to validate each definition file's :id field; the file_name is loaded from the frontend/ subdirectory. Order is preserved in GTK selectors and legacy capability constants.

Returns:

See Also:

[
  %w[stormfront wrayth],
  %w[profanity profanity],
  %w[genie genie],
  %w[frostbite frostbite],
  %w[suks suks],
  %w[wizard wizard],
  %w[avalon avalon],
  %w[saga saga]
].freeze
BUILT_IN_FRONTEND_IDS =

Stable canonical identifiers for built-in frontends, in registration order.

Returns:

See Also:

BUILT_IN_DEFINITION_FILES.map(&:first).freeze
ORIGIN_SENTINEL =
"\x1f"
SAGA_LICH_LAUNCH_ENVIRONMENT =

Launch environment variables for the Saga frontend on Linux.

Cached from the sealed built-in Saga definition; initialized at module load time.

Returns:

See Also:

definition_for(:saga)
.dig(:metadata, :launch_plans, :linux, :environment)
CLIENT_STRING =

--- Client String ----------------------------------------- Default client string (Saga identity) sent during handshake

"/FE:WRAYTH /VERSION:1.0.1.28 /P:SAGA /XML"
XML_FRONTENDS =

--- Backward-Compatible Constants ------------------------- These frozen arrays preserve the built-in capability membership exposed by older Lich versions. They intentionally remain stable when user-defined frontends are loaded. Runtime callers that need current custom frontend membership must use frontends_with_capability or supports_*? instead.

frontends_with_capability(:xml).freeze
GSL_FRONTENDS =

Frozen list of frontends claiming GSL capability, in registry order.

Preserves the membership exposed by older Lich versions; not updated when user-defined frontends are loaded. For current capability membership, use frontends_with_capability or supports_gsl? instead.

Returns:

frontends_with_capability(:gsl).freeze
STREAM_FRONTENDS =

Frozen list of frontends claiming streams capability, in registry order.

Preserves the membership exposed by older Lich versions; not updated when user-defined frontends are loaded. For current capability membership, use frontends_with_capability or supports_streams? instead.

Returns:

frontends_with_capability(:streams).freeze
MONO_FRONTENDS =

Frozen list of frontends claiming mono capability, in registry order.

Preserves the membership exposed by older Lich versions; not updated when user-defined frontends are loaded. For current capability membership, use frontends_with_capability or supports_mono? instead.

Returns:

frontends_with_capability(:mono).freeze
SENTINEL_FRONTENDS =

Frozen list of frontends claiming sentinel capability, in registry order.

Preserves the membership exposed by older Lich versions; not updated when user-defined frontends are loaded. For current capability membership, use frontends_with_capability or supports_sentinel? instead.

Returns:

frontends_with_capability(:sentinel).freeze
PROXY_HANDSHAKE_LINE =

A front end's own handshake line, as it reaches Lich's proxy: an optional prefix (Frostbite), an optional leading slash (Genie sends "FE:WRAYTH ..."), FE:, and a /XML token. The line ending is kept.

%r{\A(?<prefix>(?:<c>)?)/?FE:\S+[^\r\n]*?[ \t]/XML(?=[ \t\r\n]|\z)[^\r\n]*(?<eol>\r?\n)?\z}i
CLIENT_STRING_LOG_LIMIT =

--- Client String Logging --------------------------------- Longest client string log_client_string echoes; the rest is elided.

160
LOGGABLE_CLIENT_STRING =

The shape of a front end's handshake line (optional , optional slash, FE:), the only kind of line log_client_string echoes.

%r{\A(?:<c>)?/?FE:}i
CLIENT_STRING_LOG_LABELS =

Labels for client string logging, keyed by source symbol.

Returns:

See Also:

{ frontend: 'from front end', game: 'sent to game' }.freeze
CLIENT_STRING_REPLACED_NOTE =

log_client_string's note when Lich sent its client string in place of the front end's (proxy_handshake, send_handshake).

"Lich's, in place of the front end's"

Class Method Summary collapse

Class Method Details

.built_in_frontends ⇒ Array<String>

Returns the stable identifiers owned by Lich's built-in catalog. User configuration may override only explicitly supported launch fields; it cannot replace built-in identity, protocol capabilities, or defaults.

Returns:



192
193
194
# File 'documented/common/frontend.rb', line 192

def self.built_in_frontends
  BUILT_IN_FRONTEND_IDS
end

.canonical_name(frontend_name) ⇒ String

Returns the stable catalog identifier for a frontend or alias. Unknown values are normalized but are not registered.

Parameters:

  • frontend_name (String, Symbol)

Returns:



328
329
330
331
332
333
# File 'documented/common/frontend.rb', line 328

def self.canonical_name(frontend_name)
  registry_synchronize do
    key = frontend_name.to_s.downcase
    @aliases.fetch(key, key)
  end
end

.capability_vocabulary ⇒ Array<Symbol>

Returns the capabilities users may declare for custom frontends. Runtime-only implementation details are deliberately excluded.

Returns:

  • (Array<Symbol>)


184
185
186
# File 'documented/common/frontend.rb', line 184

def self.capability_vocabulary
  CAPABILITY_VOCABULARY
end

.cleanup_session_file ⇒ void

This method returns an undefined value.

Deletes the temporary session descriptor file, if it exists.

Called during shutdown to clean up the file created by create_session_file. Silently succeeds if no file was created or it has already been deleted.



907
908
909
910
# File 'documented/common/frontend.rb', line 907

def self.cleanup_session_file
  return if @session_file.nil?
  File.delete(@session_file) if File.exist? @session_file
end

.client ⇒ Object

Accessor for the current frontend identity ($frontend global)



723
724
725
# File 'documented/common/frontend.rb', line 723

def self.client
  $frontend
end

.client=(value) ⇒ Object

Setter for the current frontend identity



728
729
730
# File 'documented/common/frontend.rb', line 728

def self.client=(value)
  $frontend = value
end

.client_string(version = nil, frontend: client) ⇒ Object

Handshake client string for a frontend: its registry :client_string, else CLIENT_STRING, with the /VERSION: value replaced by version (--fe-version) when one is given.



735
736
737
738
739
740
# File 'documented/common/frontend.rb', line 735

def self.client_string(version = nil, frontend: client)
  base = (frontend, :client_string) || CLIENT_STRING
  return base if version.nil?

  base.sub(%r{/VERSION:\S+}) { "/VERSION:#{version}" }
end

.create_session_file(name, host, port, display_session: true) ⇒ void

This method returns an undefined value.

Writes a temporary session descriptor for the frontend to detect.

Creates the descriptor as JSON in the system temp directory (Simutronics/sessions), containing name, host, and port. The file path is stored for later cleanup. Nil name skips creation silently.

Parameters:

  • name (String, nil) —

    the session/account name

  • host (String) —

    the game server hostname or IP

  • port (Integer) —

    the game server port

  • display_session (Boolean) (defaults to: true) —

    whether to log the descriptor (default true)

See Also:



881
882
883
884
885
886
887
888
889
890
# File 'documented/common/frontend.rb', line 881

def self.create_session_file(name, host, port, display_session: true)
  return if name.nil?
  FileUtils.mkdir_p @tmp_session_dir
  @session_file = File.join(@tmp_session_dir, "%s.session" % name.downcase.capitalize)
  session_descriptor = { name: name, host: host, port: port }.to_json
  Lich.log "writing session descriptor to %s\n%s" % [@session_file, session_descriptor] if display_session
  File.open(@session_file, "w") do |fd|
    fd << session_descriptor
  end
end

.definition_for(frontend_name) ⇒ Hash

Returns an immutable catalog definition for a registered frontend.

Accepted inputs are a non-empty String or Symbol naming an existing registry entry. Invalid or unknown identifiers raise ArgumentError. This method performs no discovery and persists nothing.

Parameters:

  • frontend_name (String, Symbol)

Returns:

Raises:

  • (ArgumentError) —

    if frontend_name is blank or unregistered



369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
# File 'documented/common/frontend.rb', line 369

def self.definition_for(frontend_name)
  registry_synchronize do
    key = canonical_name(frontend_name)
    raise ArgumentError, 'frontend name must not be empty' if key.empty?
    raise ArgumentError, "unknown frontend: #{frontend_name}" unless @registry.key?(key)

    @definitions[key] ||= Lich::Util.deep_freeze(
      {
        id: key,
        capabilities: @registry.fetch(key)[:capabilities].to_a,
        metadata: deep_copy(@registry.fetch(key)[:metadata])
      }
    )
  end
end

.definitions(gui_selectable: nil) ⇒ Array<Hash>

Returns immutable catalog definitions, optionally restricted to those intended for the graphical launcher.

Parameters:

  • gui_selectable (Boolean, nil) (defaults to: nil)

Returns:



390
391
392
393
394
395
396
397
398
399
# File 'documented/common/frontend.rb', line 390

def self.definitions(gui_selectable: nil)
  registry_synchronize do
    definitions = @registry.keys.map { |name| definition_for(name) }
    next definitions if gui_selectable.nil?

    definitions.select do |definition|
      definition.dig(:metadata, :gui_selectable) == gui_selectable
    end
  end
end

.detect_pid ⇒ Integer?

Detect and store the frontend process ID Uses various methods depending on how Lich was launched

Returns:

  • (Integer, nil) —

    The detected PID or nil if detection fails



970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
# File 'documented/common/frontend.rb', line 970

def self.detect_pid
  # Return existing PID if already set
  current_pid = self.pid
  return current_pid if current_pid && current_pid > 0

  # Try to detect based on launch method
  # This is a fallback for cases where init wasn't called
  parent_pid = Process.ppid
  resolved_pid = resolve_pid(parent_pid)

  if resolved_pid && resolved_pid > 0
    self.pid = resolved_pid
    Lich.log "Frontend PID detected (fallback): #{resolved_pid}" if defined?(Lich.log)
    resolved_pid
  else
    Lich.log "Failed to detect frontend PID" if defined?(Lich.log)
    nil
  end
end

.detect_platform ⇒ Symbol

Detect the current platform

Returns:

  • (Symbol) —

    :windows, :macos, :linux, or :unsupported



1022
1023
1024
1025
# File 'documented/common/frontend.rb', line 1022

def self.detect_platform
  key = platform_key
  key == :darwin ? :macos : key
end

.display_name(frontend_name) ⇒ String

Returns the catalog display name, with a stable fallback for legacy saved entries that predate the catalog.

Parameters:

  • frontend_name (String, Symbol)

Returns:



436
437
438
439
440
# File 'documented/common/frontend.rb', line 436

def self.display_name(frontend_name)
  definition_for(frontend_name).dig(:metadata, :display_name) || frontend_name.to_s.capitalize
rescue ArgumentError
  frontend_name.to_s.capitalize
end

.ensure_windows_modules ⇒ Object

Ensure Windows modules are loaded (they're defined at top level)



1210
1211
1212
1213
1214
# File 'documented/common/frontend.rb', line 1210

def self.ensure_windows_modules
  return false unless native_windows_runtime?

  defined?(::Win32Enum) && defined?(::WinAPI)
end

.frontends_with_capability(capability) ⇒ Array<String>

Returns all frontends that have a specific capability.

Parameters:

  • capability (Symbol) —

    The capability to filter by

Returns:



452
453
454
455
456
457
458
459
460
# File 'documented/common/frontend.rb', line 452

def self.frontends_with_capability(capability)
  registry_synchronize do
    canonical = @registry.select { |_name, data| data[:capabilities].include?(capability.to_sym) }.keys
    aliases = @aliases.filter_map do |alias_name, name|
      alias_name if canonical.include?(name)
    end
    canonical + aliases
  end
end

.has_capability?(frontend_name, capability) ⇒ Boolean

Checks if a frontend has a specific capability.

Parameters:

  • frontend_name (String) —

    The name of the frontend to check

  • capability (Symbol) —

    The capability to check for

Returns:

  • (Boolean)


339
340
341
342
343
344
345
346
# File 'documented/common/frontend.rb', line 339

def self.has_capability?(frontend_name, capability)
  return false if frontend_name.nil?

  registry_synchronize do
    entry = @registry[canonical_name(frontend_name)]
    entry ? entry[:capabilities].include?(capability.to_sym) : false
  end
end

.init_from_parent(parent_pid) ⇒ Integer?

Initialize PID from parent process (for Warlock)

Returns:

  • (Integer, nil) —

    The resolved frontend PID



930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
# File 'documented/common/frontend.rb', line 930

def self.init_from_parent(parent_pid)
  Lich.log "=== Frontend.init_from_parent called ==="
  Lich.log "Parent process PID: #{parent_pid}"

  # Let's see what process this actually is on Windows
  if windows_platform?
    begin
      require 'win32ole'
      wmi = WIN32OLE.connect('winmgmts://')
      rows = wmi.ExecQuery("SELECT Name, ProcessId FROM Win32_Process WHERE ProcessId=#{parent_pid}")
      row = rows.each.first rescue nil
      if row
        Lich.log "Parent process name: #{row.Name}"
      end
    rescue StandardError, LoadError => e
      Lich.log "Could not get parent process name: #{e.message}"
    end
  end

  resolved_pid = resolve_pid(parent_pid)
  Lich.log "resolve_pid(#{parent_pid}) returned: #{resolved_pid}"

  self.pid = resolved_pid
  Lich.log "Frontend PID set to: #{self.pid}"

  resolved_pid
end

.log_client_string(source, line, note: nil) ⇒ void

This method returns an undefined value.

Log one side of the login handshake: the client string the front end sent Lich (:frontend) or the one Lich sent the game (:game).

Every login path logs through here, and only the version/handshake line is ever passed in, never the login key that precedes it. A line that is not shaped like a handshake is still withheld (only its length is logged): proxy_handshake forwards whatever a front end sent in that slot, and that could be a key.

Parameters:

  • source (Symbol) —

    :frontend or :game

  • line (String, nil) —

    the line as read or sent

  • note (String, nil) (defaults to: nil) —

    why this string, appended in parentheses



817
818
819
820
821
# File 'documented/common/frontend.rb', line 817

def self.log_client_string(source, line, note: nil)
  message = "info: client string #{CLIENT_STRING_LOG_LABELS.fetch(source)}: #{loggable_client_string(line)}"
  message += " (#{note})" if note
  Lich.log message
end

.metadata_for(frontend_name, key) ⇒ Object?

Retrieves a metadata value for a given frontend.

Parameters:

  • frontend_name (String) —

    The name of the frontend

  • key (Symbol) —

    The metadata key to retrieve

Returns:

  • (Object, nil)


352
353
354
355
356
357
358
# File 'documented/common/frontend.rb', line 352

def self.(frontend_name, key)
  return nil if frontend_name.nil?

  definition_for(frontend_name).dig(:metadata, key)
rescue ArgumentError
  nil
end

.native_windows_runtime? ⇒ Boolean

Native user32 bindings require a Windows MRI ABI, not merely a Windows host.

Returns:

  • (Boolean)


69
70
71
# File 'documented/common/frontend.rb', line 69

def self.native_windows_runtime?
  OS.host_os.to_s.match?(/mingw|mswin/i)
end

.pid ⇒ Integer?

Get the current frontend PID

Returns:

  • (Integer, nil) —

    The PID if set, nil otherwise



916
917
918
# File 'documented/common/frontend.rb', line 916

def self.pid
  @pid_mutex.synchronize { @frontend_pid }
end

.pid=(value) ⇒ Integer

Set the frontend PID

Parameters:

  • value (Integer) —

    The PID to store

Returns:

  • (Integer) —

    The stored PID



923
924
925
926
# File 'documented/common/frontend.rb', line 923

def self.pid=(value)
  value = value.to_i
  @pid_mutex.synchronize { @frontend_pid = value }
end

.platform_key ⇒ Symbol

Returns the canonical platform key used by frontend discovery and launch-plan metadata.

Returns:

  • (Symbol) —

    :darwin, :windows, :linux, or :unsupported



405
406
407
408
409
410
411
# File 'documented/common/frontend.rb', line 405

def self.platform_key
  return :darwin if OS.mac?
  return :linux if OS.linux?
  return :windows if OS.windows?

  :unsupported
end

.player_id_tag(player_id) ⇒ Object

Build the re-emit tag for a detachable client (e.g. Saga).

Lich consumes the game's one-time during its own login handshake, before a detachable client attaches, so the client never sees it. XMLData.player_id stores the id verbatim, so re-emitting reproduces exactly what a Direct login delivers.

Returns the tag string only when player_id is a bare numeric id (the form the game sends). Returns nil otherwise, so callers skip emitting an empty or malformed tag before login has populated the id.



715
716
717
718
719
720
# File 'documented/common/frontend.rb', line 715

def self.player_id_tag(player_id)
  id = player_id.to_s
  return nil unless id =~ /\A\d+\z/

  "<playerID id='#{id}'/>"
end

.proxy_handshake(line, version: nil, keep: false, frontend: client) ⇒ String?

The handshake to forward for the line a proxied front end sent (the line after the login key). A front end's own handshake is replaced with client_string(version, frontend:), Saga's own /P:SAGA line included (DragonRealms needs Lich's /VERSION:), so every proxied session asks the game for the stream Lich sends Wizard, Frostbite and --without-frontend, and Lich's adapters (RoomBlock, Markup) reshape it for the front end. $frontend is not touched: it comes from the launch arguments, so capability lookups still answer for the real front end.

Forwarded unchanged:

  • a line that is not an /XML handshake (a key, a command, a plain-text client);
  • any handshake when keep is true (--keep-fe-string or Lich.keep_fe_string).

Logs the line received and the line forwarded, with the reason (log_client_string).

Parameters:

  • line (String, nil) —

    the line as read from the front end

  • version (String, nil) (defaults to: nil) —

    the --fe-version value

  • keep (Boolean) (defaults to: false) —

    forward the front end's own handshake

  • frontend (String, nil) (defaults to: client) —

    the front end, for its registry :client_string

Returns:

  • (String, nil) —

    the line to forward



768
769
770
771
772
773
# File 'documented/common/frontend.rb', line 768

def self.proxy_handshake(line, version: nil, keep: false, frontend: client)
  log_client_string(:frontend, line)
  forwarded, note = proxy_handshake_decision(line, version, keep, frontend)
  log_client_string(:game, forwarded, note: note)
  forwarded
end

.refocus ⇒ Boolean

Refocus the frontend window

Returns:

  • (Boolean) —

    true if successful, false otherwise



992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
# File 'documented/common/frontend.rb', line 992

def self.refocus
  pid = self.pid
  return false unless pid && pid > 0

  case detect_platform
  when :windows
    refocus_windows(pid)
  when :macos
    refocus_macos(pid)
  when :linux
    refocus_linux(pid)
  else
    false
  end
end

.refocus_callback ⇒ Proc

Create a callback for GTK windows to refocus on click

Returns:

  • (Proc) —

    A proc that can be called to refocus the frontend



1010
1011
1012
1013
1014
1015
1016
1017
1018
# File 'documented/common/frontend.rb', line 1010

def self.refocus_callback
  proc {
    if defined?(GLib) && GLib.respond_to?(:Idle)
      GLib::Idle.add(50) { self.refocus; false }
    else
      self.refocus
    end
  }
end

.refocus_linux(pid) ⇒ Object

Linux refocus implementation



1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
# File 'documented/common/frontend.rb', line 1193

def self.refocus_linux(pid)
  return false unless system('which xdotool > /dev/null 2>&1')

  _stdout, stderr, status = Open3.capture3('xdotool', 'search', '--pid', pid.to_s, 'windowactivate')

  if status.success?
    true
  else
    Lich.log "Error refocusing Linux: #{stderr}" if defined?(Lich.log)
    false
  end
rescue => e
  Lich.log "Error refocusing Linux: #{e}" if defined?(Lich.log)
  false
end

.refocus_macos(pid) ⇒ Object

macOS refocus implementation



1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
# File 'documented/common/frontend.rb', line 1175

def self.refocus_macos(pid)
  return false unless system('which osascript > /dev/null 2>&1')

  script = %{tell application "System Events" to set frontmost of (first process whose unix id is #{pid}) to true}
  _stdout, stderr, status = Open3.capture3('osascript', '-e', script)

  if status.success?
    true
  else
    Lich.log "Error refocusing macOS: #{stderr}" if defined?(Lich.log)
    false
  end
rescue => e
  Lich.log "Error refocusing macOS: #{e}" if defined?(Lich.log)
  false
end

.refocus_windows(pid) ⇒ Object

Windows refocus implementation



1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
# File 'documented/common/frontend.rb', line 1136

def self.refocus_windows(pid)
  ensure_windows_modules

  hwnd_buf = Fiddle::Pointer.malloc(Fiddle::SIZEOF_VOIDP)

  enum_cb = Fiddle::Closure::BlockCaller.new(
    Fiddle::TYPE_INT,
    [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG]
  ) do |hwnd, _|
    next 1 if ::WinAPI.IsWindowVisible(hwnd).zero?

    pid_tmp = [0].pack('L')
    ::WinAPI.GetWindowThreadProcessId(hwnd, pid_tmp)
    win_pid = pid_tmp.unpack1('L')

    if win_pid == pid
      hwnd_buf[0, Fiddle::SIZEOF_VOIDP] = [hwnd].pack('L!')
      0  # stop enumeration
    else
      1  # continue enumeration
    end
  end

  ::WinAPI.EnumWindows(enum_cb, 0)
  hwnd = hwnd_buf[0, Fiddle::SIZEOF_VOIDP].unpack1('L!')

  if hwnd != 0
    ::WinAPI.SetForegroundWindow(hwnd)
    true
  else
    Lich.log "Frontend window for PID #{pid} not found" if defined?(Lich.log)
    false
  end
rescue => e
  Lich.log "Error refocusing Windows: #{e}" if defined?(Lich.log)
  false
end

.register(name, capabilities: [], metadata: {}) ⇒ void

This method returns an undefined value.

Registers a frontend with its capabilities and metadata.

Parameters:

  • name (Symbol, String) —

    The name of the frontend (e.g., :wrayth)

  • capabilities (Array<Symbol>) (defaults to: []) —

    A list of capabilities (e.g., [:xml, :streams])

  • metadata (Hash) (defaults to: {}) —

    Additional data (e.g., { client_string: "..." })



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
# File 'documented/common/frontend.rb', line 161

def self.register(name, capabilities: [], metadata: {})
  registry_synchronize do
    key = name.to_s.downcase
    raise ArgumentError, 'frontend name must not be empty' if key.empty?

    aliases = Array([:aliases]).map { |alias_name| alias_name.to_s.downcase }
    settings_owned = Array(@user_frontend_ids)
    if settings_owned.include?(key) || aliases.any? { |alias_name| settings_owned.include?(alias_name) }
      raise ArgumentError, "frontend identifier is managed by user settings: #{key}"
    end

    entry = (@registry[key] ||= { capabilities: Set.new, metadata: {} })
    entry[:capabilities].merge(capabilities.map(&:to_sym))
    entry[:metadata].merge!(deep_copy())
    aliases.each { |alias_name| @aliases[alias_name] = key }
    @definitions.delete(key)
    nil
  end
end

.registered_frontends ⇒ Array<String>

Returns every recognized frontend name: canonical catalog identifiers followed by their accepted aliases.

Returns:



445
446
447
# File 'documented/common/frontend.rb', line 445

def self.registered_frontends
  registry_synchronize { @registry.keys + @aliases.keys }
end

.replace_user_configuration!(built_in_overrides:, custom_definitions:) ⇒ void

This method returns an undefined value.

Replaces the complete process-local user configuration in one operation. Built-ins are restored from their sealed defaults before launch-only overrides are applied, and custom definitions from an earlier load are removed before the new set is registered.

FrontendSettings owns validation and persistence. This method is the narrow application seam that keeps catalog reloads deterministic.

Parameters:



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
# File 'documented/common/frontend.rb', line 224

def self.replace_user_configuration!(built_in_overrides:, custom_definitions:)
  registry_synchronize do
    raise 'built-in frontend catalog has not been sealed' unless @built_in_registry

    snapshot = {
      registry: deep_copy(@registry),
      aliases: deep_copy(@aliases),
      definitions: @definitions.dup,
      user_frontend_ids: Array(@user_frontend_ids).dup
    }

    begin
      replace_user_configuration_unlocked!(
        built_in_overrides: built_in_overrides,
        custom_definitions: custom_definitions
      )
    rescue StandardError
      @registry = snapshot[:registry]
      @aliases = snapshot[:aliases]
      @definitions = snapshot[:definitions]
      @user_frontend_ids = snapshot[:user_frontend_ids]
      raise
    end
  end
end

.resolve_linux_pid(pid) ⇒ Object

Linux-specific PID resolution



1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
# File 'documented/common/frontend.rb', line 1110

def self.resolve_linux_pid(pid)
  return pid unless system('which xdotool > /dev/null 2>&1')

  p = pid
  16.times do
    # Check if this process has a window
    return p if system("xdotool search --pid #{p} >/dev/null 2>&1")

    # Walk up to parent process
    begin
      status = File.read("/proc/#{p}/status")
      parent = status[/PPid:\s+(\d+)/, 1].to_i
    rescue
      parent = 0
    end
    return pid if parent.zero? || parent == p
    p = parent
  end

  pid # fallback
rescue => e
  Lich.log "Error resolving Linux PID: #{e}" if defined?(Lich.log)
  pid
end

.resolve_pid(pid) ⇒ Integer

Resolve PID by walking up process tree to find window owner

Parameters:

  • pid (Integer) —

    Starting process ID

Returns:

  • (Integer) —

    The resolved PID



1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
# File 'documented/common/frontend.rb', line 1030

def self.resolve_pid(pid)
  pid = pid.to_i
  return pid if pid <= 0 # Return as-is if invalid

  # Use the FrontendPID resolver logic
  case detect_platform
  when :windows
    resolve_windows_pid(pid)
  when :linux
    resolve_linux_pid(pid)
  else
    # macOS/other: PID usually already owns the window
    pid
  end
end

.resolve_windows_pid(pid) ⇒ Object

Windows-specific PID resolution



1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
# File 'documented/common/frontend.rb', line 1047

def self.resolve_windows_pid(pid)
  Lich.log "=== resolve_windows_pid starting with PID: #{pid} ==="

  ensure_windows_modules
  require 'win32ole' rescue (return pid)

  begin
    wmi = WIN32OLE.connect('winmgmts://')
    p = pid

    16.times do
      # Get process name for debugging
      rows = wmi.ExecQuery("SELECT Name FROM Win32_Process WHERE ProcessId=#{p}")
      row = rows.each.first rescue nil
      process_name = row ? row.Name : "unknown"
      Lich.log "  Process name: #{process_name}"

      # Check if this process owns any visible window
      found = false
      cb = Fiddle::Closure::BlockCaller.new(
        Fiddle::TYPE_INT,
        [Fiddle::TYPE_VOIDP, Fiddle::TYPE_LONG]
      ) do |hwnd, _|
        next 1 if ::Win32Enum.IsWindowVisible(hwnd).zero?
        buf = [0].pack('L')
        ::Win32Enum.GetWindowThreadProcessId(hwnd, buf)
        if buf.unpack1('L') == p
          found = true
          Lich.log "  Found visible window for PID #{p}"
          0  # stop enumeration
        else
          1  # continue enumeration
        end
      end
      ::Win32Enum.EnumWindows(cb, 0)

      if found
        Lich.log "  Stopping at PID #{p} (#{process_name}) - has visible window"
        return p
      end

      # Walk up to parent process
      parent = windows_parent_pid(wmi, p)

      break if parent.nil? || parent.zero? || parent == p
      p = parent
    end
  rescue => e
    Lich.log "ERROR in resolve_windows_pid: #{e}"
  end

  Lich.log "Fallback: returning original PID #{pid}"
  pid
end

.seal_built_in_catalog! ⇒ void

This method returns an undefined value.

Captures immutable built-in defaults after all built-ins are registered.



308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'documented/common/frontend.rb', line 308

def self.seal_built_in_catalog!
  registry_synchronize do
    @built_in_registry = BUILT_IN_FRONTEND_IDS.each_with_object({}) do |frontend_id, result|
      result[frontend_id] = deep_copy(@registry.fetch(frontend_id))
    end
    @built_in_aliases = @aliases.select do |_alias_name, frontend_id|
      BUILT_IN_FRONTEND_IDS.include?(frontend_id)
    end
    Lich::Util.deep_freeze(@built_in_registry)
    Lich::Util.deep_freeze(@built_in_aliases)
    @user_frontend_ids = []
    nil
  end
end

.send_handshake(version_string) ⇒ Object

Send version string, ready signals, and setup commands to the game server. Used during login handshake for wizard/avalon/frostbite frontends, whose own version line is discarded. Logs the version string as sent in place of the front end's (log_client_string).



851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
# File 'documented/common/frontend.rb', line 851

def self.send_handshake(version_string)
  log_client_string(:game, version_string, note: CLIENT_STRING_REPLACED_NOTE)
  $_CLIENTBUFFER_.push(version_string.dup)
  Game._puts(version_string)
  2.times do
    sleep 0.3
    $_CLIENTBUFFER_.push("#{$cmd_prefix}\r\n")
    Game._puts($cmd_prefix)
  end
  ["#{$cmd_prefix}_injury 2",
   "#{$cmd_prefix}_flag Display Inventory Boxes 1",
   "#{$cmd_prefix}_flag Display Dialog Boxes 0"].each do |cmd|
    $_CLIENTBUFFER_.push(cmd)
    Game._puts(cmd)
  end
end

.sentinel_requested=(value) ⇒ Object

Parameters:

  • value (Boolean)


701
702
703
# File 'documented/common/frontend.rb', line 701

def self.sentinel_requested=(value)
  @sentinel_requested = value == true
end

.sentinel_requested? ⇒ Boolean

Whether --sentinel was passed for this session.

Returns:

  • (Boolean)


696
697
698
# File 'documented/common/frontend.rb', line 696

def self.sentinel_requested?
  @sentinel_requested == true
end

.session_file_location ⇒ String?

Returns the path to the current session descriptor file, if created.

Returns:

  • (String, nil) —

    the file path, or nil if no session file was created

See Also:



896
897
898
# File 'documented/common/frontend.rb', line 896

def self.session_file_location
  @session_file
end

.set_from_client(pid) ⇒ Integer

Set PID from a detachable frontend such as Profanity or Saga.

Parameters:

  • pid (Integer) —

    The PID sent by the client

Returns:

  • (Integer) —

    The stored PID



961
962
963
964
965
# File 'documented/common/frontend.rb', line 961

def self.set_from_client(pid)
  self.pid = pid
  Lich.log "Frontend PID set from client: #{pid}" if defined?(Lich.log)
  pid
end

.supports_double_bold?(fe = $frontend) ⇒ Boolean

Whether the front end handles DragonRealms' creature bold: the doubled around linked creatures in room-object listings and the single pair around them in action and assess lines. Others get the legacy line: one pair in the listings (Markup.collapse_double_bold) and none elsewhere (Markup.strip_link_bold). Reads the front end's table only; each client's set comes from ClientCapabilities.

Returns:

  • (Boolean)


681
682
683
# File 'documented/common/frontend.rb', line 681

def self.supports_double_bold?(fe = $frontend)
  has_capability?(fe, :double_bold)
end

.supports_gsl?(fe = $frontend) ⇒ Boolean

Checks if a frontend supports GSL (GemStone Scripting Language) output.

Examples:

Frontend.supports_gsl?("wrayth") #=> true

Parameters:

  • fe (String, nil) (defaults to: $frontend) —

    the frontend name (defaults to current $frontend)

Returns:

  • (Boolean) —

    true if the frontend has :gsl capability

See Also:



625
626
627
# File 'documented/common/frontend.rb', line 625

def self.supports_gsl?(fe = $frontend)
  has_capability?(fe, :gsl)
end

.supports_mono?(fe = $frontend) ⇒ Boolean

Checks if a frontend supports monospace output.

Examples:

Frontend.supports_mono?("avalon") #=> true

Parameters:

  • fe (String, nil) (defaults to: $frontend) —

    the frontend name (defaults to current $frontend)

Returns:

  • (Boolean) —

    true if the frontend has :mono capability

See Also:



647
648
649
# File 'documented/common/frontend.rb', line 647

def self.supports_mono?(fe = $frontend)
  has_capability?(fe, :mono)
end

.supports_room_element?(fe = $frontend) ⇒ Boolean

Whether the front end renders the Saga-identity stream's inline block itself. Others get it rewritten to the legacy roomName/roomDesc layout (see Lich::Common::RoomBlock). Reads the front end's table only; each client's set comes from ClientCapabilities.

Returns:

  • (Boolean)


664
665
666
# File 'documented/common/frontend.rb', line 664

def self.supports_room_element?(fe = $frontend)
  has_capability?(fe, :room_element)
end

.supports_room_window?(fe = $frontend) ⇒ Boolean

Checks if a frontend supports a dedicated room window pane.

Parameters:

  • fe (String, nil) (defaults to: $frontend) —

    the frontend name (defaults to current $frontend)

Returns:

  • (Boolean) —

    true if the frontend has :room_window capability

See Also:



656
657
658
# File 'documented/common/frontend.rb', line 656

def self.supports_room_window?(fe = $frontend)
  has_capability?(fe, :room_window)
end

.supports_sentinel?(fe = $frontend) ⇒ Boolean

The running session also gets the sentinel when --sentinel asked for it, so a client can identify as another frontend (stormfront, for the scripts that test for it) and still receive the origin marker.

Returns:

  • (Boolean)


688
689
690
691
692
# File 'documented/common/frontend.rb', line 688

def self.supports_sentinel?(fe = $frontend)
  return true if sentinel_requested? && canonical_name(fe) == canonical_name($frontend)

  has_capability?(fe, :sentinel)
end

.supports_streams?(fe = $frontend) ⇒ Boolean

Checks if a frontend supports game streams (segmented XML).

Examples:

Frontend.supports_streams?("genie") #=> true

Parameters:

  • fe (String, nil) (defaults to: $frontend) —

    the frontend name (defaults to current $frontend)

Returns:

  • (Boolean) —

    true if the frontend has :streams capability

See Also:



636
637
638
# File 'documented/common/frontend.rb', line 636

def self.supports_streams?(fe = $frontend)
  has_capability?(fe, :streams)
end

.supports_xml?(fe = $frontend) ⇒ Boolean

Checks if a frontend supports XML output.

Examples:

Frontend.supports_xml?("wrayth") #=> true

Parameters:

  • fe (String, nil) (defaults to: $frontend) —

    the frontend name (defaults to current $frontend)

Returns:

  • (Boolean) —

    true if the frontend has :xml capability

See Also:



614
615
616
# File 'documented/common/frontend.rb', line 614

def self.supports_xml?(fe = $frontend)
  has_capability?(fe, :xml)
end

.user_definition_id_available?(frontend_name) ⇒ Boolean

Returns whether an identifier is available for a settings-owned custom frontend. An identifier already owned by the current settings document remains available so reloads can replace it without colliding with themselves. Registry entries and aliases owned elsewhere are reserved.

Parameters:

  • frontend_name (String, Symbol)

Returns:

  • (Boolean)


203
204
205
206
207
208
209
210
211
# File 'documented/common/frontend.rb', line 203

def self.user_definition_id_available?(frontend_name)
  registry_synchronize do
    key = frontend_name.to_s.downcase
    next false if key.empty?
    next true if Array(@user_frontend_ids).include?(key)

    !@registry.key?(key) && !@aliases.key?(key)
  end
end

.validate_platform_key!(key) ⇒ Symbol

Validates a canonical platform key used by discovery and launch plans.

Parameters:

  • key (Symbol)

Returns:

  • (Symbol)

Raises:

  • (ArgumentError) —

    when key is not canonical



418
419
420
421
422
# File 'documented/common/frontend.rb', line 418

def self.validate_platform_key!(key)
  return key if PLATFORM_KEYS.include?(key)

  raise ArgumentError, "invalid platform key: #{key.inspect}"
end

.windows_parent_pid(wmi, pid) ⇒ Object

Get parent process ID on Windows



1103
1104
1105
1106
1107
# File 'documented/common/frontend.rb', line 1103

def self.windows_parent_pid(wmi, pid)
  rows = wmi.ExecQuery("SELECT ParentProcessId FROM Win32_Process WHERE ProcessId=#{pid}")
  row = rows.each.first rescue nil
  row ? row.ParentProcessId.to_i : 0
end

.windows_platform? ⇒ Boolean

Returns whether the current host is classified as Windows.

Returns:

  • (Boolean)


427
428
429
# File 'documented/common/frontend.rb', line 427

def self.windows_platform?
  platform_key == :windows
end