483 lines
18 KiB
Python
483 lines
18 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Curses-based UI for QLPyCon
|
|
Handles terminal display, windows, and color rendering
|
|
"""
|
|
|
|
import curses
|
|
import curses.textpad
|
|
import threading
|
|
import queue
|
|
import logging
|
|
from config import COLOR_PAIRS, INFO_WINDOW_HEIGHT, INFO_WINDOW_Y, OUTPUT_WINDOW_Y, INPUT_WINDOW_HEIGHT, TEAM_MODES
|
|
|
|
logger = logging.getLogger('ui')
|
|
|
|
|
|
class CursesHandler(logging.Handler):
|
|
"""Logging handler that outputs to curses window"""
|
|
|
|
def __init__(self, window):
|
|
logging.Handler.__init__(self)
|
|
self.window = window
|
|
|
|
def emit(self, record):
|
|
try:
|
|
msg = self.format(record)
|
|
fs = "%s\n"
|
|
try:
|
|
print_colored(self.window, fs % msg, 0)
|
|
self.window.noutrefresh()
|
|
curses.doupdate()
|
|
except UnicodeError:
|
|
print_colored(self.window, fs % msg.encode("UTF-8"), 0)
|
|
self.window.noutrefresh()
|
|
curses.doupdate()
|
|
except (KeyboardInterrupt, SystemExit):
|
|
raise
|
|
except:
|
|
self.handleError(record)
|
|
|
|
def print_colored(window, message, attributes=0):
|
|
"""
|
|
Print message with Quake color codes (^N)
|
|
^0 = bold, ^1 = red, ^2 = green, ^3 = yellow, ^4 = blue, ^5 = cyan, ^6 = magenta, ^7 = white, ^9 = reset
|
|
"""
|
|
if not curses.has_colors:
|
|
window.addstr(message)
|
|
return
|
|
|
|
color = 0
|
|
bold = False
|
|
parse_color = False
|
|
|
|
for ch in message:
|
|
val = ord(ch)
|
|
if parse_color:
|
|
if ch == '0':
|
|
bold = True
|
|
elif ch == '9':
|
|
bold = False
|
|
elif ch == '7':
|
|
color = 0
|
|
elif ord('1') <= val <= ord('6'):
|
|
color = val - ord('0')
|
|
else:
|
|
window.addch('^', curses.color_pair(color) | (curses.A_BOLD if bold else 0) | attributes)
|
|
window.addch(ch, curses.color_pair(color) | (curses.A_BOLD if bold else 0) | attributes)
|
|
parse_color = False
|
|
elif ch == '^':
|
|
parse_color = True
|
|
else:
|
|
window.addch(ch, curses.color_pair(color) | (curses.A_BOLD if bold else 0) | attributes)
|
|
|
|
class UIManager:
|
|
"""Manages curses windows and display"""
|
|
|
|
def __init__(self, screen, host):
|
|
self.screen = screen
|
|
self.host = host
|
|
self.info_window = None
|
|
self.output_window = None
|
|
self.input_window = None
|
|
self.divider_window = None
|
|
self.input_queue = None
|
|
self.command_history = []
|
|
self.history_index = -1
|
|
|
|
self._init_curses()
|
|
self._create_windows()
|
|
|
|
def _init_curses(self):
|
|
"""Initialize curses settings"""
|
|
curses.endwin()
|
|
curses.initscr()
|
|
self.screen.nodelay(1)
|
|
curses.start_color()
|
|
curses.use_default_colors()
|
|
curses.cbreak()
|
|
curses.curs_set(0)
|
|
|
|
self.screen.addstr(f"Quake Live PyCon: {self.host}")
|
|
self.screen.noutrefresh()
|
|
|
|
# Initialize color pairs
|
|
for i in range(1, 7):
|
|
curses.init_pair(i, i, 0)
|
|
|
|
# Swap cyan and magenta (5 and 6)
|
|
curses.init_pair(5, 6, 0)
|
|
curses.init_pair(6, 5, 0)
|
|
|
|
def _create_windows(self):
|
|
"""Create all UI windows"""
|
|
maxy, maxx = self.screen.getmaxyx()
|
|
|
|
# Server info window (top)
|
|
self.info_window = curses.newwin(
|
|
INFO_WINDOW_HEIGHT,
|
|
maxx - 4,
|
|
INFO_WINDOW_Y,
|
|
2
|
|
)
|
|
self.info_window.scrollok(False)
|
|
self.info_window.idlok(False)
|
|
self.info_window.leaveok(True)
|
|
self.info_window.noutrefresh()
|
|
|
|
# Output window (middle - main display)
|
|
self.output_window = curses.newwin(
|
|
maxy - 17,
|
|
maxx - 4,
|
|
OUTPUT_WINDOW_Y,
|
|
2
|
|
)
|
|
self.output_window.scrollok(True)
|
|
self.output_window.idlok(False)
|
|
self.output_window.idcok(False)
|
|
self.output_window.leaveok(True)
|
|
self.output_window.noutrefresh()
|
|
|
|
# Divider line
|
|
self.divider_window = curses.newwin(
|
|
1,
|
|
maxx - 4,
|
|
maxy - 3,
|
|
2
|
|
)
|
|
self.divider_window.hline(curses.ACS_HLINE, maxx - 4)
|
|
self.divider_window.scrollok(False)
|
|
self.divider_window.idlok(False)
|
|
self.divider_window.leaveok(True)
|
|
self.divider_window.noutrefresh()
|
|
|
|
# Input window (bottom)
|
|
self.input_window = curses.newwin(
|
|
INPUT_WINDOW_HEIGHT,
|
|
maxx - 6,
|
|
maxy - 2,
|
|
4
|
|
)
|
|
self.input_window.keypad(True)
|
|
self.input_window.nodelay(False)
|
|
self.screen.addstr(maxy - 2, 2, '$ ')
|
|
self.input_window.idlok(True)
|
|
self.input_window.idcok(True)
|
|
self.input_window.leaveok(False)
|
|
self.input_window.noutrefresh()
|
|
|
|
self.screen.noutrefresh()
|
|
curses.doupdate()
|
|
|
|
def setup_input_queue(self):
|
|
"""Setup threaded input queue with command history"""
|
|
def wait_stdin(q, window, manager):
|
|
current_input = ""
|
|
cursor_pos = 0
|
|
temp_history_index = -1
|
|
temp_input = "" # Temp storage when navigating history
|
|
quit_confirm = False
|
|
|
|
while True:
|
|
try:
|
|
key = window.getch()
|
|
|
|
if key == -1: # No input
|
|
continue
|
|
|
|
# Enter key
|
|
if key in (curses.KEY_ENTER, 10, 13):
|
|
if len(current_input) > 0:
|
|
# Add to history
|
|
manager.command_history.append(current_input)
|
|
if len(manager.command_history) > 10:
|
|
manager.command_history.pop(0)
|
|
|
|
q.put(current_input)
|
|
current_input = ""
|
|
cursor_pos = 0
|
|
temp_history_index = -1
|
|
temp_input = ""
|
|
window.erase()
|
|
window.noutrefresh()
|
|
|
|
# Arrow UP - previous command
|
|
elif key == curses.KEY_UP:
|
|
if len(manager.command_history) > 0:
|
|
# Save current input when first entering history
|
|
if temp_history_index == -1:
|
|
temp_input = current_input
|
|
temp_history_index = len(manager.command_history)
|
|
|
|
if temp_history_index > 0:
|
|
temp_history_index -= 1
|
|
current_input = manager.command_history[temp_history_index]
|
|
cursor_pos = len(current_input)
|
|
window.erase()
|
|
window.addstr(0, 0, current_input)
|
|
window.noutrefresh()
|
|
|
|
# Arrow DOWN - next command
|
|
elif key == curses.KEY_DOWN:
|
|
if temp_history_index != -1:
|
|
temp_history_index += 1
|
|
if temp_history_index >= len(manager.command_history):
|
|
# Restore temp input
|
|
current_input = temp_input
|
|
temp_history_index = -1
|
|
temp_input = ""
|
|
else:
|
|
current_input = manager.command_history[temp_history_index]
|
|
|
|
cursor_pos = len(current_input)
|
|
window.erase()
|
|
window.addstr(0, 0, current_input)
|
|
window.noutrefresh()
|
|
|
|
# Arrow LEFT - move cursor left
|
|
elif key == curses.KEY_LEFT:
|
|
if cursor_pos > 0:
|
|
cursor_pos -= 1
|
|
window.move(0, cursor_pos)
|
|
window.noutrefresh()
|
|
|
|
# Arrow RIGHT - move cursor right
|
|
elif key == curses.KEY_RIGHT:
|
|
if cursor_pos < len(current_input):
|
|
cursor_pos += 1
|
|
window.move(0, cursor_pos)
|
|
window.noutrefresh()
|
|
|
|
# Backspace
|
|
elif key in (curses.KEY_BACKSPACE, 127, 8):
|
|
if cursor_pos > 0:
|
|
current_input = current_input[:cursor_pos-1] + current_input[cursor_pos:]
|
|
cursor_pos -= 1
|
|
temp_history_index = -1 # Exit history mode
|
|
window.erase()
|
|
window.addstr(0, 0, current_input)
|
|
window.move(0, cursor_pos)
|
|
window.noutrefresh()
|
|
|
|
# Regular character
|
|
elif 32 <= key <= 126:
|
|
char = chr(key)
|
|
current_input = current_input[:cursor_pos] + char + current_input[cursor_pos:]
|
|
cursor_pos += 1
|
|
temp_history_index = -1 # Exit history mode
|
|
window.erase()
|
|
window.addstr(0, 0, current_input)
|
|
window.move(0, cursor_pos)
|
|
window.noutrefresh()
|
|
|
|
except Exception as e:
|
|
import logging
|
|
logging.getLogger('ui').error(f'Input error: {e}')
|
|
|
|
window.move(0, cursor_pos)
|
|
curses.doupdate()
|
|
|
|
self.input_queue = queue.Queue()
|
|
t = threading.Thread(target=wait_stdin, args=(self.input_queue, self.input_window, self))
|
|
t.daemon = True
|
|
t.start()
|
|
|
|
return self.input_queue
|
|
|
|
def setup_logging(self):
|
|
"""Setup logging handler for output window"""
|
|
handler = CursesHandler(self.output_window)
|
|
formatter = logging.Formatter('%(asctime)-8s|%(name)-12s|%(levelname)-6s|%(message)-s', '%H:%M:%S')
|
|
handler.setFormatter(formatter)
|
|
return handler
|
|
|
|
def print_message(self, message, attributes=0):
|
|
"""Print formatted message to output window"""
|
|
print_colored(self.output_window, message, attributes)
|
|
self.output_window.noutrefresh()
|
|
self.input_window.move(0, 0)
|
|
curses.doupdate()
|
|
|
|
def update_server_info(self, game_state):
|
|
"""Update server info window"""
|
|
self.info_window.erase()
|
|
|
|
max_y, max_x = self.info_window.getmaxyx()
|
|
server_info = game_state.server_info
|
|
|
|
# Line 1: Hostname
|
|
hostname = server_info.hostname
|
|
warmup_display = "^3Warmup: ^2YES^9" if server_info.warmup else "^3Warmup: ^1NO^9"
|
|
print_colored(self.info_window, f"^3Name:^0 {hostname} {warmup_display}\n", 0)
|
|
|
|
# Line 2: Game info
|
|
gametype = server_info.gametype
|
|
mapname = server_info.map
|
|
timelimit = server_info.timelimit
|
|
fraglimit = server_info.fraglimit
|
|
roundlimit = server_info.roundlimit
|
|
caplimit = server_info.capturelimit
|
|
curclients = server_info.curclients
|
|
maxclients = server_info.maxclients
|
|
|
|
print_colored(self.info_window,
|
|
f"^3^9Type:^7^0 {gametype} ^9^3| Map:^7^0 {mapname} ^9^3| Players:^7^0 {curclients}/{maxclients} "
|
|
f"^3^9| Limits (T/F/R/C):^7^0 {timelimit}/{fraglimit}/{roundlimit}/{caplimit}^9\n", 0)
|
|
|
|
# Blank lines to fill
|
|
self.info_window.addstr("\n")
|
|
|
|
# Line 3: Team headers and player lists
|
|
teams = game_state.player_tracker.get_players_by_team()
|
|
|
|
if server_info.gametype in TEAM_MODES:
|
|
if server_info.gametype == 'CA':
|
|
red_score = f"{server_info.red_rounds:>3} "
|
|
blue_score = f"{server_info.blue_rounds:>3} "
|
|
|
|
else:
|
|
red_total = 0
|
|
blue_total = 0
|
|
for player in server_info.players:
|
|
player_name = player['name']
|
|
team = game_state.player_tracker.get_team(player_name)
|
|
score = int(player.get('score', 0))
|
|
|
|
if team == 'RED':
|
|
red_total += score
|
|
elif team == 'BLUE':
|
|
blue_total += score
|
|
|
|
red_score = f"{red_total:>3} "
|
|
blue_score = f"{blue_total:>3} "
|
|
|
|
print_colored(self.info_window, f"^0^7{red_score}^1RED TEAM ^7{blue_score}^4BLUE TEAM\n", 0)
|
|
|
|
# Sort players by score within each team
|
|
red_players_with_scores = []
|
|
blue_players_with_scores = []
|
|
spec_players = []
|
|
|
|
for player_name in teams['RED']:
|
|
score = 0
|
|
for player in server_info.players:
|
|
if player['name'] == player_name:
|
|
score = int(player.get('score', 0))
|
|
break
|
|
red_players_with_scores.append((player_name, score))
|
|
|
|
for player_name in teams['BLUE']:
|
|
score = 0
|
|
for player in server_info.players:
|
|
if player['name'] == player_name:
|
|
score = int(player.get('score', 0))
|
|
break
|
|
blue_players_with_scores.append((player_name, score))
|
|
|
|
# Sort by score descending
|
|
red_players_with_scores.sort(key=lambda x: x[1], reverse=True)
|
|
blue_players_with_scores.sort(key=lambda x: x[1], reverse=True)
|
|
|
|
red_players = [name for name, score in red_players_with_scores[:4]]
|
|
blue_players = [name for name, score in blue_players_with_scores[:4]]
|
|
spec_players = teams['SPECTATOR'][:4]
|
|
|
|
for i in range(4):
|
|
red_name = red_players[i] if i < len(red_players) else ''
|
|
blue_name = blue_players[i] if i < len(blue_players) else ''
|
|
|
|
# Get scores for team players
|
|
red_score = ''
|
|
blue_score = ''
|
|
if red_name:
|
|
for player in server_info.players:
|
|
if player['name'] == red_name:
|
|
red_score = player.get('score', '0')
|
|
break
|
|
if blue_name:
|
|
for player in server_info.players:
|
|
if player['name'] == blue_name:
|
|
blue_score = player.get('score', '0')
|
|
break
|
|
|
|
# Format: " 9 PlayerName" with right-aligned score
|
|
red = f"{red_score:>3} {red_name}" if red_name else ''
|
|
blue = f"{blue_score:>3} {blue_name}" if blue_name else ''
|
|
|
|
from formatter import strip_color_codes
|
|
red_clean = strip_color_codes(red)
|
|
blue_clean = strip_color_codes(blue)
|
|
|
|
red_pad = 24 - len(red_clean)
|
|
|
|
line = f"^0{red}^9{' ' * red_pad}^0{blue}^9\n"
|
|
print_colored(self.info_window, line, 0)
|
|
else:
|
|
print_colored(self.info_window, f"^0 ^5FREE\n", 0)
|
|
# Sort FREE players by score (highest first)
|
|
free_players = teams['FREE']
|
|
free_players_with_scores = []
|
|
for player_name in free_players:
|
|
score = 0
|
|
for player in server_info.players:
|
|
if player['name'] == player_name:
|
|
score = int(player.get('score', 0))
|
|
break
|
|
free_players_with_scores.append((player_name, score))
|
|
|
|
# Sort by score descending
|
|
free_players_with_scores.sort(key=lambda x: x[1], reverse=True)
|
|
sorted_free_players = [name for name, score in free_players_with_scores]
|
|
|
|
spec_players = teams['SPECTATOR'][:4]
|
|
free_col1 = sorted_free_players[:4]
|
|
free_col2 = sorted_free_players[4:8]
|
|
|
|
for i in range(4):
|
|
col1_name = free_col1[i] if i < len(free_col1) else ''
|
|
col2_name = free_col2[i] if i < len(free_col2) else ''
|
|
|
|
# Get scores for FREE players
|
|
col1_score = ''
|
|
col2_score = ''
|
|
if col1_name:
|
|
for player in server_info.players:
|
|
if player['name'] == col1_name:
|
|
col1_score = player.get('score', '0')
|
|
break
|
|
if col2_name:
|
|
for player in server_info.players:
|
|
if player['name'] == col2_name:
|
|
col2_score = player.get('score', '0')
|
|
break
|
|
|
|
# Format: " 9 PlayerName" with right-aligned score
|
|
col1 = f"{col1_score:>3} {col1_name}" if col1_name else ''
|
|
col2 = f"{col2_score:>3} {col2_name}" if col2_name else ''
|
|
|
|
from formatter import strip_color_codes
|
|
col1_clean = strip_color_codes(col1)
|
|
col2_clean = strip_color_codes(col2)
|
|
|
|
col1_pad = 24 - len(col1_clean)
|
|
|
|
line = f"^0{col1}^9{' ' * col1_pad}^0{col2}^9\n"
|
|
print_colored(self.info_window, line, 0)
|
|
|
|
# Blank lines to fill
|
|
self.info_window.addstr("\n")
|
|
|
|
# List spectators on one line
|
|
spec_list = " ".join(spec_players)
|
|
line = f"^0 ^3SPEC^7 {spec_list}\n"
|
|
print_colored(self.info_window, line, 0)
|
|
|
|
# Blank lines to fill
|
|
self.info_window.addstr("\n")
|
|
|
|
# Separator
|
|
separator = "^7" + "═" * (max_x - 1) + "^7"
|
|
print_colored(self.info_window, separator, 0)
|
|
|
|
self.info_window.noutrefresh()
|