Module: Lich

Included in:
DragonRealms, Gemstone
Defined in:
documented/lich.rb,
documented/games.rb,
documented/stash.rb,
documented/update.rb,
documented/gemcheck.rb,
documented/messaging.rb,
documented/util/opts.rb,
documented/util/util.rb,
documented/common/gtk.rb,
documented/common/hmr.rb,
documented/common/log.rb,
documented/magic-info.rb,
documented/common/move.rb,
documented/common/vars.rb,
documented/gemstone/sk.rb,
documented/global_defs.rb,
documented/common/spell.rb,
documented/gemstone/fog.rb,
documented/common/buffer.rb,
documented/common/events.rb,
documented/common/markup.rb,
documented/common/script.rb,
documented/gemstone/bank.rb,
documented/gemstone/disk.rb,
documented/gemstone/gift.rb,
documented/gemstone/mana.rb,
documented/gemstone/psms.rb,
documented/common/account.rb,
documented/common/gameobj.rb,
documented/common/pipe_io.rb,
documented/gemstone/claim.rb,
documented/gemstone/group.rb,
documented/gemstone/scars.rb,
documented/main/help_text.rb,
documented/attributes/char.rb,
documented/common/db_store.rb,
documented/common/frontend.rb,
documented/common/frontend.rb,
documented/common/postload.rb,
documented/common/settings.rb,
documented/common/throttle.rb,
documented/common/uservars.rb,
documented/common/watchfor.rb,
documented/gemstone/bounty.rb,
documented/gemstone/stance.rb,
documented/gemstone/wounds.rb,
documented/main/early_exit.rb,
documented/attributes/stats.rb,
documented/bundler_recovery.rb,
documented/common/gui/state.rb,
documented/common/gui_login.rb,
documented/common/inventory.rb,
documented/common/user_defs.rb,
documented/common/watchable.rb,
documented/common/xmlparser.rb,
documented/gemstone/effects.rb,
documented/gemstone/infomon.rb,
documented/gemstone/injured.rb,
documented/gemstone/society.rb,
documented/util/deep_freeze.rb,
documented/attributes/skills.rb,
documented/attributes/spells.rb,
documented/common/arg_parser.rb,
documented/common/gameloader.rb,
documented/common/map/map_dr.rb,
documented/common/map/map_gs.rb,
documented/common/room_block.rb,
documented/gemstone/creature.rb,
documented/gemstone/currency.rb,
documented/gemstone/stowlist.rb,
documented/main/argv_options.rb,
documented/util/textstripper.rb,
documented/common/setup_files.rb,
documented/gemstone/armaments.rb,
documented/gemstone/critranks.rb,
documented/gemstone/overwatch.rb,
documented/gemstone/psms/cman.rb,
documented/gemstone/psms/feat.rb,
documented/gemstone/readylist.rb,
documented/gemstone/xml_delta.rb,
documented/main/startup_theme.rb,
documented/api/active_sessions.rb,
documented/common/limitedarray.rb,
documented/common/map/map_base.rb,
documented/common/script_death.rb,
documented/common/sharedbuffer.rb,
documented/common/shutdown_log.rb,
documented/common/upstreamhook.rb,
documented/common/xml_entities.rb,
documented/dependency_recovery.rb,
documented/gemstone/experience.rb,
documented/gemstone/psms/armor.rb,
documented/gemstone/spellranks.rb,
documented/util/gtk_compaction.rb,
documented/util/memoryreleaser.rb,
documented/attributes/enhancive.rb,
documented/attributes/resources.rb,
documented/attributes/spellsong.rb,
documented/common/feature_flags.rb,
documented/common/gui/utilities.rb,
documented/common/hook_registry.rb,
documented/common/wait_response.rb,
documented/gemstone/bounty/task.rb,
documented/gemstone/infomon/cli.rb,
documented/gemstone/psms/shield.rb,
documented/gemstone/psms/warcry.rb,
documented/gemstone/psms/weapon.rb,
documented/common/downstreamhook.rb,
documented/common/game_transport.rb,
documented/common/gui/components.rb,
documented/dragonrealms/creature.rb,
documented/gemstone/psms/qstrike.rb,
documented/common/client_commands.rb,
documented/common/gui/theme_utils.rb,
documented/common/ruby_executable.rb,
documented/common/shutdown_intent.rb,
documented/common/websocket/frame.rb,
documented/dragonrealms/drinfomon.rb,
documented/dragonrealms/xml_delta.rb,
documented/gemstone/bounty/parser.rb,
documented/gemstone/combat/parser.rb,
documented/gemstone/infomon/cache.rb,
documented/main/arg_normalization.rb,
documented/main/reconnect_command.rb,
documented/common/credential_scrub.rb,
documented/common/frontend_locator.rb,
documented/common/orderly_shutdown.rb,
documented/common/process_launcher.rb,
documented/common/session_launcher.rb,
documented/common/socket_read_hook.rb,
documented/common/websocket/stream.rb,
documented/gemstone/combat/tracker.rb,
documented/gemstone/infomon/parser.rb,
documented/gemstone/infomon/status.rb,
documented/gemstone/psms/ascension.rb,
documented/gemstone/psms/technique.rb,
documented/main/user_exit_dispatch.rb,
documented/common/frontend_launcher.rb,
documented/common/frontend_settings.rb,
documented/common/gui/accessibility.rb,
documented/common/gui/conversion_ui.rb,
documented/common/session_lifecycle.rb,
documented/common/shutdown_watchdog.rb,
documented/common/sqlite_connection.rb,
documented/gemstone/combat/defs/ucs.rb,
documented/gemstone/combat/messages.rb,
documented/gemstone/combat/recorder.rb,
documented/main/bind_address_option.rb,
documented/common/authentication/cli.rb,
documented/common/authentication/gui.rb,
documented/common/bind_host_resolver.rb,
documented/common/cli/cli_conversion.rb,
documented/common/gui/game_selection.rb,
documented/common/saga_launch_policy.rb,
documented/common/saga_managed_login.rb,
documented/common/socketconfigurator.rb,
documented/common/update/file_writer.rb,
documented/common/update/script_sync.rb,
documented/gemstone/combat/processor.rb,
documented/common/client_capabilities.rb,
documented/common/gui/account_manager.rb,
documented/common/gui/login_tab_utils.rb,
documented/common/gui/password_change.rb,
documented/common/gui/password_cipher.rb,
documented/common/gui/saved_login_tab.rb,
documented/common/gui/window_settings.rb,
documented/common/reusable_tcp_server.rb,
documented/common/update/custom_repos.rb,
documented/common/update/file_updater.rb,
documented/common/websocket/handshake.rb,
documented/gemstone/infomon/xmlparser.rb,
documented/common/gui/manual_login_tab.rb,
documented/common/gui/password_manager.rb,
documented/common/gui/tab_communicator.rb,
documented/common/settings_transformer.rb,
documented/common/shutdown_coordinator.rb,
documented/common/update/github_client.rb,
documented/common/windows_command_line.rb,
documented/common/xmlparser/game_delta.rb,
documented/dragonrealms/commons/common.rb,
documented/gemstone/combat/defs/damage.rb,
documented/gemstone/combat/defs/flares.rb,
documented/gemstone/combat/defs/spells.rb,
documented/common/class_exts/stringproc.rb,
documented/common/cli/cli_orchestration.rb,
documented/common/gui/favorites_manager.rb,
documented/common/gui/frontend_selector.rb,
documented/common/gui/parameter_objects.rb,
documented/common/saga_managed_launcher.rb,
documented/common/settings/charsettings.rb,
documented/common/settings/gamesettings.rb,
documented/common/shutdown_script_drain.rb,
documented/gemstone/combat/defs/attacks.rb,
documented/gemstone/infomon/activespell.rb,
documented/internal_api/active_sessions.rb,
documented/common/authentication/eaccess.rb,
documented/common/creature/creature_base.rb,
documented/common/gui/account_manager_ui.rb,
documented/common/script_execution_guard.rb,
documented/common/update/status_reporter.rb,
documented/common/update/tracked_scripts.rb,
documented/dragonrealms/commons/slackbot.rb,
documented/dragonrealms/drinfomon/drdefs.rb,
documented/dragonrealms/drinfomon/drroom.rb,
documented/dragonrealms/drinfomon/events.rb,
documented/gemstone/combat/defs/assaults.rb,
documented/gemstone/combat/defs/messages.rb,
documented/gemstone/combat/defs/outcomes.rb,
documented/gemstone/combat/defs/statuses.rb,
documented/main/detachable_client_notice.rb,
documented/main/detachable_client_target.rb,
documented/common/client_input_dispatcher.rb,
documented/common/room_description_filter.rb,
documented/common/settings/path_navigator.rb,
documented/common/settings/settings_proxy.rb,
documented/common/sharing_violation_retry.rb,
documented/common/update/branch_installer.rb,
documented/common/update/channel_resolver.rb,
documented/common/update/snapshot_manager.rb,
documented/dragonrealms/drinfomon/drskill.rb,
documented/dragonrealms/drinfomon/drstats.rb,
documented/dragonrealms/drinfomon/startup.rb,
documented/gemstone/armaments/armor_stats.rb,
documented/gemstone/combat/defs/sequences.rb,
documented/main/detachable_session_poller.rb,
documented/common/authentication/web_login.rb,
documented/common/cli/cli_option_validator.rb,
documented/common/cli/cli_options_registry.rb,
documented/common/client_commands/builtins.rb,
documented/common/creature/creature_facade.rb,
documented/common/gui/frontend_manager_tab.rb,
documented/common/update/release_installer.rb,
documented/dragonrealms/drinfomon/drparser.rb,
documented/dragonrealms/drinfomon/drspells.rb,
documented/gemstone/armaments/shield_stats.rb,
documented/gemstone/armaments/weapon_stats.rb,
documented/gemstone/combat/async_processor.rb,
documented/gemstone/detachable_client_init.rb,
documented/common/cli/active_sessions_query.rb,
documented/common/settings/database_adapter.rb,
documented/dragonrealms/drinfomon/drbanking.rb,
documented/gemstone/combat/defs/supplements.rb,
documented/gemstone/societies/order_of_voln.rb,
documented/common/authentication/entry_store.rb,
documented/common/authentication/launch_data.rb,
documented/common/detachable_client_registry.rb,
documented/common/gui/encryption_mode_change.rb,
documented/common/gui/master_password_change.rb,
documented/common/gui/master_password_prompt.rb,
documented/common/settings/instance_settings.rb,
documented/common/settings/sessions_settings.rb,
documented/common/shutdown_result_predicates.rb,
documented/dragonrealms/commons/common-items.rb,
documented/dragonrealms/commons/common-money.rb,
documented/dragonrealms/commons/equipmanager.rb,
documented/dragonrealms/custom_substitutions.rb,
documented/gemstone/combat/defs/pattern_gate.rb,
documented/gemstone/combat/defs/spell_losses.rb,
documented/common/authentication/cli_password.rb,
documented/common/gui/master_password_manager.rb,
documented/dragonrealms/commons/common-arcana.rb,
documented/dragonrealms/commons/common-travel.rb,
documented/dragonrealms/drinfomon/drvariables.rb,
documented/common/authentication/authenticator.rb,
documented/common/authentication/launch_result.rb,
documented/common/authentication/login_helpers.rb,
documented/common/best_effort_shutdown_cleanup.rb,
documented/common/gui/manual_frontend_selector.rb,
documented/dragonrealms/commons/common-healing.rb,
documented/dragonrealms/commons/common-theurgy.rb,
documented/dragonrealms/detachable_client_init.rb,
documented/dragonrealms/drinfomon/drexpmonitor.rb,
documented/gemstone/societies/council_of_light.rb,
documented/internal_api/active_sessions/client.rb,
documented/internal_api/active_sessions/server.rb,
documented/common/class_exts/synchronizedsocket.rb,
documented/common/gui/master_password_prompt_ui.rb,
documented/dragonrealms/commons/common-crafting.rb,
documented/dragonrealms/commons/common-moonmage.rb,
documented/common/cli/cli_encryption_mode_change.rb,
documented/common/gui/windows_credential_manager.rb,
documented/dragonrealms/commons/common-summoning.rb,
documented/gemstone/armaments/weapon_stats_blunt.rb,
documented/gemstone/armaments/weapon_stats_edged.rb,
documented/internal_api/active_sessions/registry.rb,
documented/dragonrealms/commons/common-money-data.rb,
documented/dragonrealms/commons/common-validation.rb,
documented/gemstone/armaments/weapon_stats_hybrid.rb,
documented/gemstone/armaments/weapon_stats_ranged.rb,
documented/gemstone/armaments/weapon_stats_thrown.rb,
documented/internal_api/active_sessions/lifecycle.rb,
documented/dragonrealms/dependency/settings_config.rb,
documented/gemstone/armaments/weapon_stats_natural.rb,
documented/gemstone/armaments/weapon_stats_polearm.rb,
documented/gemstone/armaments/weapon_stats_unarmed.rb,
documented/gemstone/societies/guardians_of_sunfist.rb,
documented/common/settings/session_database_adapter.rb,
documented/dragonrealms/commons/common-healing-data.rb,
documented/gemstone/armaments/weapon_stats_brawling.rb,
documented/gemstone/armaments/weapon_stats_runestave.rb,
documented/gemstone/armaments/weapon_stats_two_handed.rb

