Files
LonaRPG-Online-Games/ModScripts/99_typing_status.rb
T
2026-10-29 21:59:06 +04:00

433 lines
12 KiB
Ruby

# encoding: UTF-8
#==============================================================================
# TypingStatus client patch 1.0.0
#------------------------------------------------------------------------------
# Shows who is actively typing next to the chat input field.
# one player: ✏ cyberya
# several players: ✏ cyberya, WorldBosse...
#
# Client -> server:
# typing:<global|clan>:<1|0>
# Server -> client:
# typing_status:<channel>:<pid>:<1|0>:<percent-escaped UTF-8 nick>
#==============================================================================
module MPTypingStatus
HEARTBEAT_SECONDS = 0.90
LOCAL_IDLE_SECONDS = 1.55
REMOTE_TTL_SECONDS = 5.0
PENCIL = "✍"
PENCIL_VIP_FALLBACK = "📎"
@remote = { "global" => {}, "clan" => {} }
@local_announced = false
@local_channel = nil
@last_local_edit = 0.0
@last_local_send = 0.0
@last_render_signature = nil
def self.now
Process.clock_gettime(Process::CLOCK_MONOTONIC)
rescue
Time.now.to_f
end
def self.normalize_channel(value)
ch = value.to_s.downcase
return "clan" if ch == "clan"
return "global" if ch == "global"
nil
rescue
nil
end
def self.percent_unescape(value)
src = value.to_s
bytes = []
i = 0
while i < src.bytesize
b = src.getbyte(i)
if b == 37 && i + 2 < src.bytesize # %
hex = src.byteslice(i + 1, 2)
if hex && hex =~ /\A[0-9A-Fa-f]{2}\z/
bytes << hex.to_i(16)
i += 3
next
end
end
bytes << b
i += 1
end
out = bytes.pack('C*')
out.force_encoding('UTF-8') if out.respond_to?(:force_encoding)
begin
out = out.encode('UTF-8', 'UTF-8', :invalid => :replace, :undef => :replace, :replace => '')
rescue
end
out.gsub(/[\r\n\t\0]/, ' ').strip
rescue
value.to_s
end
def self.current_channel
return nil unless defined?(MPChat) && MPChat.respond_to?(:current_channel)
normalize_channel(MPChat.current_channel)
rescue
nil
end
def self.local_pid
return 0 unless defined?(WebSocket) && WebSocket.respond_to?(:my_id)
WebSocket.my_id.to_i
rescue
0
end
def self.connected?
defined?(WebSocket) && WebSocket.respond_to?(:connected?) && WebSocket.connected?
rescue
false
end
def self.send_state(active, channel = nil)
return false unless connected?
ch = normalize_channel(channel || @local_channel || current_channel)
return false if ch.nil?
WebSocket.send_line("typing:#{ch}:#{active ? 1 : 0}")
@last_local_send = now if active
true
rescue
false
end
# Called only when text actually changed by keyboard/backspace.
def self.note_local_edit
ch = current_channel
return if ch.nil? # system channel/read-only
t = now
if @local_announced && @local_channel != ch
send_state(false, @local_channel)
@local_announced = false
end
@local_channel = ch
@last_local_edit = t
if !@local_announced
if send_state(true, ch)
@local_announced = true
@last_local_send = t
end
elsif t - @last_local_send >= HEARTBEAT_SECONDS
send_state(true, ch)
@last_local_send = t
end
rescue
end
def self.stop_local
if @local_announced && @local_channel
send_state(false, @local_channel)
end
@local_announced = false
@local_channel = nil
@last_local_edit = 0.0
@last_local_send = 0.0
rescue
@local_announced = false
@local_channel = nil
end
def self.receive(channel, pid, typing, nick)
ch = normalize_channel(channel)
return if ch.nil?
player_id = pid.to_i
return if player_id <= 0 || player_id == local_pid
@remote[ch] ||= {}
if typing
clean = percent_unescape(nick)
if clean.to_s.empty? && defined?(WebSocket) && WebSocket.respond_to?(:nickname_for)
clean = WebSocket.nickname_for(player_id).to_s rescue ""
end
clean = "Player#{player_id}" if clean.to_s.empty?
@remote[ch][player_id] = { :nick => clean.to_s, :at => now }
else
@remote[ch].delete(player_id)
end
refresh_if_changed(true)
rescue
end
def self.prune_remote
t = now
changed = false
@remote.each_value do |bucket|
bucket.keys.each do |pid|
row = bucket[pid]
if row.nil? || t - row[:at].to_f > REMOTE_TTL_SECONDS
bucket.delete(pid)
changed = true
end
end
end
changed
rescue
false
end
def self.names(channel = nil)
ch = normalize_channel(channel || current_channel)
return [] if ch.nil?
prune_remote
bucket = @remote[ch] || {}
bucket.values.sort_by { |row| row[:nick].to_s.downcase }.map { |row| row[:nick].to_s }.reject { |n| n.empty? }
rescue
[]
end
def self.display_text(channel = nil)
list = names(channel)
return "" if list.empty?
return list[0].to_s if list.size == 1
shown = list.first(3)
"#{shown.join(', ')}..."
rescue
""
end
def self.signature
[current_channel, names(current_channel)]
rescue
[nil, []]
end
def self.refresh_input_window
return unless defined?(MPChat)
win = MPChat.instance_variable_get(:@input_window) rescue nil
return if win.nil? || (win.respond_to?(:disposed?) && win.disposed?)
win.refresh if win.respond_to?(:refresh)
rescue
end
def self.refresh_if_changed(force = false)
sig = signature
if force || sig != @last_render_signature
@last_render_signature = sig
refresh_input_window
end
rescue
end
def self.tick
t = now
if @local_announced && (t - @last_local_edit.to_f >= LOCAL_IDLE_SECONDS)
stop_local
end
changed = prune_remote
refresh_if_changed(changed)
rescue
end
def self.clear_remote
@remote = { "global" => {}, "clan" => {} }
@last_render_signature = nil
refresh_input_window
rescue
end
end
#==============================================================================
# Network parser + helper
#==============================================================================
module WebSocket
class << self
unless method_defined?(:mp_typing_status_parse_without_typing)
alias mp_typing_status_parse_without_typing parse
end
end
def self.parse(msg)
if msg.to_s.start_with?("typing_status:")
parts = msg.to_s.split(":", 5)
if parts.size >= 5
MPTypingStatus.receive(parts[1], parts[2].to_i, parts[3].to_s == "1", parts[4])
end
return
end
mp_typing_status_parse_without_typing(msg)
end
class << self
if method_defined?(:disconnect) && !method_defined?(:mp_typing_status_disconnect_without_clear)
alias mp_typing_status_disconnect_without_clear disconnect
def disconnect(*args)
MPTypingStatus.stop_local rescue nil
MPTypingStatus.clear_remote rescue nil
mp_typing_status_disconnect_without_clear(*args)
end
end
end
end
#==============================================================================
# MPChat lifecycle. This file is loaded after chat channels, so these aliases
# wrap the final versions used by the provided client.
#==============================================================================
module MPChat
class << self
unless method_defined?(:mp_typing_status_update_without_tick)
alias mp_typing_status_update_without_tick update
end
unless method_defined?(:mp_typing_status_close_without_stop)
alias mp_typing_status_close_without_stop close
end
if method_defined?(:set_channel) && !method_defined?(:mp_typing_status_set_channel_without_stop)
alias mp_typing_status_set_channel_without_stop set_channel
end
end
def self.update
MPTypingStatus.tick
mp_typing_status_update_without_tick
end
def self.close
MPTypingStatus.stop_local
mp_typing_status_close_without_stop
end
if respond_to?(:mp_typing_status_set_channel_without_stop)
def self.set_channel(channel)
old = current_channel rescue nil
target = (defined?(MPChatChannels) ? MPChatChannels.normalize(channel) : channel.to_s)
MPTypingStatus.stop_local if old.to_s != target.to_s
result = mp_typing_status_set_channel_without_stop(channel)
MPTypingStatus.refresh_if_changed(true)
result
end
end
# Make room for a compact typing line directly above the text entry line,
# inside the same chat input window.
def self.create_windows
dispose_windows
w = Graphics.width
h = Graphics.height
input_h = 68
tabs_h = const_defined?(:TAB_H) ? TAB_H : 30
log_h = h - input_h - tabs_h
log_h = [log_h, 1].max
@tabs_window = Window_MPChatTabs.new(0, 0, w, tabs_h) if defined?(Window_MPChatTabs)
log_y = @tabs_window ? tabs_h : 0
@log_window = Window_MPChatLog.new(0, log_y, w, log_h)
@input_window = Window_MPChatInput.new(0, log_y + log_h, w, input_h)
@tabs_window.z = 9999 if @tabs_window rescue nil
@log_window.z = 9999 rescue nil
@input_window.z = 9999 rescue nil
MPTypingStatus.refresh_if_changed(true)
end
end
#==============================================================================
# Detect real edits and render the indicator beside the input field.
#==============================================================================
class Window_MPChatInput < Window_Base
unless method_defined?(:mp_typing_status_update_without_probe)
alias mp_typing_status_update_without_probe update
end
unless method_defined?(:mp_typing_status_clear_without_stop)
alias mp_typing_status_clear_without_stop clear
end
def update
before = @text.to_s.dup
mp_typing_status_update_without_probe
after = @text.to_s
MPTypingStatus.note_local_edit if after != before
end
def clear
MPTypingStatus.stop_local
mp_typing_status_clear_without_stop
end
def refresh
contents.clear
contents.font.name = MPChat.ui_font_name
contents.font.shadow = false
contents.font.outline = false
# Typing row: muted and compact. It is part of the input panel, not a popup.
typing = MPTypingStatus.display_text(MPChat.current_channel)
unless typing.to_s.empty?
contents.font.size = 16
contents.font.color = Color.new(185, 185, 185)
# Never send the Unicode pencil through draw_text: some game fonts miss
# that glyph and render a broken square. Use the same PNG-backed VIP
# emoji renderer as nickname icons. If the pencil asset is absent, show
# the names without an icon rather than falling back to the broken glyph.
text_x = 4
begin
if defined?(MPNickEmoji) && MPNickEmoji.respond_to?(:draw_icon)
icon_rect = Rect.new(4, 0, 18, 18)
rendered = MPNickEmoji.draw_icon(contents, icon_rect, MPTypingStatus::PENCIL, 16)
unless rendered
# 1F4CE is already part of the VIP icon pack used by this client.
rendered = MPNickEmoji.draw_icon(contents, icon_rect, MPTypingStatus::PENCIL_VIP_FALLBACK, 16)
end
text_x = 25 if rendered
end
rescue
text_x = 4
end
draw_text(text_x, -3, [contents.width - text_x - 4, 1].max, 22, typing.to_s)
end
contents.font.size = 20
default_color = if defined?(MPChatChannels)
MPChatChannels.color(MPChat.current_channel)
else
Color.new(255, 125, 25)
end
contents.font.color = default_color
if defined?(MPChatChannels) && MPChat.current_channel == "system"
prefix = "Системный: "
visible = "только уведомления"
else
prefix = if MPChat.respond_to?(:current_channel_label)
MPChat.current_channel_label + ": "
else
"Чат: "
end
visible = @text.to_s.dup
end
draw_width = [contents.width - 8, 1].max
begin
plain = defined?(MPChatFormat) ? MPChatFormat.strip_color_codes(visible) : visible
while visible.size > 0 && contents.text_size(prefix + plain).width > draw_width
visible = visible[1..-1] || ""
plain = defined?(MPChatFormat) ? MPChatFormat.strip_color_codes(visible) : visible
end
if visible != @text.to_s && (!defined?(MPChatChannels) || MPChat.current_channel != "system")
visible = "..." + visible
end
rescue
end
y = 19
if respond_to?(:draw_colored_input)
draw_colored_input(4, y, draw_width, line_height, prefix, visible, default_color)
else
draw_text(4, y, draw_width, line_height, prefix + visible.to_s)
end
rescue
end
end