Skip to content

Commit

Permalink
created a command processor, split that out of the interactive sessio…
Browse files Browse the repository at this point in the history
…n, added themes
  • Loading branch information
tedivm committed May 25, 2016
1 parent f4b6df1 commit 94ae3c2
Show file tree
Hide file tree
Showing 3 changed files with 226 additions and 43 deletions.
166 changes: 166 additions & 0 deletions screeps_console/command.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@

from screeps import ScreepsConnection
from settings import getSettings
from themes import themes
from types import FunctionType
import urwid


class Processor:

apiclient = False
aliases = {
'time': 'Game.time',
'help': 'list'
}

def __init__(self):
self.listbox = False
self.listwalker = False
self.edit = False

def setDisplayWidgets(self, loop, frame, listbox, listwalker, edit):
self.listbox = listbox
self.listwalker = listwalker
self.edit = edit
self.loop = loop

def getApiClient(self):
if not self.apiclient:
settings = getSettings()
self.apiclient = ScreepsConnection(u=settings['screeps_username'],p=settings['screeps_password'],ptr=settings['screeps_ptr'])
return self.apiclient

def onInput(self, key):
if not self.listbox:
return
if key == 'enter':
self.onEnter(key)
return
return


def onEnter(self, key):

userInput = self.edit
user_text = userInput.get_edit_text()


# Check for builtin commands before passing to the screeps api.
user_command_split = user_text.split(' ')
first_command = user_command_split[0]

## Check to see if command is actually an alias
if first_command in self.aliases:
first_command = self.aliases[first_command]
user_command_split[0] = first_command
user_text = ' '.join(user_command_split)


# Look for built in commands before attempting API call.
builtin = Builtin()
if hasattr(builtin, first_command):
self.listwalker.append(urwid.Text(('logged_input', '> ' + user_text)))
builtin_command = getattr(builtin, first_command)
builtin_command(self)
if len(self.listwalker) > 0:
self.listbox.set_focus(len(self.listwalker)-1)
userInput.set_edit_text('')
return


# Send command to Screeps API. Output will come from the console stream.
if len(user_text) > 0:
self.listwalker.append(urwid.Text(('logged_input', '> ' + user_text)))
userInput.set_edit_text('')
apiclient = self.getApiClient()
result = apiclient.console(user_text)


class Builtin:


def about(self, comp):
about = 'Screeps Interactive Console by Robert Hafner <tedivm@tedivm.com>'
comp.listwalker.append(urwid.Text(('logged_response', about)))
return


def clear(self, comp):
comp.listbox.set_focus_pending = 0
comp.listwalker[:] = [urwid.Text('')]
return

def exit(self, comp):
raise urwid.ExitMainLoop()


def list(self, comp):
command_list = ''
aliases = list(comp.aliases)
builtin_list = [method for method in dir(self) if callable(getattr(self, method))]
commands = builtin_list

for alias in aliases:
alias_real = comp.aliases[alias]
if alias_real not in builtin_list:
commands.append(alias)

commands.sort()
commands.reverse()
for builtin_command in commands:
if builtin_command != 'turtle':
command_list = builtin_command + ' ' + command_list

comp.listwalker.append(urwid.Text(('logged_response', command_list)))
return


def themes(self, comp):
userInput = comp.edit
user_text = userInput.get_edit_text()
user_command_split = user_text.split(' ')
if len(user_command_split) < 2 or user_command_split[1] == 'list':
theme_names = themes.keys()
theme_names.reverse()
theme_list = ''
for theme in theme_names:
theme_list = theme + ' ' + theme_list

comp.listwalker.append(urwid.Text(('logged_response', theme_list)))
return

theme = user_command_split[1]
if theme in themes:
comp.loop.screen.register_palette(themes['light'])
comp.loop.screen.clear()

return





def turtle(self, comp):
turtle = '''
________________
< How you doing? >
----------------
\ ___-------___
\ _-~~ ~~-_
\ _-~ /~-_
/^\__/^\ /~ \ / \\
/| O|| O| / \_______________/ \\
| |___||__| / / \ \\
| \ / / \ \\
| (_______) /______/ \_________ \\
| / / \ / \\
\ \^\\\ \ / \ /
\ || \______________/ _-_ //\__//
\ ||------_-~~-_ ------------- \ --/~ ~\ || __/
~-----||====/~ |==================| |/~~~~~
(_(__/ ./ / \_\ \.
(_(___/ \_____)_)
'''
comp.listwalker.append(urwid.Text(('logged_response', turtle)))
comp.listwalker.append(urwid.Text(('logged_response', '')))
60 changes: 17 additions & 43 deletions screeps_console/interactive.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
#!/usr/bin/env python

import colorama
import command
import json
import os
from outputparser import getSeverity
from outputparser import clearTags
from outputparser import getType
from screeps import ScreepsConnection
import outputparser
from settings import getSettings
import subprocess
import sys
from themes import themes
import urwid


Expand All @@ -18,7 +16,6 @@ class ScreepsInteractiveConsole:
consoleWidget = False
listWalker = False
userInput = False
apiclient = False