Overview

Namespace for the Lich 5 scripting engine.

Lich 5 is a Ruby scripting system for GemStone IV and DragonRealms.

Defined Under Namespace

Modules: API, Claim, Common, DragonRealms, GameBase, GemCheck, Gemstone, InternalAPI, Main, Messaging, Resources, SQLiteBusyWait, Stash, Unknown, Util Classes: BundlerRecovery, DependencyRecovery

Constant Summary collapse

DISPLAY_SETTINGS_MAX_ATTEMPTS =

Shared Lich.db uses a Ruby busy handler that releases the GVL while waiting (5000 ms per attempt by default). The calling thread still waits. Two attempts plus one 100 ms pause bound each operation's default lock waiting to about 10.1 seconds plus execution overhead. Failed writes raise; hot-path reads use an uncached default unless a command requests strict reads.

2
DISPLAY_SETTINGS_RETRY_DELAY =
0.1
DISPLAY_SETTINGS_RETRY_COOLDOWN =
30.0
ROOMID_LOCATIONS =

The valid values for Lich.display_roomid_location.

%w[title line both].freeze
MAX_DEBUG_LOGS_DEFAULT =

Default number of debug log files to retain when no user preference is set.

Returns:

  • (Integer) —

    the built-in retention limit

20
MAX_DEBUG_LOGS_MINIMUM =

Minimum allowed value for max_debug_logs to prevent accidental deletion of all log files.

Returns:

  • (Integer) —

    the floor value enforced by the setter

1
DEFAULT_SQLITE_BUSY_TIMEOUT_MS =

Default timeout in milliseconds for SQLite lock waits.

Returns:

  • (Integer)
5000
SQLITE_POOL_TIMEOUT_BUSY_TIMEOUTS =

How many busy timeouts a thread waits for a free pooled connection before Sequel raises Sequel::PoolTimeout; see Lich.sqlite_pool_timeout_s.

3
@@hosts_file =
nil
@@lich_db =
nil
@@last_warn_deprecated =
0
@@deprecated_log =
[]
@@keep_fe_string =

settings

nil
@@track_autosort_state =

boolean

nil
@@track_dark_mode =

boolean

nil
@@track_layout_state =

boolean

nil
@@track_persistent_launcher_mode =

boolean

nil
@@debug_messaging =

boolean

nil
@@max_debug_logs =

boolean

nil

Class Method Summary collapse

Class Method Details

.break_game_host_port(gamehost, gameport) ⇒ Array(String, Integer)

Reverses game server normalization, converting Storm endpoints back to legacy addresses.

Inverse of fix_game_host_port: maps Storm consolidated servers back to their original pre-consolidation hostnames and ports (for launcher registry restoration).

Parameters:

  • gamehost (String) —

    the game server hostname

  • gameport (Integer, #to_i) —

    the game server port

Returns:

  • (Array(String, Integer)) —

    the original [gamehost, gameport] pair



982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
# File 'documented/lich.rb', line 982

def self.break_game_host_port(gamehost, gameport)
  if (gamehost == 'storm.gs4.game.play.net') and (gameport.to_i == 10324)
    gamehost = 'gs4.simutronics.net'
    gameport = 10321
  elsif (gamehost == 'storm.gs4.game.play.net') and (gameport.to_i == 10124)
    gamehost = 'gs-plat.simutronics.net'
    gameport = 10121
  elsif (gamehost == 'storm.gs4.game.play.net') and (gameport.to_i == 10024)
    gamehost = 'gs3.simutronics.net'
    gameport = 4900
  elsif (gamehost == 'dr.simutronics.net') and (gameport.to_i == 11024)
    gamehost = 'prime.dr.game.play.net'
    gameport = 4901
  end
  [gamehost, gameport]
end

.class_eval(*_a) ⇒ nil

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.

Disabled stub for class evaluation.

Always returns nil. Prevents scripts from calling Lich.class_eval.

Returns:

  • (nil)


313
# File 'documented/lich.rb', line 313

def self.class_eval(*_a); nil; end

.class_variable_get(*_a) ⇒ nil

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.

Disabled stub for class variable access.

Always returns nil. Prevents scripts from calling Lich.class_variable_get.

Returns:

  • (nil)


305
# File 'documented/lich.rb', line 305

def self.class_variable_get(*_a); nil; end

.cleanup_debug_logs(temp_dir) ⇒ void

This method returns an undefined value.

Removes old debug log files from temp_dir, keeping at most max_debug_logs files. Files are sorted lexicographically by name (which encodes a timestamp), so the most recent files are retained.

This method is called once during Lich startup (in init.rb) after the database has been initialized.

Parameters:

  • temp_dir (String) —

    the directory containing debug log files

See Also:



1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
# File 'documented/lich.rb', line 1701

def self.cleanup_debug_logs(temp_dir)
  pattern = /^debug(?:-\d+)+\.log$/
  candidates = Dir.entries(temp_dir).select { |fn| fn.match?(pattern) }
  limit = Lich.max_debug_logs
  return if candidates.length <= limit

  candidates.sort.reverse[limit..-1].each do |old_file|
    begin
      File.delete(File.join(temp_dir, old_file))
    rescue
      Lich.log "error: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
    end
  end
end

.configure_sqlite_connection(db) ⇒ Object

For a single SQLite3::Database that several threads share (Lich.db and the session summary connection). It gets the same Ruby busy handler as the pooled connections, and every sqlite3 call on it and on its statements runs under one Monitor (see SQLiteBusyWait::SerializedDatabase), so a second thread waits in Ruby instead of on SQLite's connection mutex while the first sleeps in the handler. The C busy timeout set first stays in force if the connection has no busy_handler API.



28
29
30
31
# File 'documented/common/sqlite_connection.rb', line 28

def self.configure_sqlite_connection(db)
  db.busy_timeout(sqlite_busy_timeout_ms) if db.respond_to?(:busy_timeout)
  SQLiteBusyWait.install(db, sqlite_busy_timeout_ms.to_i, shared: true)
end

.core_updated_with_lich_version ⇒ String

Retrieves the Lich version that last updated the core scripts.

Reads from lich_settings and retries on SQLite3::BusyException.

Returns:

  • (String) —

    the version string, or empty string if not set



1286
1287
1288
1289
1290
1291
1292
1293
1294
# File 'documented/lich.rb', line 1286

def self.core_updated_with_lich_version
  begin
    val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='core_updated_with_lich_version';")
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
  return val.to_s
end

.core_updated_with_lich_version=(val) ⇒ void

This method returns an undefined value.

Records the Lich version that last updated the core scripts.

Writes to lich_settings as UTF-8 encoded string via INSERT OR REPLACE. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    the Lich version string



1303
1304
1305
1306
1307
1308
1309
1310
# File 'documented/lich.rb', line 1303

def self.core_updated_with_lich_version=(val)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('core_updated_with_lich_version',?);", [val.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.db ⇒ Object

WARNING: do not call Lich.db.transaction { } (or run BEGIN/COMMIT by hand on Lich.db) without handling a failed or interrupted COMMIT. If the thread is killed while COMMIT waits for the lock, the transaction stays open on this shared connection and holds the write lock until Lich exits. Nothing calls Lich.db.transaction today. Databases opened with Lich.open_sequel_sqlite roll back a failed or interrupted COMMIT; see SQLiteBusyWait::Transactions.



244
245
246
# File 'documented/lich.rb', line 244

def self.db
  @@lich_db ||= open_sqlite_db("#{DATA_DIR}/lich.db3")
end

.db_maint_due?(months = 6) ⇒ Boolean

Determines whether database maintenance is due based on elapsed time.

Returns true if no maintenance timestamp is recorded, or if the last recorded time is older than the specified number of months. Treats the timestamp as ISO 8601 and compares against the current UTC time. Returns true on parse errors or if last_at is nil.

Parameters:

  • months (Integer) (defaults to: 6) —

    interval in months between maintenance operations (default 6)

Returns:

  • (Boolean) —

    true if VACUUM should be attempted, false otherwise



68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'documented/lich.rb', line 68

def self.db_maint_due?(months = 6)
  last = Lich.db_maint_last_at
  return true if last.nil? || last.empty?
  begin
    cutoff = Time.now.utc - (months * 30 * 24 * 60 * 60)
    last_t = Time.parse(last) rescue nil
    return true if last_t.nil?
    last_t < cutoff
  rescue => e
    Lich.log "db_maint_due? parse error: #{e}"
    true
  end
end

.db_maint_last_at ⇒ String?

Retrieves the timestamp of the last database maintenance operation.

Reads from the lich_settings table and retries on SQLite3::BusyException. Returns nil if the setting does not exist or if a read error occurs (other than busy contention).

Returns:

  • (String, nil) —

    ISO 8601 UTC timestamp, or nil if no maintenance has been recorded



24
25
26
27
28
29
30
31
32
33
34
35
# File 'documented/lich.rb', line 24

def self.db_maint_last_at
  ts = nil
  begin
    ts = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='db_maint_last_at';")
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  rescue => e
    Lich.log "db_maint_last_at error: #{e}"
  end
  ts
end

.db_maint_lock_path ⇒ Object

--- Minimal DB maintenance helpers (simple + safe) --- Stores last maintenance timestamp and summary in lich_settings. Uses an advisory OS file lock so only one Lich instance attempts VACUUM.



13
14
15
# File 'documented/lich.rb', line 13

def self.db_maint_lock_path
  File.join(DATA_DIR, 'lich.db3.maint.lock')
end

.db_maint_set!(iso_utc, note = '') ⇒ void

This method returns an undefined value.

Records a database maintenance operation with timestamp and optional summary.

Creates the lich_settings table if it does not exist, then writes the db_maint_last_at and db_maint_last_note settings via INSERT OR REPLACE. The note is UTF-8 encoded before storage. Retries on SQLite3::BusyException.

Parameters:

  • iso_utc (String) —

    ISO 8601 UTC timestamp (e.g., from Time.now.utc.iso8601)

  • note (String) (defaults to: '') —

    optional summary of the maintenance operation (default '')



46
47
48
49
50
51
52
53
54
55
56
57
# File 'documented/lich.rb', line 46

def self.db_maint_set!(iso_utc, note = '')
  begin
    Lich.db.execute("CREATE TABLE IF NOT EXISTS lich_settings (name TEXT NOT NULL, value TEXT, PRIMARY KEY(name));")
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name, value) VALUES('db_maint_last_at', ?);", [iso_utc])
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name, value) VALUES('db_maint_last_note', ?);", [note.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  rescue => e
    Lich.log "db_maint_set! error: #{e}"
  end
end

.db_mutex ⇒ Mutex

Returns the Mutex protecting access to Lich.db.

Returns:

  • (Mutex) —

    the shared database mutex



168
169
170
# File 'documented/lich.rb', line 168

def self.db_mutex
  @@db_mutex
end

.db_vacuum_if_due!(months: 6, lock_timeout_s: 0.5) ⇒ Object

Try VACUUM if due. If the DB is busy (another process), skip and try next run.



83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
# File 'documented/lich.rb', line 83

def self.db_vacuum_if_due!(months: 6, lock_timeout_s: 0.5)
  return :skipped_recent unless Lich.db_maint_due?(months)

  lock_path = Lich.db_maint_lock_path
  File.open(lock_path, File::RDWR | File::CREAT, 0o644) do |f|
    start = Time.now
    got = false
    begin
      got = f.flock(File::LOCK_EX | File::LOCK_NB)
    rescue => e
      Lich.log "db_maint flock error: #{e}"
    end
    unless got
      while (Time.now - start) < lock_timeout_s && !got
        sleep 0.1
        begin
          got = f.flock(File::LOCK_EX | File::LOCK_NB)
        rescue SystemCallError, IOError
          # Transient error acquiring lock on some filesystems; back off and retry.
          sleep 0.05
        end
      end
    end
    return :skipped_lock_held unless got

    begin
      page_count_before     = Lich.db.get_first_value('PRAGMA page_count;').to_i
      freelist_count_before = Lich.db.get_first_value('PRAGMA freelist_count;').to_i
    rescue SQLite3::BusyException
      Lich.log "db_maint: busy reading stats; skipping"
      return :skipped_busy
    end

    begin
      mode = Lich.db.get_first_value('PRAGMA journal_mode;')
      if mode && mode.to_s.strip.upcase == 'WAL'
        Lich.db.execute('PRAGMA wal_checkpoint(TRUNCATE);')
      end
    rescue SQLite3::SQLException => e
      Lich.log "db_maint: checkpoint skipped (#{e.class}: #{e.message})"
    end

    begin
      Lich.db.execute('VACUUM;')
    rescue SQLite3::BusyException => e
      Lich.log "db_maint: VACUUM busy; skipping (#{e.message})"
      return :skipped_busy
    rescue => e
      Lich.log "db_maint: VACUUM error: #{e}"
      return :error
    end

    page_count_after     = Lich.db.get_first_value('PRAGMA page_count;').to_i rescue 0
    freelist_count_after = Lich.db.get_first_value('PRAGMA freelist_count;').to_i rescue 0
    note = "VACUUM ok pages #{page_count_before}->#{page_count_after}, free #{freelist_count_before}->#{freelist_count_after}"
    Lich.db_maint_set!(Time.now.utc.iso8601, note)
    :vacuum_ok
  end
end

.debug_messaging ⇒ Boolean

Returns the debug messaging setting (cached).

Reads from lich_settings on first call and caches the result as a Boolean. Retries on SQLite3::BusyException.

Returns:

  • (Boolean) —

    true if debug messaging is enabled, false otherwise



1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
# File 'documented/lich.rb', line 1007

def self.debug_messaging
  if @@debug_messaging.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='debug_messaging';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@debug_messaging = (val.to_s =~ /on|true|yes/ ? true : false)
    Lich.debug_messaging = @@debug_messaging
  end
  return @@debug_messaging
end

.debug_messaging=(val) ⇒ void

This method returns an undefined value.

Enables or disables debug messaging.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings as UTF-8 encoded string. Updates the cache immediately. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes



1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'documented/lich.rb', line 1029

def self.debug_messaging=(val)
  @@debug_messaging = (val.to_s =~ /on|true|yes/ ? true : false)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('debug_messaging',?);", [@@debug_messaging.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.deprecated(old_object = '', new_object = '', script_location = "#{Script.current.name || 'unknown'}", debug_log: true, fe_log: false, limit_log: true) ⇒ void

This method returns an undefined value.

Records a deprecation warning for outdated script API usage.

Logs the warning to stderr (if debug_log is true) and optionally displays it in-game via Lich::Messaging (if fe_log is true). By default, each unique message is logged only once (limit_log: true) to avoid spam. The warning includes the calling script name.

Parameters:

  • old_object (String) (defaults to: '') —

    the deprecated method or variable name (default '')

  • new_object (String) (defaults to: '') —

    the recommended replacement (default '')

  • script_location (String) (defaults to: "#{Script.current.name || 'unknown'}") —

    the script calling the deprecated code (default current script name or 'unknown')

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

    whether to log to stderr (default true)

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

    whether to display in-game (default false)

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

    whether to suppress duplicate messages (default true)



347
348
349
350
351
352
353
# File 'documented/lich.rb', line 347

def self.deprecated(old_object = '', new_object = '', script_location = "#{Script.current.name || 'unknown'}", debug_log: true, fe_log: false, limit_log: true)
  msg = "Deprecated call to #{old_object} used in #{script_location}. Please change to #{new_object} instead!"
  return if limit_log && @@deprecated_log.include?(msg)
  Lich.log(msg) if debug_log
  Lich::Messaging.msg("bold", msg) if fe_log
  @@deprecated_log.push(msg) unless @@deprecated_log.include?(msg)
end

.display_exits ⇒ Boolean?

Returns whether room exits should be displayed in output.

Reads from lich_settings on first access and caches the result. Defaults to false when no value is stored and a game is identified. Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to display exits, false to hide them, or nil if no game identified



1373
1374
1375
1376
1377
1378
# File 'documented/lich.rb', line 1373

def self.display_exits
  read_display_setting(:display_exits) do |val|
    val = false if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_exits=(val) ⇒ Boolean, String

Sets whether room exits should be displayed in output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and retry cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1387
1388
1389
# File 'documented/lich.rb', line 1387

def self.display_exits=(val)
  write_display_setting(:display_exits, val.to_s.match?(/on|true|yes/))
end

.display_expgains ⇒ Boolean?

Returns whether experience gains should be displayed in output.

Reads from lich_settings on first access and caches the result. Defaults based on frontend: Genie defaults to false (off), others default to true (on). Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to display exp gains, false to hide them, or nil if no game identified



1472
1473
1474
1475
1476
1477
# File 'documented/lich.rb', line 1472

def self.display_expgains
  read_display_setting(:display_expgains) do |val|
    val = ($frontend == 'genie' ? 'false' : 'true') if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_expgains=(val) ⇒ Boolean, String

Sets whether experience gains should be displayed in output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and retry cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1486
1487
1488
# File 'documented/lich.rb', line 1486

def self.display_expgains=(val)
  write_display_setting(:display_expgains, val.to_s.match?(/on|true|yes/))
end

.display_lichid ⇒ Boolean?

Returns whether Lich IDs should be displayed in output.

Reads from lich_settings on first access and caches the result. Defaults to true for GemStone games, false for others, when no value is stored. Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to display Lich IDs, false to hide them, or nil if no game identified