palette = [
('header', 'bold, white', 'dark gray'),
Expand All @@ -28,7 +25,6 @@ class ScreepsInteractiveConsole:
('error', 'yellow', 'dark red'),
('bg', 'dark blue', 'black'),
('default', 'light blue', 'black'),

('severity0', 'light gray', 'black'),
('severity1', 'dark blue', 'black'),
('severity2', 'dark cyan', 'black'),
Expand All @@ -42,7 +38,9 @@ class ScreepsInteractiveConsole:
def __init__(self):

frame = self.getFrame()
self.loop = urwid.MainLoop(urwid.AttrMap(frame, 'bg'), unhandled_input=self.catch_user_input, palette=self.palette)
comp = self.getCommandProcessor()
self.loop = urwid.MainLoop(urwid.AttrMap(frame, 'bg'), unhandled_input=comp.onInput, palette=themes['dark'])
comp.setDisplayWidgets(self.loop, frame, self.getConsole(), self.getConsoleListWalker(), self.getEdit())
console_monitor = ScreepsConsoleMonitor(self.consoleWidget, self.listWalker, self.loop)
self.loop.run()

Expand All @@ -68,50 +66,21 @@ def getEdit(self):

def getConsole(self):
if not self.consoleWidget:
welcome = self.getWelcomeMessage()
self.consoleWidget = urwid.ListBox(self.getConsoleListWalker())
return self.consoleWidget

def getConsoleListWalker(self):
if not self.listWalker:
self.listWalker = urwid.SimpleFocusListWalker([self.getWelcomeMessage()])
self.listWalker = urwid.SimpleListWalker([self.getWelcomeMessage()])
return self.listWalker


def catch_user_input(self, key):

if key == 'enter':
userInput = self.getEdit()
user_text = userInput.get_edit_text()
userInput.set_edit_text('')

walker = self.getConsoleListWalker()
walker.append(urwid.Text(('logged_input', '> ' + user_text)))

if len(walker) > 0:
self.getConsole().set_focus(len(walker)-1)

if user_text == 'exit':
raise urwid.ExitMainLoop()

if len(user_text) > 0:
apiclient = self.getApiClient()
result = apiclient.console(user_text)

return
def getCommandProcessor(self):
return command.Processor()

def getWelcomeMessage(self):
return urwid.Text(('default', 'Welcome to the Screeps Interactive Console'))


def getApiClient(self):
if not self.apiclient:
settings = getSettings()
self.apiclient = ScreepsConnection(u=settings['screeps_username'],p=settings['screeps_password'],ptr=settings['screeps_ptr'])
return self.apiclient



class ScreepsConsoleMonitor:

proc = False
Expand All @@ -135,11 +104,16 @@ def getProcess(self):
return self.proc

def onUpdate(self, data):

# If we lose the connection to the remote system close the console.
if data.startswith('### closed ###'):
raise urwid.ExitMainLoop()

data_lines = data.rstrip().split('\n')
for line_json in data_lines:
try:
line = json.loads(line_json.strip())
log_type = getType(line)
log_type = outputparser.getType(line)

if log_type == 'result':
formatting = 'logged_response'
Expand All @@ -148,14 +122,14 @@ def onUpdate(self, data):
elif log_type == 'error':
formatting = 'error'
else:
severity = getSeverity(line)
severity = outputparser.getSeverity(line)
if not severity or severity > 5 or severity < 0:
formatting = 'highlight'
else:
formatting = 'severity' + str(severity)

line = line.replace('&#09;', " ")
line = clearTags(line)
line = outputparser.clearTags(line)
self.walker.append(urwid.Text((formatting, line)))
if len(self.walker) > 0:
self.widget.set_focus(len(self.walker)-1)
Expand Down
43 changes: 43 additions & 0 deletions screeps_console/themes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@



themes = {
'dark':[
('bg', 'dark blue', 'black'),
('header', 'bold, white', 'dark gray'),
('input', 'white', 'dark blue'),

('logged_input', 'dark magenta', 'black'),
('logged_response', 'light magenta', 'black'),

('error', 'yellow', 'dark red'),
('default', 'light blue', 'black'),
('severity0', 'light gray', 'black'),
('severity1', 'dark blue', 'black'),
('severity2', 'dark cyan', 'black'),
('severity3', 'dark green', 'black'),
('severity4', 'light red', 'black'),
('severity5', 'yellow', 'dark red'),
('highlight', 'black', 'yellow'),
],

'light':[
('bg', 'dark blue', 'white'),
('header', 'bold, black', 'light gray'),
('input', 'black', 'light cyan'),

('logged_input', 'dark magenta', 'white'),
('logged_response', 'light magenta', 'white'),

('error', 'yellow', 'light red'),
('default', 'light blue', 'white'),
('severity0', 'light gray', 'white'),
('severity1', 'dark blue', 'white'),
('severity2', 'dark cyan', 'white'),
('severity3', 'dark green', 'white'),
('severity4', 'light red', 'white'),
('severity5', 'yellow', 'light red'),
('highlight', 'black', 'yellow'),
],

}

0 comments on commit 94ae3c2

Please sign in to comment.