1185
1186
1187
1188
1189
1190
# File 'documented/lich.rb', line 1185

def self.display_lichid
  read_display_setting(:display_lichid) do |val|
    val = (XMLData.game =~ /^GS/ ? true : false) if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_lichid=(val) ⇒ Boolean, String

Sets whether Lich IDs should be displayed in output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and retry cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1199
1200
1201
# File 'documented/lich.rb', line 1199

def self.display_lichid=(val)
  write_display_setting(:display_lichid, val.to_s.match?(/on|true|yes/))
end

Whether room exits are rendered as clickable command links (a tag) or as plain text in room-display output. Persisted in the lich_settings table and shared across characters. When no value has been saved yet, the default is game-aware: DragonRealms defaults to off (plain text, matching the retired roomnumbers.lic look) while GemStone and any other game default to on (clickable links, the pre-existing core behavior).

Returns:

  • (Boolean, nil) —

    true when exits should be clickable links; nil until the game is identified (XMLData.game still blank), matching the pre-existing display_* getters. Callers treat nil as falsy.



1425
1426
1427
1428
1429
1430
# File 'documented/lich.rb', line 1425

def self.display_room_links
  read_display_setting(:display_room_links) do |val|
    val = (XMLData.game =~ /^DR/ ? false : true) if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_room_links=(val) ⇒ Boolean, String

Sets and persists the room-exit link toggle.

Parameters:

  • val (Boolean, String) —

    truthy values are any of on/true/yes

Returns:

  • (Boolean, String) —

    the value passed in - Ruby assignment methods always return their argument, not the method body's result



1436
1437
1438
# File 'documented/lich.rb', line 1436

def self.display_room_links=(val)
  write_display_setting(:display_room_links, val.to_s.match?(/on|true|yes/))
end

.display_room_mono ⇒ Boolean?

Whether the Lich-injected room lines (Room Number, Room Exits, StringProcs) are wrapped in the fixed-width mono style. Persisted in the lich_settings table and shared across characters. When no value has been saved yet, the default is game-aware: DragonRealms defaults to on (mono, matching the retired roomnumbers.lic look) while GemStone and any other game default to off (the proportional game font, the pre-existing core behavior). The mono wrapper is only emitted on mono-capable frontends (see Frontend.supports_mono?).

Returns:

  • (Boolean, nil) —

    true when the lines should render in the mono style; nil until the game is identified (XMLData.game still blank), matching the pre-existing display_* getters. Callers treat nil as falsy.



1450
1451
1452
1453
1454
1455
# File 'documented/lich.rb', line 1450

def self.display_room_mono
  read_display_setting(:display_room_mono) do |val|
    val = (XMLData.game =~ /^DR/ ? true : false) if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_room_mono=(val) ⇒ Boolean, String

Sets and persists the room-line mono-font toggle.

Parameters:

  • val (Boolean, String) —

    truthy values are any of on/true/yes

Returns:

  • (Boolean, String) —

    the value passed in - Ruby assignment methods always return their argument, not the method body's result



1461
1462
1463
# File 'documented/lich.rb', line 1461

def self.display_room_mono=(val)
  write_display_setting(:display_room_mono, val.to_s.match?(/on|true|yes/))
end

.display_roomid_location ⇒ String?

Where DragonRealms renders the optional room id / UID chosen via ;display lichid and ;display uid: "title" injects into the room-name line (visible on every front-end), "line" is the historical "Room Number:" line below the room, and "both" does both. GemStone ignores this setting (it always injects into the title line). The value is read fresh from the lich_settings table on first access and then memoized.

Returns:

  • (String, nil) —

    one of ROOMID_LOCATIONS, or nil before a game has been identified



1347
1348
1349
1350
1351
1352
# File 'documented/lich.rb', line 1347

def self.display_roomid_location
  read_display_setting(:display_roomid_location) do |val|
    val = "line" if val.nil? && XMLData.game != ""
    val.nil? ? nil : (ROOMID_LOCATIONS.include?(val) ? val : "line")
  end
end

.display_roomid_location=(val) ⇒ void

This method returns an undefined value.

Sets the DragonRealms room-id display placement and persists it. An unrecognized value is ignored (the current setting is retained) so a typo can never blank the display or feed the renderer an invalid placement.

Parameters:

  • val (String, Symbol) —

    one of ROOMID_LOCATIONS ("title", "line", or "both"); case-insensitive



1359
1360
1361
1362
1363
1364
# File 'documented/lich.rb', line 1359

def self.display_roomid_location=(val)
  normalized = val.to_s.downcase
  return unless ROOMID_LOCATIONS.include?(normalized)

  write_display_setting(:display_roomid_location, normalized)
end

.display_stringprocs ⇒ Boolean?

Returns whether StringProcs should be displayed in output.

Reads from lich_settings on first access and caches the result. Defaults to false when no value is stored and a game is identified. Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to display StringProcs, false to hide them, or nil if no game identified



1398
1399
1400
1401
1402
1403
# File 'documented/lich.rb', line 1398

def self.display_stringprocs
  read_display_setting(:display_stringprocs) do |val|
    val = false if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_stringprocs=(val) ⇒ Boolean, String

Sets whether StringProcs should be displayed in output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and retry cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1412
1413
1414
# File 'documented/lich.rb', line 1412

def self.display_stringprocs=(val)
  write_display_setting(:display_stringprocs, val.to_s.match?(/on|true|yes/))
end

.display_uid ⇒ Boolean?

Returns whether UIDs (unique identifiers) should be displayed in output.

Reads from lich_settings on first access and caches the result. Defaults to true for GemStone games, false for others, when no value is stored. Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to display UIDs, false to hide them, or nil if no game identified



1319
1320
1321
1322
1323
1324
# File 'documented/lich.rb', line 1319

def self.display_uid
  read_display_setting(:display_uid) do |val|
    val = (XMLData.game =~ /^GS/ ? true : false) if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.display_uid=(val) ⇒ Boolean, String

Sets whether UIDs should be displayed in output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and triggers automatic subtitle UID cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1334
1335
1336
# File 'documented/lich.rb', line 1334

def self.display_uid=(val)
  write_display_setting(:display_uid, val.to_s.match?(/on|true|yes/))
end

.enable_display_uid_automatically ⇒ Object

Explicit setters bypass this cooldown and clear it after a successful save.



1174
1175
1176
# File 'documented/lich.rb', line 1174

def self.enable_display_uid_automatically
  write_display_setting(:display_uid, true, automatic: true)
end

.find_hosts_file ⇒ String, Boolean

Locates the hosts file on the current system.

On Windows, queries the registry for the TCP/IP database path or searches standard Windows locations (C:\windows\system32\drivers\etc\hosts, etc.). On macOS/Linux, checks /etc/hosts and /private/etc/hosts. Caches and returns the result, or false if not found.

Returns:

  • (String, Boolean) —

    the hosts file path, or false if not found



774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
# File 'documented/lich.rb', line 774

def self.find_hosts_file
  if defined?(Win32)
    begin
      key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'System\\CurrentControlSet\\Services\\Tcpip\\Parameters', :samDesired => Win32::KEY_READ)[:phkResult]
      hosts_path = Win32.RegQueryValueEx(:hKey => key, :lpValueName => 'DataBasePath')[:lpData]
    ensure
      Win32.RegCloseKey(:hKey => key) rescue nil
    end
    if hosts_path
      windir = (ENV['windir'] || ENV['SYSTEMROOT'] || 'c:\windows')
      hosts_path = hosts_path.gsub(/%SystemRoot%/i, windir)
      hosts_file = "#{hosts_path}\\hosts"
      if File.exist?(hosts_file)
        return (@@hosts_file = hosts_file)
      end
    end
    if (windir = (ENV['windir'] || ENV['SYSTEMROOT'])) and File.exist?("#{windir}\\system32\\drivers\\etc\\hosts")
      return (@@hosts_file = "#{windir}\\system32\\drivers\\etc\\hosts")
    end

    for drive in ['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
      for windir in ['winnt', 'windows']
        if File.exist?("#{drive}:\\#{windir}\\system32\\drivers\\etc\\hosts")
          return (@@hosts_file = "#{drive}:\\#{windir}\\system32\\drivers\\etc\\hosts")
        end
      end
    end
  else # Linux/Mac
    if File.exist?('/etc/hosts')
      return (@@hosts_file = '/etc/hosts')
    elsif File.exist?('/private/etc/hosts')
      return (@@hosts_file = '/private/etc/hosts')
    end
  end
  return (@@hosts_file = false)
end

.fix_game_host_port(gamehost, gameport) ⇒ Array(String, Integer)

Normalizes game server host and port for known redirects.

Maps legacy game server addresses to their current Storm endpoints: gs-plat.simutronics.net:10121 → storm.gs4.game.play.net:10124 (Platinum) gs3.simutronics.net:4900 → storm.gs4.game.play.net:10024 (Prime) gs4.simutronics.net:10321 → storm.gs4.game.play.net:10324 (Shattered) prime.dr.game.play.net:4901 → dr.simutronics.net:11024 (DragonRealms Prime)

Parameters:

  • gamehost (String) —

    the game server hostname

  • gameport (Integer, #to_i) —

    the game server port

Returns:

  • (Array(String, Integer)) —

    the normalized [gamehost, gameport] pair



957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
# File 'documented/lich.rb', line 957

def self.fix_game_host_port(gamehost, gameport)
  if (gamehost == 'gs-plat.simutronics.net') and (gameport.to_i == 10121)
    gamehost = 'storm.gs4.game.play.net'
    gameport = 10124
  elsif (gamehost == 'gs3.simutronics.net') and (gameport.to_i == 4900)
    gamehost = 'storm.gs4.game.play.net'
    gameport = 10024
  elsif (gamehost == 'gs4.simutronics.net') and (gameport.to_i == 10321)
    gamehost = 'storm.gs4.game.play.net'
    gameport = 10324
  elsif (gamehost == 'prime.dr.game.play.net') and (gameport.to_i == 4901)
    gamehost = 'dr.simutronics.net'
    gameport = 11024
  end
  [gamehost, gameport]
end

.follow_description_flag ⇒ Boolean?

Whether the client gets the character's room view without its description while DragonRealms' FLAG DESCRIPTION is OFF (";display descflag"). Works around the Saga-identity stream ignoring the flag; see Lich::Common::RoomDescriptionFilter. Off by default.

Returns:

  • (Boolean, nil) —

    nil until a game is identified and no value is stored



1233
1234
1235
1236
1237
1238
# File 'documented/lich.rb', line 1233

def self.follow_description_flag
  read_display_setting(:follow_description_flag) do |val|
    val = false if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.follow_description_flag=(val) ⇒ Object

Sets and persists the room description filter toggle.

Parameters:

  • val (Boolean, String) —

    truthy values are any of on/true/yes



1242
1243
1244
# File 'documented/lich.rb', line 1242

def self.follow_description_flag=(val)
  write_display_setting(:follow_description_flag, val.to_s.match?(/on|true|yes/))
end

.get_simu_launcher ⇒ String?

Retrieves the Simutronics launcher command from the system registry.

On Windows, queries HKEY_LOCAL_MACHINE\Software\Classes\Simutronics.Autolaunch\Shell\Open\command. On Linux/Mac with Wine, queries the equivalent Wine registry key. Returns nil on unsupported platforms or if the registry key is not found.

Returns:

  • (String, nil) —

    the launcher command path, or nil if not available



464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
# File 'documented/lich.rb', line 464

def self.get_simu_launcher
  if defined?(Win32)
    begin
      launcher_key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command', :samDesired => (Win32::KEY_ALL_ACCESS | Win32::KEY_WOW64_32KEY))[:phkResult]
      launcher_cmd = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'RealCommand')[:lpData]
      if launcher_cmd.nil? or launcher_cmd.empty?
        launcher_cmd = Win32.RegQueryValueEx(:hKey => launcher_key)[:lpData]
      end
      return launcher_cmd
    ensure
      Win32.RegCloseKey(:hKey => launcher_key) rescue nil
    end
  elsif defined?(Wine)
    launcher_cmd = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\RealCommand')
    unless launcher_cmd and not launcher_cmd.empty?
      launcher_cmd = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\')
    end
    return launcher_cmd
  else
    return nil
  end
end

.hide_uid_flag ⇒ Boolean?

Returns whether the UID flag should be hidden from output.

Reads from lich_settings on first access and caches the result. Defaults to false when no value is stored and a game is identified. Returns nil before any game is identified.

Returns:

  • (Boolean, nil) —

    true to hide the UID flag, false to show it, or nil if no game identified



1210
1211
1212
1213
1214
1215
# File 'documented/lich.rb', line 1210

def self.hide_uid_flag
  read_display_setting(:hide_uid_flag) do |val|
    val = false if val.nil? && XMLData.game != ""
    val.nil? ? nil : val.to_s.match?(/on|true|yes/)
  end
end

.hide_uid_flag=(val) ⇒ Boolean, String

Sets whether the UID flag should be hidden from output.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings. Clears the display cache and retry cooldown on save.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes

Returns:

  • (Boolean, String) —

    the normalized value passed in



1224
1225
1226
# File 'documented/lich.rb', line 1224

def self.hide_uid_flag=(val)
  write_display_setting(:hide_uid_flag, val.to_s.match?(/on|true|yes/))
end

.hosts_file ⇒ String, Boolean

Returns the path to the system hosts file.

Caches the result after the first lookup. Calls find_hosts_file to locate it if not already cached.

Returns:

  • (String, Boolean) —

    the hosts file path, or false if not found



761
762
763
764
# File 'documented/lich.rb', line 761

def self.hosts_file
  Lich.find_hosts_file if @@hosts_file.nil?
  return @@hosts_file
end

.init_db ⇒ void

This method returns an undefined value.

Initializes the Lich database schema on first run.

Creates all core tables if they do not exist: script_setting, script_auto_settings, lich_settings, uservars, session_summary_state, and indexes. Applies idempotent ALTER TABLE statements for backward-compatible migration (tolerating duplicate column errors). Retries on SQLite3::BusyException.

Called once at Lich startup to ensure the database structure is ready.



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
# File 'documented/lich.rb', line 258

def self.init_db
  begin
    Lich.db.execute("CREATE TABLE IF NOT EXISTS script_setting (script TEXT NOT NULL, name TEXT NOT NULL, value BLOB, PRIMARY KEY(script, name));")
    Lich.db.execute("CREATE TABLE IF NOT EXISTS script_auto_settings (script TEXT NOT NULL, scope TEXT, hash BLOB, PRIMARY KEY(script, scope));")
    Lich.db.execute("CREATE TABLE IF NOT EXISTS lich_settings (name TEXT NOT NULL, value TEXT, PRIMARY KEY(name));")
    Lich.db.execute("CREATE TABLE IF NOT EXISTS uservars (scope TEXT NOT NULL, hash BLOB, PRIMARY KEY(scope));")
    # Session summary reporting table for process-level heartbeat metadata.
    # This schema is initialized with the rest of core DB setup to avoid
    # runtime DDL lock contention on first adapter access.
    Lich.db.execute("CREATE TABLE IF NOT EXISTS session_summary_state (pid INTEGER PRIMARY KEY, session_name TEXT, role TEXT, state TEXT, frontend TEXT, game_code TEXT, hidden INTEGER DEFAULT 0, started_at INTEGER, last_heartbeat_at INTEGER, os_seen_at INTEGER, os_seen INTEGER, os_name INTEGER, last_utilization_at INTEGER, metadata_json TEXT);")
    Lich.db.execute("CREATE INDEX IF NOT EXISTS idx_session_summary_state_session_name ON session_summary_state(session_name);")
    Lich.db.execute("CREATE INDEX IF NOT EXISTS idx_session_summary_state_heartbeat ON session_summary_state(last_heartbeat_at);")
    # Backward-compatible migration guards:
    # In dev/test transitions, older local tables may be missing newer columns.
    # We keep these ALTER blocks idempotent by tolerating duplicate-column errors.
    begin
      Lich.db.execute("ALTER TABLE session_summary_state ADD COLUMN os_seen_at INTEGER;")
    rescue SQLite3::SQLException => e
      raise unless e.message.include?('duplicate column name')
    end
    begin
      Lich.db.execute("ALTER TABLE session_summary_state ADD COLUMN os_seen INTEGER;")
    rescue SQLite3::SQLException => e
      raise unless e.message.include?('duplicate column name')
    end
    begin
      Lich.db.execute("ALTER TABLE session_summary_state ADD COLUMN os_name INTEGER;")
    rescue SQLite3::SQLException => e
      raise unless e.message.include?('duplicate column name')
    end
    if (RUBY_VERSION =~ /^2\.[012]\./)
      Lich.db.execute("CREATE TABLE IF NOT EXISTS trusted_scripts (name TEXT NOT NULL);")
    end
    Lich.db.execute("CREATE TABLE IF NOT EXISTS simu_game_entry (character TEXT NOT NULL, game_code TEXT NOT NULL, data BLOB, PRIMARY KEY(character, game_code));")
    Lich.db.execute("CREATE TABLE IF NOT EXISTS enable_inventory_boxes (player_id INTEGER NOT NULL, PRIMARY KEY(player_id));")
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.inventory_boxes(player_id) ⇒ Boolean

Checks whether inventory boxes are enabled for a player.

Queries the enable_inventory_boxes table and retries on SQLite3::BusyException.

Parameters:

  • player_id (Integer, #to_i) —

    the player ID

Returns:

  • (Boolean) —

    true if inventory boxes are enabled for this player, false otherwise



874
875
876
877
878
879
880
881
882
883
884
885
886
# File 'documented/lich.rb', line 874

def self.inventory_boxes(player_id)
  begin
    v = Lich.db.get_first_value('SELECT player_id FROM enable_inventory_boxes WHERE player_id=?;', [player_id.to_i])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
  if v
    true
  else
    false
  end
end

.keep_fe_string ⇒ Boolean

Whether Lich's proxy forwards a front end's own /FE: handshake instead of replacing it with Lich's client string (Frontend.proxy_handshake). The kill switch for that replacement; the --keep-fe-string flag does the same for one launch. Persisted in the lich_settings table, shared across characters, read at the handshake. Default false, also when the read fails.

Returns:

  • (Boolean)


1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
# File 'documented/lich.rb', line 1252

def self.keep_fe_string
  if @@keep_fe_string.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='keep_fe_string';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@keep_fe_string = val.to_s.strip.match?(/\A(?:on|true|yes)\z/i)
  end
  @@keep_fe_string
rescue StandardError => e
  # Read on the login path: a settings failure must not stop the handshake.
  Lich.log "warning: could not read keep_fe_string, replacing the client string: #{e}"
  false
end

.keep_fe_string=(val) ⇒ Object

Sets and persists the handshake kill switch; takes effect at the next login.

Parameters:

  • val (Boolean, String) —

    true, or any of on/true/yes



1271
1272
1273
1274
1275
1276
1277
1278
1279
# File 'documented/lich.rb', line 1271

def self.keep_fe_string=(val)
  @@keep_fe_string = val.to_s.strip.match?(/\A(?:on|true|yes)\z/i)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('keep_fe_string',?);", [@@keep_fe_string.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

Integrates Lich into the Simutronics Autolaunch (SAL) protocol on Windows.

Modifies the registry to handle Simutronics.Autolaunch URIs (SAL links) by routing them through Lich before launching the game. Requires administrator privileges; attempts elevation via ShellExecuteEx if run without admin.

Returns:

  • (Boolean) —

    true if successfully linked or already linked, false on error



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
# File 'documented/lich.rb', line 629

def self.link_to_sal
  if defined?(Win32)
    if Win32.admin?
      begin
        # fixme: 64 bit browsers?
        launcher_key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command', :samDesired => (Win32::KEY_ALL_ACCESS | Win32::KEY_WOW64_32KEY))[:phkResult]
        r = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'RealCommand')
        if (r[:return] == 0) and not r[:lpData].empty?
          # already linked
          return true
        end

        r = Win32.GetModuleFileName
        unless r[:return] > 0
          # fixme
          return false
        end

        new_launcher_cmd = "\"#{r[:lpFilename]}\" \"#{File.expand_path($PROGRAM_NAME)}\" %1"
        r = Win32.RegQueryValueEx(:hKey => launcher_key)
        launcher_cmd = r[:lpData]
        r = Win32.RegSetValueEx(:hKey => launcher_key, :lpValueName => 'RealCommand', :dwType => Win32::REG_SZ, :lpData => launcher_cmd)
        return false unless (r == 0)

        r = Win32.RegSetValueEx(:hKey => launcher_key, :dwType => Win32::REG_SZ, :lpData => new_launcher_cmd)
        return (r == 0)
      ensure
        Win32.RegCloseKey(:hKey => launcher_key) rescue nil
      end
    else
      begin
        r = Win32.GetModuleFileName
        file = ((r[:return] > 0) ? r[:lpFilename] : 'rubyw.exe')
        params = "#{$PROGRAM_NAME.split(/\/|\\/).last} --link-to-sal"
        r = Win32.ShellExecuteEx(:lpVerb => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params, :fMask => Win32::SEE_MASK_NOCLOSEPROCESS)
        if r[:return] > 0
          process_id = r[:hProcess]
          sleep 0.2 while Win32.GetExitCodeProcess(:hProcess => process_id)[:lpExitCode] == Win32::STILL_ACTIVE
          sleep 3
        else
          Win32.ShellExecute(:lpOperation => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params)
          sleep 6
        end
      rescue
        Lich.msgbox(:message => $!)
      end
    end
  elsif defined?(Wine)
    launch_cmd = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\')
    return false unless launch_cmd

    new_launch_cmd = "#{File.expand_path($PROGRAM_NAME)} --wine=#{Wine::BIN} --wine-prefix=#{Wine::PREFIX} %1"
    result = true
    if launch_cmd
      if launch_cmd =~ /lich/i
        $stdout.puts "--- warning: Lich appears to already be installed to the registry"
        Lich.log "warning: Lich appears to already be installed to the registry"
        Lich.log 'info: launch_cmd: ' + launch_cmd
      else
        result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\RealCommand', launch_cmd)
        result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\', new_launch_cmd)
      end
    end
    return result
  else
    return false
  end
end

Integrates Lich into the Simutronics Game Entry (SGE) launcher on Windows.

Requires administrator privileges. Modifies the registry to redirect the SGE launcher to launch Lich, then Lich launches the game. Returns false if already linked or if the operation fails (insufficient privileges, registry errors, etc.).

On Windows without admin, attempts elevation via ShellExecuteEx with 'runas' verb. On Wine/Linux, updates the Wine registry equivalently.

Returns:

  • (Boolean) —

    true if successfully linked or already linked, false on error



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
# File 'documented/lich.rb', line 497

def self.link_to_sge
  if defined?(Win32)
    if Win32.admin?
      begin
        launcher_key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'Software\\Simutronics\\Launcher', :samDesired => (Win32::KEY_ALL_ACCESS | Win32::KEY_WOW64_32KEY))[:phkResult]
        r = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'RealDirectory')
        if (r[:return] == 0) and not r[:lpData].empty?
          # already linked
          return true
        end

        r = Win32.GetModuleFileName
        unless r[:return] > 0
          # fixme
          return false
        end

        new_launcher_dir = "\"#{r[:lpFilename]}\" \"#{File.expand_path($PROGRAM_NAME)}\" "
        r = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'Directory')
        launcher_dir = r[:lpData]
        r = Win32.RegSetValueEx(:hKey => launcher_key, :lpValueName => 'RealDirectory', :dwType => Win32::REG_SZ, :lpData => launcher_dir)
        return false unless (r == 0)

        r = Win32.RegSetValueEx(:hKey => launcher_key, :lpValueName => 'Directory', :dwType => Win32::REG_SZ, :lpData => new_launcher_dir)
        return (r == 0)
      ensure
        Win32.RegCloseKey(:hKey => launcher_key) rescue nil
      end
    else
      begin
        r = Win32.GetModuleFileName
        file = ((r[:return] > 0) ? r[:lpFilename] : 'rubyw.exe')
        params = "#{$PROGRAM_NAME.split(/\/|\\/).last} --link-to-sge"
        r = Win32.ShellExecuteEx(:lpVerb => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params, :fMask => Win32::SEE_MASK_NOCLOSEPROCESS)
        if r[:return] > 0
          process_id = r[:hProcess]
          sleep 0.2 while Win32.GetExitCodeProcess(:hProcess => process_id)[:lpExitCode] == Win32::STILL_ACTIVE
          sleep 3
        else
          Win32.ShellExecute(:lpOperation => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params)
          sleep 6
        end
      rescue
        Lich.msgbox(:message => $!)
      end
    end
  elsif defined?(Wine)
    launch_dir = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\Directory')
    return false unless launch_dir

    lich_launch_dir = "#{File.expand_path($PROGRAM_NAME)} --wine=#{Wine::BIN} --wine-prefix=#{Wine::PREFIX}  "
    result = true
    if launch_dir
      if launch_dir =~ /lich/i
        $stdout.puts "--- warning: Lich appears to already be installed to the registry"
        Lich.log "warning: Lich appears to already be installed to the registry"
        Lich.log 'info: launch_dir: ' + launch_dir
      else
        result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\RealDirectory', launch_dir)
        result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\Directory', lich_launch_dir)
      end
    end
    return result
  else
    return false
  end
end

.log(msg) ⇒ void

This method returns an undefined value.

Writes a timestamped message to stderr.

Used internally by Lich to log debug, error, and informational messages. The timestamp is in YYYY-MM-DD HH:MM:SS format (UTC).

Parameters:

  • msg (String) —

    the message to log



330
331
332
# File 'documented/lich.rb', line 330

def self.log(msg)
  $stderr.puts "#{Time.now.strftime("%Y-%m-%d %H:%M:%S")}: #{msg}"
end

.max_debug_logs ⇒ Integer

Returns the maximum number of debug log files to retain in the temp directory. The value is lazily loaded from the lich_settings database table on first access, then cached in a class variable for subsequent calls. When no persisted value exists, falls back to MAX_DEBUG_LOGS_DEFAULT.

Examples:

Query the current setting in-game

;e respond Lich.max_debug_logs

Returns:

See Also:



1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
# File 'documented/lich.rb', line 1655

def self.max_debug_logs
  if @@max_debug_logs.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='max_debug_logs';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@max_debug_logs = val.nil? ? MAX_DEBUG_LOGS_DEFAULT : [val.to_i, MAX_DEBUG_LOGS_MINIMUM].max
  end
  @@max_debug_logs
end

.max_debug_logs=(val) ⇒ void

This method returns an undefined value.

Persists the maximum number of debug log files to retain. Values below MAX_DEBUG_LOGS_MINIMUM are clamped to prevent accidental deletion of all logs.

Examples:

Set retention to 50 files in-game

;e Lich.max_debug_logs = 50

Parameters:

  • val (#to_i) —

    the desired retention limit

See Also:



1680
1681
1682
1683
1684
1685
1686
1687
1688
# File 'documented/lich.rb', line 1680

def self.max_debug_logs=(val)
  @@max_debug_logs = [val.to_i, MAX_DEBUG_LOGS_MINIMUM].max
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('max_debug_logs',?);", [@@max_debug_logs.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.method_missing(arg1, arg2 = '') ⇒ 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.

Delegates deprecated Lich.* variable access to Vars.*.

Emits a deprecation warning (at most once per 5 minutes) directing script authors to use Vars instead. Calls are delegated transparently to Vars.method_missing.

Parameters:

  • arg1 (Object) —

    the variable name or method call

  • arg2 (String) (defaults to: '') —

    optional secondary argument (default '')

Returns:

  • (Object) —

    the result of delegating to Vars



211
212
213
214
215
216
217
# File 'documented/lich.rb', line 211

def self.method_missing(arg1, arg2 = '')
  if (Time.now.to_i - @@last_warn_deprecated) > 300
    respond "--- warning: Lich.* variables will stop working in a future version of Lich.  Use Vars.* (offending script: #{Script.current.name || 'unknown'})"
    @@last_warn_deprecated = Time.now.to_i
  end
  Vars.method_missing(arg1, arg2)
end

.modify_hosts(game_host) ⇒ Boolean

Adds a localhost entry to the hosts file for testing purposes.

Backs up the current hosts file to hosts.bak, then appends a line mapping game_host to 127.0.0.1. Restores the backup on exit. Returns false if the hosts file does not exist or if a backup already exists.

Parameters:

  • game_host (String) —

    the game hostname to redirect to localhost

Returns:

  • (Boolean) —

    true on success, false if hosts file not found or backup exists



819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
# File 'documented/lich.rb', line 819

def self.modify_hosts(game_host)
  if Lich.hosts_file and File.exist?(Lich.hosts_file)
    at_exit { Lich.restore_hosts }
    Lich.restore_hosts
    if File.exist?("#{Lich.hosts_file}.bak")
      return false
    end

    begin
      # copy hosts to hosts.bak
      File.open("#{Lich.hosts_file}.bak", 'w') { |hb| File.open(Lich.hosts_file) { |h| hb.write(h.read) } }
    rescue
      File.unlink("#{Lich.hosts_file}.bak") if File.exist?("#{Lich.hosts_file}.bak")
      return false
    end
    File.open(Lich.hosts_file, 'a') { |f| f.write "\r\n127.0.0.1\t\t#{game_host}" }
    return true
  else
    return false
  end
end

.module_eval(*_a) ⇒ nil

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.

Disabled stub for module evaluation.

Always returns nil. Prevents scripts from calling Lich.module_eval.

Returns:

  • (nil)


321
# File 'documented/lich.rb', line 321

def self.module_eval(*_a); nil; end

.msgbox(args) ⇒ Symbol?

Displays a modal message box with optional buttons and icon.

On Windows (Win32), uses native MessageBox; on Linux/Mac with Gtk, uses a Gtk dialog; otherwise writes to stdout. Accepts a String (converted to message) or a Hash with keys: :message, :buttons, :icon, :title.

:buttons may be :ok, :ok_cancel, or :yes_no; :icon may be :error, :question, :warning, or omitted. The title defaults to "Lich vVERSION".

Examples:

Show a simple message

Lich.msgbox("Script finished.")

Show a yes/no dialog

response = Lich.msgbox(message: "Continue?", buttons: :yes_no, icon: :question, title: "Confirm")
respond response.to_s

Parameters:

  • args (String, Hash) —

    either a message string or options hash

Returns:

  • (Symbol, nil) —

    :ok, :cancel, :yes, :no, or nil (if dismissed or unsupported platform)



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
# File 'documented/lich.rb', line 382

def self.msgbox(args)
  args = { message: args.to_s } unless args.is_a?(Hash)
  if defined?(Win32)
    if args[:buttons] == :ok_cancel
      buttons = Win32::MB_OKCANCEL
    elsif args[:buttons] == :yes_no
      buttons = Win32::MB_YESNO
    else
      buttons = Win32::MB_OK
    end
    if args[:icon] == :error
      icon = Win32::MB_ICONERROR
    elsif args[:icon] == :question
      icon = Win32::MB_ICONQUESTION
    elsif args[:icon] == :warning
      icon = Win32::MB_ICONWARNING
    else
      icon = 0
    end
    args[:title] ||= "Lich v#{LICH_VERSION}"
    r = Win32.MessageBox(:lpText => args[:message], :lpCaption => args[:title], :uType => (buttons | icon))
    if r == Win32::IDIOK
      return :ok
    elsif r == Win32::IDICANCEL
      return :cancel
    elsif r == Win32::IDIYES
      return :yes
    elsif r == Win32::IDINO
      return :no
    else
      return nil
    end
  elsif defined?(Gtk)
    if args[:buttons] == :ok_cancel
      buttons = :ok_cancel
    elsif args[:buttons] == :yes_no
      buttons = :yes_no
    else
      buttons = :ok
    end
    if args[:icon] == :error
      type = :error
    elsif args[:icon] == :question
      type = :question
    elsif args[:icon] == :warning
      type = :warning
    else
      type = :info
    end
    dialog = Gtk::MessageDialog.new(parent: nil, flags: :modal, type: type, buttons: buttons, message: args[:message])
    args[:title] ||= "Lich v#{LICH_VERSION}"
    dialog.title = args[:title]
    begin
      # GTK3 returns the response; it does not yield to a block passed to run.
      response = dialog.run
    ensure
      dialog.destroy
    end
    if response == Gtk::ResponseType::OK
      return :ok
    elsif response == Gtk::ResponseType::CANCEL
      return :cancel
    elsif response == Gtk::ResponseType::YES
      return :yes
    elsif response == Gtk::ResponseType::NO
      return :no
    else
      return nil
    end
  elsif $stdout.isatty
    $stdout.puts(args[:message])
    return nil
  end
end

.mutex_lock ⇒ void

This method returns an undefined value.

Acquires the database mutex if not already owned by the current thread.

Logs errors to stderr and sends a respond message on acquisition failure. Does nothing if the mutex is already held by this thread.



178
179
180
181
182
183
184
185
# File 'documented/lich.rb', line 178

def self.mutex_lock
  begin
    self.db_mutex.lock unless self.db_mutex.owned?
  rescue StandardError
    respond "--- Lich: error: Lich.mutex_lock: #{$!}"
    Lich.log "error: Lich.mutex_lock: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
end

.mutex_unlock ⇒ void

This method returns an undefined value.

Releases the database mutex if currently owned by the calling thread.

Logs errors to stderr and sends a respond message on release failure. Does nothing if the mutex is not currently owned by this thread.



193
194
195
196
197
198
199
200
# File 'documented/lich.rb', line 193

def self.mutex_unlock
  begin
    self.db_mutex.unlock if self.db_mutex.owned?
  rescue StandardError
    respond "--- Lich: error: Lich.mutex_unlock: #{$!}"
    Lich.log "error: Lich.mutex_unlock: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
  end
end

.open_sequel_sqlite(path) ⇒ Object

Opens lich.db3 through Sequel. Sequel's pool hands each thread its own connection, and every connection it creates gets a busy handler that waits with Ruby's sleep (see SQLiteBusyWait). timeout: is the C busy timeout Sequel sets first; it stays in force if the Ruby handler can't be installed. pool_timeout: is Lich.sqlite_pool_timeout_s.



79
80
81
82
83
84
85
86
87
88
# File 'documented/common/sqlite_connection.rb', line 79

def self.open_sequel_sqlite(path)
  timeout_ms = sqlite_busy_timeout_ms.to_i
  db = Sequel.sqlite(
    path,
    timeout: timeout_ms,
    pool_timeout: sqlite_pool_timeout_s,
    after_connect: ->(conn) { SQLiteBusyWait.install(conn, timeout_ms) }
  )
  db.extend(SQLiteBusyWait::Transactions)
end

.open_sqlite_db(path) ⇒ SQLite3::Database

Opens a raw SQLite3::Database connection with Lich's busy handler installed.

Parameters:

  • path (String) —

    file path to the SQLite database

Returns:

  • (SQLite3::Database) —

    the opened and configured connection



36
37
38
# File 'documented/common/sqlite_connection.rb', line 36

def self.open_sqlite_db(path)
  configure_sqlite_connection(SQLite3::Database.new(path))
end

.restore_hosts ⇒ void

This method returns an undefined value.

Restores the hosts file from backup (hosts.bak).

Called automatically on exit if modify_hosts was used. Replaces the current hosts file with the backed-up version and removes the .bak file. Exits with code 1 and logs the error if restoration fails.



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

def self.restore_hosts
  if Lich.hosts_file and File.exist?(Lich.hosts_file)
    begin
      # fixme: use rename instead?  test rename on windows
      if File.exist?("#{Lich.hosts_file}.bak")
        File.open("#{Lich.hosts_file}.bak") { |infile|
          File.open(Lich.hosts_file, 'w') { |outfile|
            outfile.write(infile.read)
          }
        }
        File.unlink "#{Lich.hosts_file}.bak"
      end
    rescue
      $stdout.puts "--- error: restore_hosts: #{$!}"
      Lich.log "error: restore_hosts: #{$!}\n\t#{$!.backtrace.join("\n\t")}"
      exit(1)
    end
  end
end

.seek(fe) ⇒ String?

Locates the installation path for a game front-end by name.

Uses Lich::Common::FrontendLocator if available; falls back to legacy global variables ($wiz_fe_loc, $sf_fe_loc) for Wizard and Stormfront respectively.

Parameters:

  • fe (String) —

    front-end identifier (e.g., "wizard", "stormfront")

Returns:

  • (String, nil) —

    the front-end installation path, or nil if not found



226
227
228
229
230
231
232
233
234
235
# File 'documented/lich.rb', line 226

def self.seek(fe)
  if defined?(Lich::Common::FrontendLocator)
    return Lich::Common::FrontendLocator.compatibility_location(fe)
  end

  return $wiz_fe_loc if fe =~ /wizard/
  return $sf_fe_loc if fe =~ /stormfront/

  nil
end

.set_inventory_boxes(player_id, enabled) ⇒ nil

Enables or disables inventory boxes for a player.

Inserts a row into enable_inventory_boxes if enabled is true, or deletes the row if false. Retries on SQLite3::BusyException.

Parameters:

  • player_id (Integer, #to_i) —

    the player ID

  • enabled (Boolean) —

    true to enable, false to disable

Returns:

  • (nil)


896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
# File 'documented/lich.rb', line 896

def self.set_inventory_boxes(player_id, enabled)
  if enabled
    begin
      Lich.db.execute('INSERT OR REPLACE INTO enable_inventory_boxes values(?);', [player_id.to_i])
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
  else
    begin
      Lich.db.execute('DELETE FROM enable_inventory_boxes where player_id=?;', [player_id.to_i])
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
  end
  nil
end

.show_deprecated_log ⇒ void

This method returns an undefined value.

Displays all recorded deprecation warnings to the game window.

Iterates over the internal deprecation log and responds with each message.



360
361
362
363
364
# File 'documented/lich.rb', line 360

def self.show_deprecated_log
  @@deprecated_log.each do |msg|
    respond(msg)
  end
end

.sqlite_busy_timeout_ms ⇒ Integer

Returns the timeout in milliseconds for SQLite lock waits.

Returns:

  • (Integer) —

    milliseconds to wait before timing out a lock acquisition



17
18
19
# File 'documented/common/sqlite_connection.rb', line 17

def self.sqlite_busy_timeout_ms
  DEFAULT_SQLITE_BUSY_TIMEOUT_MS
end

.sqlite_pool_timeout_s ⇒ Object

Seconds a thread waits for a free connection from the lich.db3 Sequel pool.

Threads holding pooled connections wait for the lock side by side, each for up to the busy timeout, and keep their connections meanwhile. With Sequel's default pool timeout (5 s, the same as the busy timeout) a thread queued behind them timed out on the pool at about the moment they gave up or got the lock, and failed with Sequel::PoolTimeout without ever having waited for the lock itself. A connection holder usually keeps its connection waiting for locks for at most two busy timeouts in one transaction (BEGIN IMMEDIATE or its first write, and COMMIT); a third leaves room for holders that start waiting after the queued thread does. A queued thread then usually gets a connection once those holders finish, and its own full busy timeout after that. Sequel's pool is not strictly first come, first served: a thread that releases a connection and asks again at once can take it back before a queued thread wakes. A queued thread can still time out behind callers that keep coming back, and queued writes do not necessarily land in the order they queued.

A caller that defers interrupts around a database call (Thread.handle_interrupt(Object => :never)) and is killed while queued holds the kill back for up to this long plus one busy timeout for each statement that then waits for a lock: the pool wait does not end on an interrupt, and each statement that follows starts with the kill pending, so it waits out its lock wait (see SQLiteBusyWait.wait_uninterrupted). That is 20 s with the defaults for a single statement, and 25 s for a transaction, which usually waits twice (its first write and COMMIT).



70
71
72
# File 'documented/common/sqlite_connection.rb', line 70

def self.sqlite_pool_timeout_s
  SQLITE_POOL_TIMEOUT_BUSY_TIMEOUTS * sqlite_busy_timeout_ms.to_i / 1000.0
end

.track_autosort_state ⇒ Boolean

Returns the autosort state tracking preference (cached).

Reads from lich_settings on first call and caches the result as a Boolean. Retries on SQLite3::BusyException.

Returns:

  • (Boolean) —

    true if autosort state tracking is enabled, false otherwise



1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
# File 'documented/lich.rb', line 1496

def self.track_autosort_state
  if @@track_autosort_state.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='track_autosort_state';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@track_autosort_state = (val.to_s =~ /on|true|yes/ ? true : false)
  end
  return @@track_autosort_state
end

.track_autosort_state=(val) ⇒ void

This method returns an undefined value.

Enables or disables autosort state tracking.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings as UTF-8 encoded string. Updates the cache immediately. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes



1517
1518
1519
1520
1521
1522
1523
1524
1525
# File 'documented/lich.rb', line 1517

def self.track_autosort_state=(val)
  @@track_autosort_state = (val.to_s =~ /on|true|yes/ ? true : false)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('track_autosort_state',?);", [@@track_autosort_state.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.track_dark_mode ⇒ Boolean

Returns the dark mode tracking preference (cached).

Reads from lich_settings on first call and caches the result as a Boolean. Retries on SQLite3::BusyException.

Returns:

  • (Boolean) —

    true if dark mode tracking is enabled, false otherwise



1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
# File 'documented/lich.rb', line 1533

def self.track_dark_mode
  if @@track_dark_mode.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='track_dark_mode';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@track_dark_mode = (val.to_s =~ /on|true|yes/ ? true : false)
  end
  return @@track_dark_mode
end

.track_dark_mode=(val) ⇒ void

This method returns an undefined value.

Enables or disables dark mode tracking.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings as UTF-8 encoded string. Updates the cache immediately. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes



1554
1555
1556
1557
1558
1559
1560
1561
1562
# File 'documented/lich.rb', line 1554

def self.track_dark_mode=(val)
  @@track_dark_mode = (val.to_s =~ /on|true|yes/ ? true : false)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('track_dark_mode',?);", [@@track_dark_mode.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.track_layout_state ⇒ Boolean

Returns the layout state tracking preference (cached).

Reads from lich_settings on first call and caches the result as a Boolean. Retries on SQLite3::BusyException.

Returns:

  • (Boolean) —

    true if layout state tracking is enabled, false otherwise



1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
# File 'documented/lich.rb', line 1570

def self.track_layout_state
  if @@track_layout_state.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='track_layout_state';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@track_layout_state = (val.to_s =~ /on|true|yes/ ? true : false)
  end
  return @@track_layout_state
end

.track_layout_state=(val) ⇒ void

This method returns an undefined value.

Enables or disables layout state tracking.

Normalizes the value to Boolean (on/true/yes → true, else false) and persists to lich_settings as UTF-8 encoded string. Updates the cache immediately. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    any value; truthy strings: on, true, yes



1591
1592
1593
1594
1595
1596
1597
1598
1599
# File 'documented/lich.rb', line 1591

def self.track_layout_state=(val)
  @@track_layout_state = (val.to_s =~ /on|true|yes/ ? true : false)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('track_layout_state',?);", [@@track_layout_state.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.track_persistent_launcher_mode ⇒ Boolean

Returns persisted launcher mode state for GUI login flow.

Returns:

  • (Boolean) —

    true when persistent multi-launch mode is enabled



1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
# File 'documented/lich.rb', line 1604

def self.track_persistent_launcher_mode
  if @@track_persistent_launcher_mode.nil?
    begin
      val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='track_persistent_launcher_mode';")
    rescue SQLite3::BusyException
      sleep 0.1
      retry
    end
    @@track_persistent_launcher_mode = (val.to_s =~ /on|true|yes/ ? true : false)
  end
  return @@track_persistent_launcher_mode
end

.track_persistent_launcher_mode=(val) ⇒ void

This method returns an undefined value.

Persists launcher mode state for GUI login flow.

Parameters:

  • val (Object) —

    truthy/falsey value parsed to Boolean



1621
1622
1623
1624
1625
1626
1627
1628
1629
# File 'documented/lich.rb', line 1621

def self.track_persistent_launcher_mode=(val)
  @@track_persistent_launcher_mode = (val.to_s =~ /on|true|yes/ ? true : false)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('track_persistent_launcher_mode',?);", [@@track_persistent_launcher_mode.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

Removes Lich from the Simutronics Autolaunch (SAL) protocol on Windows.

Reverses a previous link_to_sal operation by restoring the original SAL handler command in the registry. Requires administrator privileges; attempts elevation via ShellExecuteEx if run without admin.

Returns:

  • (Boolean) —

    true if successfully unlinked or was never linked, false on error



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
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
# File 'documented/lich.rb', line 705

def self.unlink_from_sal
  if defined?(Win32)
    if Win32.admin?
      begin
        launcher_key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command', :samDesired => (Win32::KEY_ALL_ACCESS | Win32::KEY_WOW64_32KEY))[:phkResult]
        real_directory = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'RealCommand')[:lpData]
        if real_directory.nil? or real_directory.empty?
          # not linked
          return true
        end

        r = Win32.RegSetValueEx(:hKey => launcher_key, :dwType => Win32::REG_SZ, :lpData => real_directory)
        return false unless (r == 0)

        r = Win32.RegDeleteValue(:hKey => launcher_key, :lpValueName => 'RealCommand')
        return (r == 0)
      ensure
        Win32.RegCloseKey(:hKey => launcher_key) rescue nil
      end
    else
      begin
        r = Win32.GetModuleFileName
        file = ((r[:return] > 0) ? r[:lpFilename] : 'rubyw.exe')
        params = "#{$PROGRAM_NAME.split(/\/|\\/).last} --unlink-from-sal"
        r = Win32.ShellExecuteEx(:lpVerb => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params, :fMask => Win32::SEE_MASK_NOCLOSEPROCESS)
        if r[:return] > 0
          process_id = r[:hProcess]
          sleep 0.2 while Win32.GetExitCodeProcess(:hProcess => process_id)[:lpExitCode] == Win32::STILL_ACTIVE
          sleep 3
        else
          Win32.ShellExecute(:lpOperation => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params)
          sleep 6
        end
      rescue
        Lich.msgbox(:message => $!)
      end
    end
  elsif defined?(Wine)
    real_launch_cmd = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\RealCommand')
    result = true
    if real_launch_cmd and not real_launch_cmd.empty?
      result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\', real_launch_cmd)
      result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Classes\\Simutronics.Autolaunch\\Shell\\Open\\command\\RealCommand', '')
    end
    return result
  else
    return false
  end
end

Removes Lich from the Simutronics Game Entry (SGE) launcher on Windows.

Reverses a previous link_to_sge operation by restoring the original launcher command in the registry. Requires administrator privileges; attempts elevation via ShellExecuteEx if run without admin.

Returns:

  • (Boolean) —

    true if successfully unlinked or was never linked, false on error



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
# File 'documented/lich.rb', line 572

def self.unlink_from_sge
  if defined?(Win32)
    if Win32.admin?
      begin
        launcher_key = Win32.RegOpenKeyEx(:hKey => Win32::HKEY_LOCAL_MACHINE, :lpSubKey => 'Software\\Simutronics\\Launcher', :samDesired => (Win32::KEY_ALL_ACCESS | Win32::KEY_WOW64_32KEY))[:phkResult]
        real_directory = Win32.RegQueryValueEx(:hKey => launcher_key, :lpValueName => 'RealDirectory')[:lpData]
        if real_directory.nil? or real_directory.empty?
          # not linked
          return true
        end

        r = Win32.RegSetValueEx(:hKey => launcher_key, :lpValueName => 'Directory', :dwType => Win32::REG_SZ, :lpData => real_directory)
        return false unless (r == 0)

        r = Win32.RegDeleteValue(:hKey => launcher_key, :lpValueName => 'RealDirectory')
        return (r == 0)
      ensure
        Win32.RegCloseKey(:hKey => launcher_key) rescue nil
      end
    else
      begin
        r = Win32.GetModuleFileName
        file = ((r[:return] > 0) ? r[:lpFilename] : 'rubyw.exe')
        params = "#{$PROGRAM_NAME.split(/\/|\\/).last} --unlink-from-sge"
        r = Win32.ShellExecuteEx(:lpVerb => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params, :fMask => Win32::SEE_MASK_NOCLOSEPROCESS)
        if r[:return] > 0
          process_id = r[:hProcess]
          sleep 0.2 while Win32.GetExitCodeProcess(:hProcess => process_id)[:lpExitCode] == Win32::STILL_ACTIVE
          sleep 3
        else
          Win32.ShellExecute(:lpOperation => 'runas', :lpFile => file, :lpDirectory => LICH_DIR.tr("/", "\\"), :lpParameters => params)
          sleep 6
        end
      rescue
        Lich.msgbox(:message => $!)
      end
    end
  elsif defined?(Wine)
    real_launch_dir = Wine.registry_gets('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\RealDirectory')
    result = true
    if real_launch_dir and not real_launch_dir.empty?
      result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\Directory', real_launch_dir)
      result = result && Wine.registry_puts('HKEY_LOCAL_MACHINE\\Software\\Simutronics\\Launcher\\RealDirectory', '')
    end
    return result
  else
    return false
  end
end

.win32_launch_method ⇒ String?

Retrieves the Windows game launch method preference.

Reads from lich_settings and retries on SQLite3::BusyException.

Returns:

  • (String, nil) —

    the stored launch method, or nil if not set



920
921
922
923
924
925
926
927
928
# File 'documented/lich.rb', line 920

def self.win32_launch_method
  begin
    val = Lich.db.get_first_value("SELECT value FROM lich_settings WHERE name='win32_launch_method';")
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
  val
end

.win32_launch_method=(val) ⇒ void

This method returns an undefined value.

Stores the Windows game launch method preference.

Writes to lich_settings as UTF-8 encoded string via INSERT OR REPLACE. Retries on SQLite3::BusyException.

Parameters:

  • val (#to_s) —

    the launch method to store



937
938
939
940
941
942
943
944
# File 'documented/lich.rb', line 937

def self.win32_launch_method=(val)
  begin
    Lich.db.execute("INSERT OR REPLACE INTO lich_settings(name,value) values('win32_launch_method',?);", [val.to_s.encode('UTF-8')])
  rescue SQLite3::BusyException
    sleep 0.1
    retry
  end
end

.with_strict_display_reads { ... } ⇒ Object

Commands and one-shot startup actions must not act on a busy-read default. Nested callers retain the outer strict scope, even when a read raises.

Yields:

  • reads display settings through their public accessors

Returns:

  • (Object) —

    the block result



1052
1053
1054
1055
1056
1057
1058
# File 'documented/lich.rb', line 1052

def self.with_strict_display_reads
  previous = Thread.current[:lich_strict_display_reads]
  Thread.current[:lich_strict_display_reads] = true
  yield
ensure
  Thread.current[:lich_strict_display_reads] = previous
end