# -*- coding: utf-8 -*-
#######################################################################
# This file is part of Lyntin.
# copyright (c) Free Software Foundation 1999 - 2002
# Update: Nitram Treblig
#
# Lyntin is distributed under the GNU General Public License license.  See the
# file LICENSE for distribution details.
#######################################################################
"""
This is a wxPython oriented user interface for lyntin.

Initial port from the tkui.py file by Bryan Muir

KNOWN BUGS
1. Thread error on closeing, intermittent.


New:
9-25-03:  Added Action Manager
          Added save functionality
          Added Load file
          
9-23-03:  Added Alias Manager

"""

import wx as WX
import time
import wx
import wx.stc as stc
import os, types, queue, re, ctypes
from lyntin import ansi, event, engine, exported, utils, constants, config, argparser
from lyntin.shortcut import *
from lyntin.view import ViewManager
from lyntin.voice import VoiceManager
from lyntin.ui import base, message
from lyntin.ui.view import History, restore_command_focus
from lyntin.ui.exits import ExitChoicePopup
from lyntin.modules import alias, music
from lyntin.modules.sound import play, setVolume, getVolume
from lyntin.ui.wxpui_forms import CommandPanel
from lyntin.mud_connections import MudRegistry, queue_connection, queue_current_mud
from lyntin.ui.mud_connections import MudConnectionDialog, ManageMudConnectionsDialog
from lyntin.ui.gag_editor import GagEditorDialog
import ctypes
##################################################################


import codecs

############################################################################

UNICODE_ENCODING = "latin-1"
ALIAS = 1
ACTION = 2

HELP_TEXT = """The wxpythonui uses wxPython and provides a graphical interface 
to Lyntin.  It also has the following additional functionality:

 - numpad bindings (VK_NUMPAD0 through VK_NUMPAD9)
 - user-defined function key bindings (F1 through F12)
 - pgup and pgdown scroll back
 - up and down command line history
 - tab or escape opens the history window of the current view; there,
   escape or tab goes back to the command line (escape toggles between
   the two). The history window adds new messages while it is open.
   Back in the command line, it is empty for a new command; a command
   being typed goes into the command history (up arrow brings it back).
 - ctrl-u removal of text
 - ctrl-c copy from the text buffer and ctrl-v paste into the command
   buffer (in Windows)
 - ctrl-t autotyper
 - NamedWindow handling

To bind function key and numpad bindings, create an alias for the
symbol.  For example:

   #alias {VK_NUMPAD2} {south}


"""

# the complete list of foreground color codes and what color they
# map to in RGB.
fg_color_codes = {"30": "#000000",
                  "31": "#aa0000",
                  "32": "#00dd00",
                  "33": "#daa520",
                  "35": "#bb00bb",
                  "36": "#00cccc",
                  "37": "#aaaaaa",
                  "b30": "#666666",
                  "b31": "#ff3333",
                  "b32": "#00ff3f",
                  "b33": "#ffff00",
                  "b34": "#2222ff",
                  "b35": "#ff33ff",
                  "b36": "#70eeee",
                  "b37": "#ffffff" }

# the complete list of background color codes and what color they
# map to in RGB.
bg_color_codes = {"40": "#000000",
                  "41": "#ff0000",
                  "42": "#00ff00",
                  "43": "#daa520",
                  "44": "#0000aa",
                  "45": "#ff00ff",
                  "46": "#00cccc",
                  "47": "#bbbbbb",
                  "b40": "#777777",
                  "b41": "#fa6072",
                  "b42": "#00ff7f",
                  "b43": "#ffff00",
                  "b44": "#2222ff",
                  "b45": "#ee82ee",
                  "b46": "#70eeee",
                  "b47": "#ffffff" }


#a dictionary of virtual keycodes and their string based name.  Makes it easier to look
#up the string that something is bound to.
keyMap = {
    wx.WXK_BACK : "WXK_BACK",
    wx.WXK_TAB : "WXK_TAB",
    wx.WXK_RETURN : "WXK_RETURN",
    wx.WXK_ESCAPE : "WXK_ESCAPE",
    wx.WXK_SPACE : "WXK_SPACE",
    wx.WXK_DELETE : "WXK_DELETE",
    wx.WXK_START : "WXK_START",
    wx.WXK_LBUTTON : "WXK_LBUTTON",
    wx.WXK_RBUTTON : "WXK_RBUTTON",
    wx.WXK_CANCEL : "WXK_CANCEL",
    wx.WXK_MBUTTON : "WXK_MBUTTON",
    wx.WXK_CLEAR : "WXK_CLEAR",
    wx.WXK_SHIFT : "WXK_SHIFT",
    wx.WXK_ALT : "WXK_ALT",
    wx.WXK_CONTROL : "WXK_CONTROL",
    wx.WXK_MENU : "WXK_MENU",
    wx.WXK_PAUSE : "WXK_PAUSE",
    wx.WXK_CAPITAL : "WXK_CAPITAL",
    wx.WXK_PAGEUP : "WXK_PRIOR",
    wx.WXK_PAGEDOWN : "WXK_NEXT",
    wx.WXK_END : "WXK_END",
    wx.WXK_HOME : "WXK_HOME",
    wx.WXK_LEFT : "WXK_LEFT",
    wx.WXK_UP : "WXK_UP",
    wx.WXK_RIGHT : "WXK_RIGHT",
    wx.WXK_DOWN : "WXK_DOWN",
    wx.WXK_SELECT : "WXK_SELECT",
    wx.WXK_PRINT : "WXK_PRINT",
    wx.WXK_EXECUTE : "WXK_EXECUTE",
    wx.WXK_SNAPSHOT : "WXK_SNAPSHOT",
    wx.WXK_INSERT : "WXK_INSERT",
    wx.WXK_HELP : "WXK_HELP",
    wx.WXK_NUMPAD0 : "WXK_NUMPAD0",
    wx.WXK_NUMPAD1 : "WXK_NUMPAD1",
    wx.WXK_NUMPAD2 : "WXK_NUMPAD2",
    wx.WXK_NUMPAD3 : "WXK_NUMPAD3",
    wx.WXK_NUMPAD4 : "WXK_NUMPAD4",
    wx.WXK_NUMPAD5 : "WXK_NUMPAD5",
    wx.WXK_NUMPAD6 : "WXK_NUMPAD6",
    wx.WXK_NUMPAD7 : "WXK_NUMPAD7",
    wx.WXK_NUMPAD8 : "WXK_NUMPAD8",
    wx.WXK_NUMPAD9 : "WXK_NUMPAD9",
    wx.WXK_MULTIPLY : "WXK_MULTIPLY",
    wx.WXK_ADD : "WXK_ADD",
    wx.WXK_SEPARATOR : "WXK_SEPARATOR",
    wx.WXK_SUBTRACT : "WXK_SUBTRACT",
    wx.WXK_DECIMAL : "WXK_DECIMAL",
    wx.WXK_DIVIDE : "WXK_DIVIDE",
    wx.WXK_F1 : "WXK_F1",
    wx.WXK_F2 : "WXK_F2",
    wx.WXK_F3 : "WXK_F3",
    wx.WXK_F4 : "WXK_F4",
    wx.WXK_F5 : "WXK_F5",
    wx.WXK_F6 : "WXK_F6",
    wx.WXK_F7 : "WXK_F7",
    wx.WXK_F8 : "WXK_F8",
    wx.WXK_F9 : "WXK_F9",
    wx.WXK_F10 : "WXK_F10",
    wx.WXK_F11 : "WXK_F11",
    wx.WXK_F12 : "WXK_F12",
    wx.WXK_F13 : "WXK_F13",
    wx.WXK_F14 : "WXK_F14",
    wx.WXK_F15 : "WXK_F15",
    wx.WXK_F16 : "WXK_F16",
    wx.WXK_F17 : "WXK_F17",
    wx.WXK_F18 : "WXK_F18",
    wx.WXK_F19 : "WXK_F19",
    wx.WXK_F20 : "WXK_F20",
    wx.WXK_F21 : "WXK_F21",
    wx.WXK_F22 : "WXK_F22",
    wx.WXK_F23 : "WXK_F23",
    wx.WXK_F24 : "WXK_F24",
    wx.WXK_NUMLOCK : "WXK_NUMLOCK",
    wx.WXK_SCROLL : "WXK_SCROLL",
    wx.WXK_PAGEUP : "WXK_PAGEUP",
    wx.WXK_PAGEDOWN : "WXK_PAGEDOWN",
    wx.WXK_NUMPAD_SPACE : "WXK_NUMPAD_SPACE",
    wx.WXK_NUMPAD_TAB : "WXK_NUMPAD_TAB",
    wx.WXK_NUMPAD_ENTER : "WXK_NUMPAD_ENTER",
    wx.WXK_NUMPAD_F1 : "WXK_NUMPAD_F1",
    wx.WXK_NUMPAD_F2 : "WXK_NUMPAD_F2",
    wx.WXK_NUMPAD_F3 : "WXK_NUMPAD_F3",
    wx.WXK_NUMPAD_F4 : "WXK_NUMPAD_F4",
    wx.WXK_NUMPAD_HOME : "WXK_NUMPAD_HOME",
    wx.WXK_NUMPAD_LEFT : "WXK_NUMPAD_LEFT",
    wx.WXK_NUMPAD_UP : "WXK_NUMPAD_UP",
    wx.WXK_NUMPAD_RIGHT : "WXK_NUMPAD_RIGHT",
    wx.WXK_NUMPAD_DOWN : "WXK_NUMPAD_DOWN",
    wx.WXK_NUMPAD_PAGEUP : "WXK_NUMPAD_PRIOR",
    wx.WXK_NUMPAD_PAGEUP : "WXK_NUMPAD_PAGEUP",
    wx.WXK_NUMPAD_PAGEDOWN : "WXK_NUMPAD_NEXT",
    wx.WXK_NUMPAD_PAGEDOWN : "WXK_NUMPAD_PAGEDOWN",
    wx.WXK_NUMPAD_END : "WXK_NUMPAD_END",
    wx.WXK_NUMPAD_BEGIN : "WXK_NUMPAD_BEGIN",
    wx.WXK_NUMPAD_INSERT : "WXK_NUMPAD_INSERT",
    wx.WXK_NUMPAD_DELETE : "WXK_NUMPAD_DELETE",
    wx.WXK_NUMPAD_EQUAL : "WXK_NUMPAD_EQUAL",
    wx.WXK_NUMPAD_MULTIPLY : "WXK_NUMPAD_MULTIPLY",
    wx.WXK_NUMPAD_ADD : "WXK_NUMPAD_ADD",
    wx.WXK_NUMPAD_SEPARATOR : "WXK_NUMPAD_SEPARATOR",
    wx.WXK_NUMPAD_SUBTRACT : "WXK_NUMPAD_SUBTRACT",
    wx.WXK_NUMPAD_DECIMAL : "WXK_NUMPAD_DECIMAL",
    wx.WXK_NUMPAD_DIVIDE : "WXK_NUMPAD_DIVIDE",
}

#ID's used to identify menu entries
ID_ABOUT=wx.NewIdRef()

# Help > About: the history of the client, without the old NTLyntin blog,
# which no longer exists.
ABOUT_TEXT = (
    "NTLyntin64 : client MUD accessible aux personnes aveugles et malvoyantes, "
    "pensé pour MultiMonde.\n\n"
    "Historique :\n"
    "- Lyntin : le client MUD libre d'origine (licence GPL), écrit par Will Guaraldi.\n"
    "- Lyntin Access : adaptation de Lyntin aux lecteurs d'écran, par jlpo.\n"
    "- NTLyntin : version optimisée pour MultiMonde, par Nitram Treblig.\n"
    "- NTLyntin64 : version 64 bits pour Windows 10 et 11, par JVPA "
    "(Jeux vidéo pour aveugles) : Python 3, NVDA, JAWS et SAPI, lecteur "
    "musical, connexion chiffrée (TLS).\n\n"
    "Site : https://jeuxvideopouraveugles.fr")
ID_EXIT=wx.NewIdRef()
ID_ADD_MUD = wx.NewIdRef()
ID_MANAGE_MUDS = wx.NewIdRef()
ID_ALIAS = wx.NewIdRef()
ID_TRIGGER = wx.NewIdRef()
ID_TRIGGER_PROPOSALS = wx.NewIdRef()
ID_FILTERS = wx.NewIdRef()

#widget ID's
ID_TEXT = wx.NewIdRef()
ID_TEXT_BUFFER = wx.NewIdRef()
ID_ENTRY = wx.NewIdRef()

#misc ID's
ID_QUEUE_TIMER = wx.NewIdRef()


# this is the default color--it's what we use when the mud hasn't
# specified a color yet.  this might get a little fishy.
# when using DEFAULT make sure you clone it first.

# The elements of the default color list are as follows...
# [bold, underline, blink, reverse, foreground, background]
DEFAULT_COLOR = list(ansi.DEFAULT_COLOR)

#this sets the fg color to 37, which from ansi.py stylemap is white
#also sets bg color to black
DEFAULT_COLOR[ansi.PLACE_FG] = 37
DEFAULT_COLOR[ansi.PLACE_BG] = 40

myui = None

def get_ui_instance():
    global myui
    if myui == None:
        myui = wxui()
    return myui
  

class _Event:
    def __init__(self):
        pass

    def execute(self, wxui):
        pass

class _OutputEvent(_Event):
    def __init__(self, text):
        self._text = text

    def execute(self, wxui):
        wxui.write_internal(self._text)

class _ColorCheckEvent(_Event):
    def execute(self, wxui):
      wxui.colorCheck() 

class _TitleEvent(_Event):
    def __init__(self, wxFrame, title):
        self._wxFrame = wxFrame
        self._title = title

    def execute(self, wxui):
        self._wxFrame.SetTitle(self._title)

class _WriteWindowEvent(_Event):
    def __init__(self, windowname, message):
        self._windowname = windowname
        self._message = message

    def execute(self, wxui):
        wxui.writeWindow_internal(self._windowname, self._message)
    
    
class MudFrame(wx.Frame):
    def __init__(self,parent,id,title, pos, size):
        global myui
        wx.Frame.__init__(self, parent, id, "NTLyntin64", pos, size,
                          style=wx.DEFAULT_FRAME_STYLE)
                            
#       self._parent = parent
        self._closing = False
        self._history_window = None

        #attr to hold a reference to our command_editor once
        #it is created.  Also used so we dont create it more
        #times than is necessary
        self.command_editor = None
        
        # A Statusbar in the bottom of the window
        self.CreateStatusBar()
        
        # Setting up the File menu.
        filemenu = wx.Menu()
        filemenu.Append(ID_EXIT,"&Quitter"," Quitter le programme")

        # Setting up the Tools Menu
        self._tool_menu = toolmenu = wx.Menu()
        toolmenu.Append(ID_ALIAS, "Éditeur d'&alias", "")
        toolmenu.Append(ID_TRIGGER, "Éditeur de &déclencheurs", "")
        toolmenu.Append(ID_FILTERS, "Éditeur de &filtres", "")

        # Setting up login menu
        self._connection_menu = login = wx.Menu()
        self._connection_menu_ids = []
        try:
            self._mud_registry = MudRegistry()
        except (OSError, ValueError) as exc:
            self._mud_registry = MudRegistry(load=False)
            wx.CallAfter(wx.MessageBox, str(exc), 'Connexions non chargées', wx.OK | wx.ICON_ERROR, self)
        self.refreshConnectionMenu()

        helpmenu = wx.Menu()
        helpmenu.Append(ID_ABOUT, "À &propos de...","Information à propos de NTLyntin64")
        
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&Fichier")
        menuBar.Append(toolmenu, "&Commandes")
        menuBar.Append(login, "C&onnexion")
        menuBar.Append(helpmenu, "&Aide")
        self.SetMenuBar(menuBar)
        #event table
        self.Bind(wx.EVT_MENU, self.OnAbout, id=ID_ABOUT)                                                   
        self.Bind(wx.EVT_MENU, self.OnExit, id=ID_EXIT)
        self.Bind(wx.EVT_MENU, self.onAddMud, id=ID_ADD_MUD)
        self.Bind(wx.EVT_MENU, self.onManageMuds, id=ID_MANAGE_MUDS)
        self.Bind(wx.EVT_MENU, self.onCommand, id=ID_ALIAS)
        self.Bind(wx.EVT_MENU, self.onCommand, id=ID_TRIGGER)
        self.Bind(wx.EVT_MENU, self.onFilters, id=ID_FILTERS)
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Bind(wx.EVT_CHAR_HOOK, self.OnSystemKeyDown)

        #create main container        
        self.panel = wx.Panel(self, -1)
        #create widgets
        self._text = wx.TextCtrl( self.panel,
                                    ID_TEXT,
                                    "",
                                    wx.DefaultPosition,
                                    wx.Size(80,40),
                                    style=wx.TE_MULTILINE )
        self._text.Bind(wx.EVT_CHAR, self._ignoreThis)
        self._txtbuffer = wx.TextCtrl( self.panel,
                                         ID_TEXT_BUFFER,
                                         "",
                                         wx.DefaultPosition,
                                         wx.Size(80,40),
                                         style=wx.TE_MULTILINE )
        self._txtbuffer.Bind(wx.EVT_CHAR, self._ignoreThis)

        self._txtbuffer.Show(0)

        self._entry = CommandEntry(self.panel, ID_ENTRY, '', myui)

        #create vertical sizer to hold the widgets
        self.vsizer=wx.BoxSizer(wx.VERTICAL)
        self.vsizer.Add(self._text, 1, wx.EXPAND|wx.ALL, 5)
        self.vsizer.Add(self._entry,  0, wx.EXPAND|wx.ALL, 5)

        #attach sizer to panel
        self.panel.SetSizer(self.vsizer)
        self.panel.SetAutoLayout(1)
        self.vsizer.Fit(self.panel)
        self.Show(1)
        hot._hwnd = wx.GetTopLevelParent(self).GetHandle()
        self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
    
    def OnActivate(self, e):
      if e.GetActive():
        hot.KeyDownID = []
        hot._suppressed_keys.clear()
        hot._hwnd = self.GetHandle()
        key.refresh()
        history = self._history_window
        if history and not history._close and history.IsShown():
          history.Raise()
          history.control.SetFocus()
        else:
          self._entry.SetFocus()
      e.Skip()
        
    def OnSystemKeyDown(self, event):
        if event.AltDown() and event.GetKeyCode() == wx.WXK_F4:
            self.Close()
            return
        event.Skip()

    def _ignoreThis(self, event):
        #following line is useful for debugging keycodes
        #print event.GetKeyCode()
        
        if event.ControlDown() or event.AltDown() or event.MetaDown():
            event.Skip()
            return
        code = event.GetUnicodeKey()
        if code == wx.WXK_NONE or code < 32:
            event.Skip()
            return
        # Do not modify the text control during its native CHAR event.
        def redirect():
            if self._closing:
                return
            self._entry.SetFocus()
            self._entry.WriteText(chr(code))
        wx.CallAfter(redirect)

    def refreshConnectionMenu(self):
        for identifier in self._connection_menu_ids:
            self.Unbind(wx.EVT_MENU, id=identifier)
        self._connection_menu_ids = []
        for item in list(self._connection_menu.GetMenuItems()):
            self._connection_menu.DestroyItem(item)
        self._connection_menu.Append(ID_ADD_MUD, '&Ajouter un MUD…')
        self._connection_menu.Append(ID_MANAGE_MUDS, '&Gérer les MUDs…')
        profiles = self._mud_registry.all()
        if profiles:
            self._connection_menu.AppendSeparator()
        for profile in profiles:
            item = self._connection_menu.Append(wx.ID_ANY, profile['name'].replace('&', '&&'),
                    'Se connecter à %s' % profile['name'])
            identifier = item.GetId()
            self._connection_menu_ids.append(identifier)
            self.Bind(wx.EVT_MENU, lambda event, row=profile: queue_connection(row), id=identifier)

    def onFilters(self, event):
        dialog = GagEditorDialog(self)
        try:
            dialog.ShowModal()
        finally:
            dialog.Destroy()

    def onAddMud(self, event):
        dialog = MudConnectionDialog(self, self._mud_registry)
        try:
            if dialog.ShowModal() == wx.ID_OK:
                self.refreshConnectionMenu()
        finally:
            dialog.Destroy()

    def onManageMuds(self, event):
        dialog = ManageMudConnectionsDialog(self, self._mud_registry)
        try:
            dialog.ShowModal()
        finally:
            dialog.Destroy()
            self.refreshConnectionMenu()

    def chooseMud(self, new_session=False):
        profiles = self._mud_registry.all()
        if not profiles:
            self.onAddMud(None)
            return
        if len(profiles) == 1:
            queue_connection(profiles[0], new_session=new_session)
            return
        dialog = wx.SingleChoiceDialog(self, 'Choisissez le MUD auquel vous connecter :',
                                        'Connexion à un MUD', [row['name'] for row in profiles])
        try:
            if dialog.ShowModal() == wx.ID_OK:
                queue_connection(profiles[dialog.GetSelection()], new_session=new_session)
        finally:
            dialog.Destroy()

    def OnAbout(self,e):
        msg = ABOUT_TEXT
        dialog = wx.MessageDialog(self,msg,"À propos de NTLyntin64",wx.OK)
        dialog.ShowModal() 
        dialog.Destroy() 
        
    def OnExit(self,e):
        if self._closing:
            return
        self._closing = True
        try:
            self._entry.unload()
        finally:
            event.ShutdownEvent().enqueue()
            self.Destroy()
    
    def onCommand(self, event):
        id = event.GetId()
        #print 'id_alias:',ID_ALIAS
        #print 'id_trigger:',ID_TRIGGER
        #print 'event.GetId:', event.GetId()
        
        if id == ID_ALIAS:
            mode = ALIAS
            title = "Éditeur d'alias"
        elif id == ID_TRIGGER:
            mode = ACTION
            title = "Éditeur de trigger"

        #print mode
        if not self.command_editor:
            self.command_editor = CommandEditor(self, -1, title, mode = mode)
        else:
            self.command_editor.mode = mode

        self.command_editor.resetWidgetsForMode(mode)
        self.command_editor.CentreOnParent()
        self.command_editor.Show(1)
        
class MudApp(wx.App):
        
    def OnInit(self):
        self._topFrame = MudFrame(None,
                                  -1,
                                  'Lyntin',
                                  wx.DefaultPosition,
                                  wx.Size(800, 600))
        #not sure why we have to set this in the wxApp instance.  I assumed that it
        #would be set in the wxFRame instance, but when I do that, it is
        # *convientently* ignored
        self._topFrame._text.SetBackgroundColour("BLACK")
        self._topFrame._text.SetForegroundColour("WHITE")
        self._topFrame.Show(1)

        self.SetTopWindow(self._topFrame)
        return 1

class wxui(base.BaseUI):
    """
    This is a ui class which handles the wxPython user interface
    """
    def __init__(self):
        base.BaseUI.__init__(self)
        

        #internal ui queue
        self._event_queue = queue.Queue() # map of session -> (bold, foreground, background)

        # map of session -> (bold, foreground, background)
        self._currcolors = {}

        # ses -> string
        self._unfinishedcolor = {}

        self._viewhistory = 0
        self._do_i_echo = 0 # JLP
        
        # holds a map of window names -> window references
        self._windows = {}


        self._wx = MudApp(0)

        self._wx._topFrame._entry.SetFocus()
        
        #since the entry control is created before the wxui is finished being created,
        #we set it afterward.  A bit of an ugly hack, but not sure how to get around it.
        self._wx._topFrame._entry._wxui = self
        
        self.queue_timer = wx.Timer(self._wx, ID_QUEUE_TIMER)
        self._wx.Bind(wx.EVT_TIMER, self.dequeue, id=ID_QUEUE_TIMER)
        self.dequeue()

        exported.hook_register("mudecho_hook", self.echo)
        exported.hook_register("to_user_hook", self.write)
        


    def runui(self):
        global HELP_TEXT
        exported.add_help("wxui", HELP_TEXT)
        exported.write_message("For wx help type \"#help wxui\".")
        exported.add_command("colorcheck", colorcheck_cmd)


        #start the wxPython mainloop here
        self._wx.MainLoop()

    def wantMainThread(self):
        # wxPython needs the main thread of execution so we return
        # a 1 here.
        return 1


    def dequeue(self, event = None):
        hot.pollRecovery()
        qsize = self._event_queue.qsize()
        if qsize > 10:
            qsize = 10

        for i in range(qsize):
          try:
            ev = self._event_queue.get_nowait()
            ev.execute(self)
          except Exception:
            import logging
            logging.exception("UI event failed")
        self.queue_timer.Start(25, 1)

        
    def settitle(self, title=""):
        """
        Sets the title bar to the Lyntin title plus the given string.

        @param title: the title to set
        @type  title: string
        """
        if title:
            title = constants.LYNTINTITLE + title
        else:
            title = constants.LYNTINTITLE
        self._event_queue.put(_TitleEvent(self._wx, title))
        
    def removeWindow(self, windowname):
        """
        This removes a NamedWindow from our list of NamedWindows.

        @param windowname: the name of the window to write to
        @type  windowname: string
        """
        if windowname in self._windows:
            del self._windows[windowname]
    
    def writeWindow_internal(self, windowname, message):
        if windowname not in self._windows:
            self._windows[windowname] = NamedWindow(windowname, self, self._wx)
        self._windows[windowname].write(message)
        
        
    def writeWindow(self, windowname, message):
        """
        This writes to the window named "windowname".  If the window
        does not exist, we spin one off.  It handles ansi text and
        messages just like writing to the main window.
    
        @param windowname: the name of the window to write to
        @type  windowname: string
    
        @param message: the message to write to the window
        @type  message: string or Message instance
        """
        self._event_queue.put(_WriteWindowEvent(windowname, message))
        
    def pageUp(self, event):
        self._page(event, -1)

    def pageDown(self, event):
        self._page(event, 1)

    def _page(self, event, inc):
        tf = self._wx._topFrame
        e = tf._entry
        t = tf._text
        if inc == 1:
            start = 0
            end = t.GetNumberOfLines() - 1
        else:
            start = t.GetNumberOfLines() - 1
            end = 0
        if self._viewhistory == 0:
            self._history_line = start - inc
            self._viewhistory = 1
            e._edit_mode = True
        if event.ControlDown():
            nb = 22
        else:
            nb = 1
        for i in range(nb):
            if self._history_line == end:
                break
            self._history_line += inc
            while not t.GetLineText(self._history_line) or\
                  t.GetLineText(self._history_line).strip() == ">":
                if self._history_line == end:
                    break
                self._history_line += inc
        e.SetValue(t.GetLineText(self._history_line))
        e.SetSelection(-1, -1)
##        return
##        """ Handles prior (Page-Up) events."""
##        if self._viewhistory == 0:
##            self._wx._topFrame.vsizer.Insert(0,
##                                             self._wx._topFrame._txtbuffer,
##                                             1,
##                                             wx.EXPAND|wx.ALL, 5)
##            self._wx._topFrame._txtbuffer.Show(1)
##            #tell the vertical sizer to recalc its layout so that the
##            #txtbuffer gets resized.
##            self._wx._topFrame.vsizer.Layout()
##            self._viewhistory = 1
##            self._wx._topFrame._txtbuffer.Clear()
##            lotofstuff = self._wx._topFrame._text.GetValue()
##            self._wx._topFrame._txtbuffer.AppendText(lotofstuff)
            
##    def pageDown(self):
##        tf = self._wx._topFrame
##        e = tf._entry
##        t = tf._text
##        if self._viewhistory == 1:
##            self._history_line += 1
##            if self._history_line > t.GetNumberOfLines() - 1:
##                self._history_line = t.GetNumberOfLines() - 1
##        e.SetValue(t.GetLineText(self._history_line))
####        return
####        """ Handles next (Page-Down) events."""
####        if self._viewhistory == 1:
####            # yscroll down stuff
####            self._wx.topFrame._txtbuffer.ScrollToLine(self._wx._txtbuffer.GetCurrentLine())
    
    def escape(self, event):
        tf = self._wx._topFrame
        e = tf._entry
        t = tf._text
        if self._viewhistory == 1:
            self._viewhistory = 0
            if e._content:
                e.SetValue(e._content)
        else:
            e.Clear()
##        return
##        """ Handles escape (Escape) events."""
##        if self._viewhistory == 1:
##            self._wx._topFrame.vsizer.Remove(self._wx._topFrame._txtbuffer)
##            self._wx._topFrame._txtbuffer.Show(0)
##            self._wx._topFrame.vsizer.Layout()
##            self._viewhistory = 0
##        else:
##            self._wx._topFrame._entry.Clear()
            
    def echo(self, args):
        """ This turns echo on and off on the CommandEntry widget."""
        yesno = args["yesno"]
        if yesno==1:
            # echo on
            self._do_i_echo = 1
        else:
            # echo off
            self._do_i_echo = 0
            
    def write(self, args):
        """
        This writes text to the text buffer for viewing by the user.
        This is overridden from the 'base.BaseUI'.
        """
        self._event_queue.put(_OutputEvent(args))


    def write_internal(self, args):
        mess = args["message"]
        if isinstance(mess, str):
            mess = message.Message(mess, message.LTDATA)

        line = mess.data
        ses = mess.session

        if line == '' or self.showTextForSession(ses) == 0:
            return

     
        color, leftover = buffer_write(mess, self._wx._topFrame._text, self._currcolors, 
                                   self._unfinishedcolor)

        if mess.type == message.MUDDATA:
            self._unfinishedcolor[ses] = leftover
            self._currcolors[ses] = color
            
    def colorCheck(self):
        """
        Goes through and displays all the combinations of fg and bg
        with the text string involved.  Purely for debugging
        purposes.
        """
        fgkeys = ['30','31','32','33','34','35','36','37']
        bgkeys = ['40','41','42','43','44','45','46','47']

        #used for convienence, as I was being lazy and didnt wanna type it
        #out all the time
        txt_widget = self._wx._topFrame._text

        txt_widget.AppendText('color check:\n')
        for bg in bgkeys:
            for fg in fgkeys:
              txt_widget.GetDefaultStyle().SetTextColour(fg_color_codes[fg]) 
              txt_widget.GetDefaultStyle().SetBackgroundColour(bg_color_codes[bg])
              txt_widget.AppendText(fg)
              txt_widget.GetDefaultStyle().SetTextColour(fg_color_codes["b" +fg])
              txt_widget.AppendText("b" + fg)
            txt_widget.AppendText('\n')
            for fg in fgkeys:
              txt_widget.GetDefaultStyle().SetTextColour(fg_color_codes[fg]) 
              txt_widget.GetDefaultStyle().SetBackgroundColour(bg_color_codes["b" + bg])
              txt_widget.AppendText(fg)
              txt_widget.GetDefaultStyle().SetTextColour(fg_color_codes["b" +fg])
              txt_widget.GetDefaultStyle().SetBackgroundColour(bg_color_codes["b" + bg])
              txt_widget.AppendText("b" + fg)
            txt_widget.AppendText('\n')
        txt_widget.AppendText('\n')
        txt_widget.AppendText('\n')

#create ShortcutHook class instance
hot = Shortcut()

class CommandEntry(wx.TextCtrl):
    """ This class handles the user input area."""

    def __init__(self, master, id, text, wxui):
        """ Initializes and sets the key-bindings."""
        self._unloaded = True
        self._exit_dialog_open = False
        self._wxui = wxui
        self._inputstack = []
        self._autotyper = None
        self._autotyper_ses = None
        self_parent = master
        self._editMode = True

        wx.TextCtrl.__init__(self,master, id, text, style = wx.TE_PROCESS_ENTER) #|wx.TE_PASSWORD)
        
        #since wxPython doesnt bind events the same way as TKinter,
        #this is used as a map between the keycode, and the func to call
        self._key_func_map ={
                   wx.WXK_RETURN: self.createInputEvent,
                   wx.WXK_TAB: self.insertTab,
                   wx.WXK_PAGEUP: self.callPrior,
                   wx.WXK_UP: self.insertPrevCommand,
                   wx.WXK_DOWN: self.insertNextCommand,
                   wx.WXK_PAGEDOWN: self.callNext,
                   'Ctrl-T': self.startAutotyper,
                   'Ctrl-U': self.callKillLine,
                   'Ctrl-M': self.createInputEvent,
                   wx.WXK_ESCAPE: self.callEsc,
                   wx.WXK_F1: self.callBinding,
                   wx.WXK_F2: self.callBinding,
                   wx.WXK_F3: self.callBinding,
                   wx.WXK_F4: self.callBinding,
                   wx.WXK_F5: self.callBinding,
                   wx.WXK_F6: self.callBinding,
                   wx.WXK_F7: self.callBinding,
                   wx.WXK_F8: self.callBinding,
                   wx.WXK_F9: self.callBinding,
                   wx.WXK_F10: self.callBinding,
                   wx.WXK_F11: self.callBinding,
                   wx.WXK_F12: self.callBinding,
                   wx.WXK_NUMPAD_UP: self.callKP8,
                   wx.WXK_NUMPAD_RIGHT: self.callKP6,
                   wx.WXK_NUMPAD_LEFT: self.callKP4,
                   wx.WXK_NUMPAD_DOWN: self.callKP2,
                   wx.WXK_NUMPAD_PAGEUP: self.callKP9,
                   wx.WXK_NUMPAD_HOME: self.callKP7,
                   wx.WXK_NUMPAD_BEGIN: self.callKP5,
                   wx.WXK_NUMPAD_PAGEDOWN: self.callKP3,
                    wx.WXK_NUMPAD_END: self.callKP1}
        self.Bind(wx.EVT_KEY_DOWN, self.onKeyDown)
        self.Bind(wx.EVT_CHAR, self.onChar)
        self.Bind(wx.EVT_KEY_UP, self.onKeyUp)
        
        
        self.hist_index = -1
        self._wxui = wxui
        self.saveinputhighlight = 0
        self._edit_mode = False
        self._content = ""
        self._vm = None #ViewManager
        self._sm = None #SpeechManager (VoiceManager)
        
          
        #add hotkey
        
        hot.addHotkey(['Capital','Y'],self.up)
        hot.addHotkey(['Capital','U'],self.northWest)
        hot.addHotkey(['Capital','I'],self.north)
        hot.addHotkey(['Capital','O'],self.northEast)
        hot.addHotkey(['Capital','P'],self.getObjets)
        hot.addHotkey(['Capital','H'],self.getExits)
        hot.addHotkey(['Capital','J'],self.west)
        hot.addHotkey(['Capital','K'],self.look)
        hot.addHotkey(['Capital','L'],self.east)
        hot.addHotkey(['Capital','M'],self.getCharacters)
        hot.addHotkey(['Capital','N'],self.down)
        hot.addHotkey(['Capital','Oem_Comma'],self.southWest)
        hot.addHotkey(['Capital','Oem_Period'],self.south)
        hot.addHotkey(['Alt','Capital','Oem_Period'],self.down)
        hot.addHotkey(['Capital','Oem_2'],self.southEast)
        hot.addHotkey(['Capital','Oem_8'],self.getCorpses)
        hot.addHotkey(['Ctrl','Tab'],self.nextSession)
        hot.addHotkey(['Ctrl','Return'],self.newSession)
        hot.addHotkey(['Ctrl','Alt','U'],self.displayCurentViewUp)
        hot.addHotkey(['Ctrl','Alt','I'],self.chooseExit)
        hot.addHotkey(['Ctrl','Alt','O'],self.volumeUp)
        #hot.addHotkey(['Ctrl','Alt','P'],self.fun1)
        hot.addHotkey(['Ctrl','Alt','K'],self.setProfile)
        #hot.addHotkey(['Ctrl','Alt','L'],self.fun1)
        #hot.addHotkey(['Ctrl','Alt','M'],self.fun1)
        hot.addHotkey(['Ctrl','Alt','Oem_Comma'],self.displayCurentViewDown)
        hot.addHotkey(['Ctrl','Alt','Oem_2'],self.volumeDown)
        #hot.addHotkey(['Ctrl','Alt','Oem_8'],self.fun1)
        hot.addHotkey(['Ctrl','Y'],self.changeView,param=[1])
        hot.addHotkey(['Ctrl','U'],self.getMsg,param=[7])
        hot.addHotkey(['Ctrl','I'],self.getMsg,param=[8])
        hot.addHotkey(['Ctrl','O'],self.getMsg,param=[9])
        hot.addHotkey(['Ctrl','P'],self.changeView,param=[4])
        hot.addHotkey(['Ctrl','H'],self.changeView,param=[2])
        hot.addHotkey(['Ctrl','J'],self.getMsg,param=[4])
        hot.addHotkey(['Ctrl','E'],self.setEcho)
        hot.addHotkey(['Ctrl','K'],self.getMsg,param=[5])
        hot.addHotkey(['Ctrl','L'],self.getMsg,param=[6])
        hot.addHotkey(['Ctrl','M'],self.changeView,param=[5])
        hot.addHotkey(['Ctrl','N'],self.changeView,param=[3])
        hot.addHotkey(['Ctrl','Oem_Comma'],self.getMsg,param=[1])
        hot.addHotkey(['Ctrl','Oem_Period'],self.getMsg,param=[2])
        hot.addHotkey(['Ctrl','Oem_2'],self.getMsg,param=[3])
        hot.addHotkey(['Ctrl','Oem_8'],self.changeView,param=[6])
        hot.addHotkey(['Ctrl','Shift','O'],self.musicVolumeUp)
        hot.addHotkey(['Ctrl','Shift','Oem_2'],self.musicVolumeDown)
        hot.addHotkey(['Ctrl','Alt','Left'],self.west)
        hot.addHotkey(['Ctrl','Alt','Right'],self.east)
        hot.addHotkey(['Ctrl','Alt','Up'],self.north)
        hot.addHotkey(['Ctrl','Alt','Down'],self.south)
        hot.addHotkey(['Ctrl','Up'],self.displayCurentViewUp)
        hot.addHotkey(['Ctrl','Down'],self.displayCurentViewDown)
        self.load()
        self.Bind(wx.EVT_SET_FOCUS, self.OnSetFocus)
        #self.Bind(wx.EVT_KILL_FOCUS, self.OnKillFocus)
    
    def OnSetFocus(self, e):
      hot._hwnd = wx.GetTopLevelParent(self).GetHandle()
      hot.KeyDownID.clear()
      hot._suppressed_keys.clear()
      key.refresh()
      e.Skip()
      
    def OnKillFocus(self, e):
      #hot._focus = False
      pass
        
    def fun1(self):
      exported.write_message("coucou")
    
    def fun2(self, nbr):
      exported.write_message(nbr) 

    def load(self):
        """Initializes the module by binding all the commands."""
        self._vm  = ViewManager()
        self._sm = VoiceManager()
        exported.add_manager("view", self._vm)
        exported.hook_register("mud_filter_hook", self._vm.mudfilter, 100)
        exported.hook_register("to_user_hook", self._vm.touserhook, 100)
        exported.add_manager("voice", self._sm)
        exported.hook_register("to_user_hook", self._sm.lyntin_profile)
        exported.hook_register("mud_filter_hook", self._sm.mud_profile)
        hot.start()
        self._unloaded = False
        
    
    def __del__(self):
      self.unload()
    
    def unload(self):
        """ Unbinds the commands (for when we reimport the module)."""
        if self._unloaded:
            return
        self._unloaded = True
        hot.end()
        exported.remove_manager("view")
        exported.hook_unregister("mud_filter_hook", self._vm.mudfilter)
        exported.hook_unregister("to_user_hook", self._vm.touserhook)
        exported.remove_manager("voice")
        exported.hook_unregister("to_user_hook", self._sm.lyntin_profile)
        exported.hook_unregister("mud_filter_hook", self._sm.mud_profile)
        
        

    def editModeOn(self):
        if not self._edit_mode:
            self._edit_mode = True
            self.SetValue(self._content)
            self.SetInsertionPointEnd()
    def say(self, text):
      self.stopSpeech()
      return self._sm.getVoiceData(exported.get_current_session()).say(text, force=True)
    def stopSpeech(self):
      self._sm.getVoiceData(exported.get_current_session()).stop()
    def display(self, text, voice=True):
      if text == "" or text == None:
        return
      if voice:
        self.say(text)
      self._edit_mode = True
      self.SetValue(text)
      self._editMode = False
    def play(self, filename):
      try:
        play('./sounds/%s' % filename)
      except:
        exported.write_message("couldn't play sound: %s" % filename)
    def volume(self, v):
      try:
        if 0 <= v <= 100:
          setVolume(v)
          self.play("Volume.ogg")
        else:
          self.play("OutRange1.ogg")
      except:
        exported.write_message("couldn't set volume")

    def volumeDown(self):
      self.volume(getVolume()-5)
      
    def volumeUp(self):
      self.volume(getVolume()+5)

    def musicVolumeDown(self):
      music.player.adjust_volume(-5)
      self.play("Volume.ogg")

    def musicVolumeUp(self):
      music.player.adjust_volume(5)
      self.play("Volume.ogg")

    def getCurentView(self):
      vd = self._vm.getViewData(exported.get_current_session())
      return vd.getCurentView()
    def viewUI(self, text):
      frame = wx.GetTopLevelParent(self)
      history = getattr(frame, '_history_window', None)
      if history and not history._close:
        history.Raise()
        history.control.SetFocus()
        return
      vd = self._vm.getViewData(exported.get_current_session())
      title = "Historique : %s" % vd._curent_view
      # The window follows this view: new messages appear while it is open.
      historyView = History(self.Parent, title, WX.DefaultPosition, WX.Size(800,600), text,
                            view=vd.getCurentView())
      historyView.CentreOnParent()
      self.Parent.Enable(False)
      historyView.Show(1)
      historyView.control.SetFocus()
         
    def onKeyDown(self, event):
      
      keycode = event.GetKeyCode()
      keyname = keyMap.get(keycode, None)
      
      if keycode == 0:
        keyname = None
      elif keycode < 27:
        keyname = "Ctrl-%s" % chr(ord('A') + keycode-1)
      if not event.ControlDown() and not event.AltDown() and not event.ShiftDown():
        if keyname in self._key_func_map:
          self._key_func_map[keyname](event)
        elif  keycode in self._key_func_map:
          self._key_func_map[keycode](event)
        elif 38 <= keycode <= 90:
          if not self._editMode:
            self._wxui.escape(event)
            self._editMode = True
      if not event.ControlDown() and not event.AltDown():
        if keycode == wx.WXK_TAB:
          self.viewUI(self.getCurentView().getMessages())
          return
      event.Skip()
    def onKeyUp(self, event):
      keycode = event.GetKeyCode()
      if keycode in [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_BACK]:
        self.editModeOn()
      event.Skip()
      
    def onChar(self, event):
      # AltGr/Ctrl+Alt characters must enter the editable command buffer.
      if event.AltDown() and event.ControlDown():
        unicode_key = event.GetUnicodeKey()
        if unicode_key != wx.WXK_NONE and 0 <= unicode_key <= 0x10ffff:
          if chr(unicode_key).isprintable():
            self.editModeOn()
            event.Skip()
            return
      # Preserve Windows accelerators, including Alt+F4, before processing
      # the client's function-key bindings.
      if event.AltDown() or event.ControlDown() or event.MetaDown():
        event.Skip()
        return
      keycode = event.GetKeyCode()
      if keycode in [wx.WXK_LEFT, wx.WXK_RIGHT, wx.WXK_BACK]:
        self.editModeOn()
      if keycode in self._key_func_map:
        return
      else:
        unicode_key = event.GetUnicodeKey()
        if unicode_key == wx.WXK_NONE or not 0 <= unicode_key <= 0x10ffff:
          event.Skip()
          return
        character = chr(unicode_key)
        if not character.isprintable():
          event.Skip()
          return
        if self._edit_mode:
          event.Skip()
        else:
##        if keycode == wx.WXK_BACK:
##          self._content = self._content[:-1]
##        else:
            if event.MetaDown() or event.AltDown() or event.CmdDown() or event.ControlDown():
              event.Skip()
            else:
              self.SetValue(character)
              self.SetInsertionPointEnd()
              self._content += character
          
    def displayCurentViewDown(self):
      self.display(self.getCurentView().cursor_down())
    def displayCurentViewUp(self):
      self.display(self.getCurentView().cursor_up())
    def command(self, cmd, internal=0):
      self.stopSpeech()
      exported.lyntin_command(cmd,internal)
    def newSession(self):
      try:
        if queue_current_mud(exported.get_current_session()):
          return
      except ValueError as exc:
        self.say("Impossible d’ouvrir une nouvelle connexion : %s" % exc)
        return
      wx.GetTopLevelParent(self).chooseMud(new_session=True)
    def nextSession(self):
      list = exported.get_active_sessions()
      if len(list) <= 2:
        self.say("Il y a moins de deux sessions actives.")
        return
      next = False
      current = exported.get_current_session()
      vd = self._sm.getVoiceData(current)
      for ses in list:
        if str(ses) != "session.Session common":
          if next == True:
            vd.setEcho(0)
            exported.set_current_session(ses)
            vd = self._sm.getVoiceData(ses)
            vd.setEcho(1)
            self.say("Session : %s" % ses.getName())
            return
          if str(ses) == str(current):
            next = True
      for ses in list:
        if str(ses) != "session.Session common":
          if next == True:
            vd.setEcho(0)
            exported.set_current_session(ses)
            vd = self._sm.getVoiceData(ses)
            vd.setEcho(1)
            self.say("Session : %s" % ses.getName())
            return
    def look(self):
      self.command("look",1)
    def up(self):
      self.command("haut")
    def down(self):
      self.command("bas")
    def north(self):
      self.command("nord")
    def south(self):
      self.command("sud")
    def east(self):
      self.command("est")
    def west(self):
      self.command("ouest")
    def northEast(self):
      self.command("nord-est")
    def southEast(self):
      self.command("sud-est")
    def northWest(self):
      self.command("nord-ouest")
    def southWest(self):
      self.command("sud-ouest")
    def chooseExit(self):
      if self._exit_dialog_open:
        return
      ses = exported.get_current_session()
      vd = self._vm.getViewData(ses)
      exits = vd.getExits()
      if not exits:
        self.say('Aucune sortie disponible.')
        return
      frame = wx.GetTopLevelParent(self)
      snapshot = vd.roomExit
      self._exit_dialog_open = True
      def send_selected(selected):
        if not frame or frame._closing:
          return
        if vd.roomExit != snapshot:
          self.say('Les sorties ont changé. Ouvrez à nouveau la liste.')
        elif selected in exits:
          event.InputEvent(selected, ses=ses).enqueue()

      def closed(selected):
        self._exit_dialog_open = False
        if not frame or frame._closing:
          return
        restore_command_focus(frame)
        if selected is not None:
          # Let screen-reader focus announcements finish before MUD output.
          wx.CallLater(200, send_selected, selected)

      try:
        ExitChoicePopup(self, exits, closed)
      except Exception:
        self._exit_dialog_open = False
        restore_command_focus(frame)
        raise
    def getMsg(self,nbr):
      cv = self.getCurentView()
      self.display(cv.getMsg(nbr-1))
    def getCharacters(self):
      vd = self._vm.getViewData(exported.get_current_session())
      self.display(vd.getRoomStr("characters"))
    def getObjets(self):
      vd = self._vm.getViewData(exported.get_current_session())
      self.display(vd.getRoomStr("objets"))
    def getExits(self):
      vd = self._vm.getViewData(exported.get_current_session())
      self.say(vd.roomExit or 'Aucune sortie disponible.')
    def getCorpses(self):
      vd = self._vm.getViewData(exported.get_current_session())
      self.display(vd.getRoomStr("corpses"))

    def setEcho(self):
      vd = self._sm.getVoiceData(exported.get_current_session())
      self.say(vd.setEcho(-1))
      return
    
    def setProfile(self):
      self._sm.changeProfile()
      return

    def changeView(self, nbr):
      vd = self._vm.getViewData(exported.get_current_session())
      self.say(vd.change_view(nbr-1))
    def createInputEvent(self, event):
        """ Handles the <KeyPress-Return> event."""
        if self._edit_mode:
            val = fix_unicode(self.GetValue())
            self._edit_mode = False
            self._content = ""
        else:
            val = fix_unicode(self._content)
            self._content = ""
        self._wxui.handleinput(val)

        if self.saveinputhighlight == 1:
            self.SetSelection(-1, -1)
        else:
            self.Clear()
        self.hist_index = -1
        self._wxui._viewhistory = 0

    def _executeBinding(self, binding, quiet=False):
        """ Returns the alias for this keybinding."""
        ses = exported.get_current_session()
        action = exported.get_manager("alias").getAlias(ses, binding)
        if action:
            self._wxui.handleinput(action)
            return 1
        else:
            if not quiet:
                exported.write_error("%s is currently not bound to anything." % binding)
            return 0

    def callBinding(self, event):
        """ Handles arbitrary bindings of function call keypresses."""
        if event.ControlDown() or event.AltDown() or event.ShiftDown():
          return "break"
        if self._executeBinding(keyMap[event.GetKeyCode()], quiet=True) == 1:
            return "break"

        # these two lines help in debugging stuff we bound
        # print repr(event)
        # print repr(event.__dict__)

    def callKP9(self, event):
        if self._executeBinding("WXK_NUMPAD9") == 1:
            return "break"

    def callKP8(self, event):
        if self._executeBinding("WXK_NUMPAD8") == 1:
            return "break"

    def callKP7(self, event):
        if self._executeBinding("WXK_NUMPAD7") == 1:
            return "break"

    def callKP6(self, event):
        if self._executeBinding("WXK_NUMPAD6") == 1:
            return "break"

    def callKP5(self, event):
        if self._executeBinding("WXK_NUMPAD5") == 1:
            return "break"

    def callKP4(self, event):
        if self._executeBinding("WXK_NUMPAD4") == 1:
            return "break"

    def callKP3(self, event):
        if self._executeBinding("WXK_NUMPAD3") == 1:
            return "break"

    def callKP2(self, event):
        if self._executeBinding("WXK_NUMPAD2") == 1:
            return "break"

    def callKP1(self, event):
        if self._executeBinding("WXK_NUMPAD1") == 1:
            return "break"
    def startAutotyper(self, event):
        """
       This will start the autotyper. It will be called if you type <Ctrl>+<t>.
       There can be only one autotyper at a time. The autotyper cannot be started
       for the common session.
       """
        if self._autotyper != None:
            self._autotyper.Show(1)
            #exported.write_error("cannot start autotyper: already started.")
            return
    
        session = exported.get_current_session()
    
        if session.getName() == "common":
            exported.write_error("autotyper cannot be applied to common session.")
            return
    
        self._autotyper = Autotyper(self._wxui._wx._topFrame, self.autotyperDone)
        self._autotyper_ses = session
    
        exported.write_message("autotyper: started.")

    def autotyperDone(self, data):
        """
       This is a callback for the autotyper. It will be called when the autotyper
       is finished.
      
        @param data: the autotyper data--None if the user clicked on "Cancel"
            or closed the autotyper window
        @type  data: string or None  
        """
        if data != None:
            self._autotyper_ses.writeSocket(data)
            
        exported.write_message("autotyper: done.")

    def clearInput(self):
        """ Clears the text widget."""
        self.Clear()
        
    def insertTab(self, event):
        """ Handles the <KeyPress-Tab> event."""
        pass
        
    def callPrior(self, event):
        """ Handles the <KeyPress-Prior> event."""
        self._wxui.pageUp(event)
        
    def callNext(self, event):
        """ Handles the <KeyPress-Next> event."""
        self._wxui.pageDown(event)
        
    def callEsc(self, event):
        """ Handles the <KeyPress-Escape> event.

        Escape toggles between the command entry and the history window:
        here it opens (or goes back to) the history of the current view.
        The typed line is kept; Ctrl+U still clears it."""
        if self._wxui._viewhistory == 1:
            # Leaving the command history: put back the line being typed.
            self._wxui.escape(event)
        self.viewUI(self.getCurentView().getMessages())
    
    def callKillLine(self, event): 
        """ Handles the <Control-KeyPress-u> event."""
        self.Clear()

    def callPushInputStack(self, event):
        """ Handles the <Control-KeyPress-Up> event."""
        self._inputstack.append((self.index('insert'),self.GetValue()))
        self.Clear()

    def callPopInputStack(self,event):
        """ Handles the <Control-KeyPress-Down> event."""
        if len(self._inputstack) < 1:
            return
        poppage = self._inputstack.pop()
        self.Clear()
        self.SetValue(poppage[1])
        
    def currentDraft(self):
        """Returns the command being typed, without a read message or a
        recalled command (same rule as the Enter key)."""
        if not self._editMode or self._wxui._viewhistory == 1:
            # The line shows a read message or a line of the output buffer.
            draft = self._content
        elif self._edit_mode:
            draft = self.GetValue()
        else:
            draft = self._content
        if self.hist_index != -1:
            hist = exported.get_history()
            if 0 <= self.hist_index < len(hist) and draft == hist[self.hist_index]:
                # A recalled command, unchanged: the draft is what was typed
                # before going through the history.
                draft = getattr(self, 'current_input', '')
        return fix_unicode(draft or '').strip()

    def parkDraft(self):
        """Empties the command line for a new command. A command being typed
        goes into the command history, where Up brings it back."""
        draft = self.currentDraft()
        if draft:
            exported.get_manager("history").recordHistory(draft)
        self.Clear()
        self._content = ""
        self._edit_mode = False
        self._editMode = True
        self.hist_index = -1
        self._wxui._viewhistory = 0

    def insertPrevCommand(self, event):
        self._edit_mode = True
        """ Handles the <KeyPress-Up> event."""
        hist = exported.get_history()
        if self.hist_index == -1:
            self.current_input = self.GetValue()
        if self.hist_index < len(hist) - 1:
            self.hist_index = self.hist_index + 1
            self.Clear()
            self.SetValue(hist[self.hist_index])
        self.SetInsertionPointEnd()

    def insertNextCommand(self, event):
        self._edit_mode = True
        """ Handles the <KeyPress-Down> event."""
        hist = exported.get_history()
        if self.hist_index == -1:
            return
        self.hist_index = self.hist_index - 1
        if self.hist_index == -1:
            self.Clear()
            self.SetValue(self.current_input)
            
        else:
            self.Clear()
            self.SetValue(hist[self.hist_index])        
        self.SetInsertionPointEnd()


class NamedWindow:
    """
    This creates a window for the wxpythonui which you can then write to 
    programmatically.  This allows modules to spin off new named windows
    and write to them.
    """
    def __init__(self, windowname, master, wxui):
      """
      Initializes the window

      @param windowname: the name of the new window
      @type  windowname: string

      @param master: the main wxpythonui window
      @type  master: wxFrame
      """
      self._parent = master
      self._frame = wx.Frame(master, -1, 'Lyntin -- ' + windowname)
      self._windowname = windowname
    
      # map of session -> (bold, foreground, background)
      self._currcolors = {}

      # ses -> string
      self._unfinishedcolor = {}

      self._do_i_echo = 1

      self._txt = wx.TextCtrl( self._frame, -1, "",
                                 wx.DefaultPosition,
                                 wx.Size(80,40), wx.TE_MULTILINE )
       
    def close(self):
      """
      Closes and destroys references to this window.
      """
      self._parent.removeWindow(self._windowname)
      self._frame.Close()

    def write(self, msg):
      """
      This writes text to the text buffer for viewing by the user.
  
      This is overridden from the 'base.BaseUI'.
      """
      if type(msg) == tuple:
        msg = msg[0]

      if isinstance(msg, str):
          msg = message.Message(message, message.LTDATA)

      line = msg.data
      ses = msg.session

      if line == '':
          return

      color, leftover = buffer_write(msg, self._txt, self._currcolors, 
                                   self._unfinishedcolor)

      if msg.type == message.MUDDATA:
          self._unfinishedcolor[ses] = leftover
          self._currcolors[ses] = color

class Autotyper(wx.Frame):
    """
    Autotyper class, it generates the autotyper window, waits for entering text
    and then calls a function to work with the text.
    """
    def __init__(self, master, sendfunc):
        """
        Initializes the autotyper.

        @param master: the parent window
        @type  master: wxWindow

        @param sendfunc: the callback function
        @type  sendfunc: function
        """
        self._sendfunc = sendfunc

        send_btn = wx.NewIdRef()
        cancel_btn = wx.NewIdRef()

        wx.Frame.__init__(self, master, -1, "Lyntin -- Autotyper")
        self._panel = wx.Panel(self, -1)
        self._vsizer = wx.BoxSizer(wx.VERTICAL)
        self._txt = wx.TextCtrl( self._panel, -1, '',wx.DefaultPosition,
                                   wx.Size(80,40), wx.TE_MULTILINE )
        self._vsizer.Add(self._txt, 1,
                         wx.EXPAND|wx.ALL, 5)

        self._hsizer = wx.BoxSizer(wx.HORIZONTAL)
        self._sendbtn = wx.Button( self._panel, send_btn, "Send",
                                     wx.DefaultPosition, wx.DefaultSize, 0 )
        self._hsizer.Add( self._sendbtn, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )

        self.cancel_btn = wx.Button( self._panel, cancel_btn, "Cancel",
                                       wx.DefaultPosition, wx.DefaultSize, 0 )
        self._hsizer.Add( self.cancel_btn, 0, wx.ALIGN_CENTRE|wx.ALL, 5 )

        self._vsizer.AddSizer( self._hsizer, 0,
                               wx.ALIGN_RIGHT|wx.ALL, 5 )
        self.Bind(wx.EVT_BUTTON, self.send, id=send_btn)
        self.Bind(wx.EVT_BUTTON, self.cancel, id=cancel_btn)
        self._panel.SetSizer(self._vsizer)
        self._panel.SetAutoLayout(1)
        self._vsizer.Fit(self._panel)

        self.CentreOnParent()
        self.Show(1)
        self._txt.SetFocus()
        self._txt.SetInsertionPoint(0)

    def send(self, event):
        """
        Will be called when the user clicks on the 'Send' button.
        """
        text = fix_unicode(self._txt.GetValue())
        self._sendfunc(text)
        self._txt.Clear()
        self.Show(0)

    def cancel(self, event):
        """
        Will be called when the user clicks on the 'Cancel' button.
        """
        self._sendfunc(None)
        self.Show(0)

class CommandEditor(wx.Frame):
    ID_COMMAND_LOAD = wx.NewIdRef()

    def __init__(self, parent, id, text, mode = 0, savefile = ''):
        wx.Frame.__init__(self,parent, id, text)
        self.parent = parent
        self.mode = mode
        self.mainpanel = CommandPanel(self, -1)
        self.mainpanel.Fit()
        self.mainpanel.command_list.InsertColumn(0, "")
        self.mainpanel.command_list.InsertColumn(1, "")
        self.mainpanel.txt_command_name.SetFocus()
        self.alias_dict = {}
        self.action_dict = {}
        self.savefile = savefile
        
        filemenu = wx.Menu()
        filemenu.Append(self.ID_COMMAND_LOAD, "&Charger un fichier","Charger un fichier...")
        
        # Creating the menubar.
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu,"&Fichier")
        self.SetMenuBar(menuBar)  

        self.Bind(wx.EVT_MENU, self.onLoadCommand, id=self.ID_COMMAND_LOAD)  
        self.Bind(wx.EVT_BUTTON, self.OnExit, id=self.mainpanel.btn_close.GetId())
        self.Bind(wx.EVT_BUTTON, self.addCommand, id=self.mainpanel.btn_add.GetId())
        self.Bind(wx.EVT_BUTTON, self.removeCommand, id=self.mainpanel.btn_delete.GetId())
        self.Bind(wx.EVT_CLOSE, self.OnExit)
        self.Bind(wx.EVT_CHAR_HOOK, self.onEditorKeyDown)
        self.Bind(wx.EVT_LIST_ITEM_SELECTED, self.onCommandSelected, id=self.mainpanel.command_list.GetId())
        self.mainpanel.command_list.Bind(wx.EVT_KEY_DOWN, self.onCommandListKeyDown)
        self.session = exported.get_current_session()
        self._proposal_selected = None
        self.Bind(wx.EVT_LISTBOX, self.onProposalSelected, self.mainpanel.proposal_list)
        self.Bind(wx.EVT_LISTBOX_DCLICK, self.addCommand, self.mainpanel.proposal_list)
        self.getCommandsFromMud(self.mode)

        if self.mode == ALIAS:
            if self.alias_dict:
                self.fillCommandWidget(self.alias_dict)
        elif self.mode == ACTION:
            if self.action_dict:
                self.fillCommandWidget(self.action_dict)
            
        
        
    def onCommandListKeyDown(self, key_event):
        if key_event.GetKeyCode() in (wx.WXK_DELETE, wx.WXK_NUMPAD_DELETE):
            self.removeCommand(key_event)
            return
        key_event.Skip()

    def onEditorKeyDown(self, key_event):
        if key_event.GetKeyCode() == wx.WXK_ESCAPE:
            self.OnExit(key_event)
            return
        key_event.Skip()

    def getColumnText(self, index, col):
        item = self.mainpanel.command_list.GetItem(index, col)
        return item.GetText()

    def resetWidgetsForMode(self, mode):
        self.mode = mode
        self.session = exported.get_current_session()
        self._proposal_selected = None
        self.getCommandsFromMud(mode)
        editor = ""
        if mode == ALIAS:
            editor = "Éditeur d'alias"
            title = ["Raccourci à saisir", "Commande(s) à exécuter pour ce raccourci"]
            help_text = "Un alias remplace un raccourci que vous tapez par une ou plusieurs commandes.\nExemple : soin lance cast soin. Séparez plusieurs commandes par un point-virgule (;)."
            dict = self.alias_dict
        elif mode == ACTION:
            editor = "Éditeur de déclencheurs"
            title = ["Texte reçu qui déclenche l’action", "Commande(s) à exécuter automatiquement"]
            help_text = "Un déclencheur exécute des commandes quand le MUD envoie le texte recherché.\nExemple : Vous avez faim déclenche eat pain. Séparez plusieurs commandes par un point-virgule (;)."
            dict = self.action_dict

        self.SetTitle(editor)
        self.mainpanel.label_command_name.SetLabel(title[0])
        self.mainpanel.txt_command_name.SetName(title[0])
        self.mainpanel.txt_command_name.SetHelpText(help_text)
        self.mainpanel.txt_command_replacement.SetName(title[1])
        self.mainpanel.txt_command_replacement.SetHelpText("Saisissez les commandes à exécuter, séparées par un point-virgule si nécessaire.")
        self.mainpanel.label_replacement.SetLabel(title[1])
        self.mainpanel.command_list.SetName("Alias définis" if mode == ALIAS else "Déclencheurs définis")
        for column, label in enumerate(title):
            item = self.mainpanel.command_list.GetColumn(column)
            item.SetText(label)
            self.mainpanel.command_list.SetColumn(column, item)
        self.mainpanel.help_text.SetLabel(help_text)
        self.fillCommandWidget(dict)
        self.mainpanel.Layout()
        self.refreshProposals()
        self.SetClientSize((920, 560))
    
    def _getSelectedIndices(self):
        state =  wx.LIST_STATE_SELECTED
        indices = []
        found = 1
        lastFound = -1
        while found:
                index = self.mainpanel.command_list.GetNextItem(
                        lastFound,
                        wx.LIST_NEXT_ALL,
                        state,
                )
                if index == -1:
                        break
                else:
                        lastFound = index
                        indices.append( index )
        return indices


    def onCommandSelected(self, event):
        self._proposal_selected = None
        self.mainpanel.proposal_list.SetSelection(wx.NOT_FOUND)
        currentItem = event.GetIndex()
        self.mainpanel.txt_command_name.SetValue(self.mainpanel.command_list.GetItemText(currentItem))
        self.mainpanel.txt_command_name.Refresh()
        self.mainpanel.txt_command_replacement.SetValue(self.getColumnText(currentItem, 1))
        self.mainpanel.txt_command_replacement.Refresh()


    def onLoadCommand(self, event):
        dlg = wx.FileDialog(self, "Choisir un fichier", '.', "", "*.*", wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            filename=dlg.GetFilename()
            dirname=dlg.GetDirectory()
        else:
            dlg.Destroy()
            return

        
        old_dir = os.getcwd()
        os.chdir(dirname)
        file = str(dirname+"\\"+filename).replace("\\", "\\\\")
        cmnd = r"#read %s" % file
        exported.lyntin_command(cmnd)
        #self.resetWidgetsForMode(self.mode)
        self.getCommandsFromMud(mode = self.mode)
        if self.mode == ALIAS:
            if self.alias_dict:
                self.fillCommandWidget(self.alias_dict)
        elif self.mode == ACTION:
            if self.action_dict:
              self.fillCommandWidget(self.action_dict)
            
        dlg.Destroy()
        os.chdir(old_dir)
                        
    def getCommandsFromMud(self, mode):
        kind = 'alias' if mode == ALIAS else 'action'
        rows = exported.get_manager(kind).getInfoMappings(kind, self.session)
        if mode == ALIAS:
            self.alias_dict = {row['alias']: row['expansion'] for row in rows}
        else:
            self.action_dict = {row['trigger']: row['action'] for row in rows}

    def refreshProposals(self):
        from lyntin.trigger_proposals import is_multimonde, load_editor_proposals
        kind = 'alias' if self.mode == ALIAS else 'action'
        self.proposals = load_editor_proposals(kind, self.session)
        key, value = ('alias', 'expansion') if kind == 'alias' else ('trigger', 'action')
        self.mainpanel.proposal_list.Set([row[key]+' → '+row[value] for row in self.proposals])
        visible = is_multimonde(self.session)
        self.mainpanel.proposal_label.Show(visible)
        self.mainpanel.proposal_list.Show(visible)
        self.mainpanel.Layout()

    def onProposalSelected(self, event):
        index = self.mainpanel.proposal_list.GetSelection()
        if index == wx.NOT_FOUND:
            return
        row = self.proposals[index]
        self._proposal_selected = row
        key, value = ('alias', 'expansion') if self.mode == ALIAS else ('trigger', 'action')
        self.mainpanel.txt_command_name.SetValue(row[key])
        self.mainpanel.txt_command_replacement.SetValue(row[value])

    def refreshRules(self):
        if not self or self.IsBeingDeleted():
            return
        self.getCommandsFromMud(self.mode)
        self._proposal_selected = None
        self.mainpanel.proposal_list.SetSelection(wx.NOT_FOUND)
        self.fillCommandWidget(self.alias_dict if self.mode == ALIAS else self.action_dict)

    def addToCommandWidget(self, name, expansion):
        row_ndx = self.mainpanel.command_list.GetItemCount()
        self.mainpanel.command_list.InsertItem(row_ndx,name)
        self.mainpanel.command_list.SetItem(row_ndx,1,expansion)
        self.mainpanel.txt_command_name.Clear()
        self.mainpanel.txt_command_replacement.Clear()
        self.mainpanel.txt_command_name.SetFocus()
        self.mainpanel.command_list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        self.mainpanel.command_list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
        
    def updateCommandWidget(self, name, expansion, mode):
        if mode == ALIAS:
            command_list = list(self.alias_dict.keys())
        elif mode == ACTION:
            command_list = list(self.action_dict.keys())
            
        command_list.sort()
        row_ndx = command_list.index(name)
        self.mainpanel.command_list.SetItem(row_ndx,1,expansion)
        self.mainpanel.command_list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
        self.mainpanel.command_list.SetColumnWidth(1, wx.LIST_AUTOSIZE)
        
    def fillCommandWidget(self, dict):
        self.mainpanel.command_list.DeleteAllItems()
        dict_list = list(dict.keys())
        dict_list.sort()
        for entry in dict_list:
            self.addToCommandWidget(entry, dict[entry])

    def addCommand(self, event):
        from lyntin.trigger_proposals import EditorRuleEvent
        name = self.mainpanel.txt_command_name.GetValue().strip()
        expansion = self.mainpanel.txt_command_replacement.GetValue().strip()
        if not name or not expansion:
            return
        kind = 'alias' if self.mode == ALIAS else 'action'
        row = dict(self._proposal_selected or {})
        if kind == 'alias':
            row.update(alias=name, expansion=expansion)
        else:
            row.update(trigger=name, action=expansion)
        EditorRuleEvent(self.session, kind, row, lambda: wx.CallAfter(self.refreshRules),
                        proposal=self._proposal_selected is not None).enqueue()

    def removeCommand(self, event):
        from lyntin.trigger_proposals import EditorRuleEvent
        indices = self._getSelectedIndices()
        if not indices:
            return
        kind = 'alias' if self.mode == ALIAS else 'action'
        key = 'alias' if kind == 'alias' else 'trigger'
        for index in indices:
            name = self.mainpanel.command_list.GetItemText(index)
            EditorRuleEvent(self.session, kind, {key: name},
                            lambda: wx.CallAfter(self.refreshRules), remove=True).enqueue()

    def OnExit(self,e):
        self.Show(0)

        
def buffer_write(msg, txtbuffer, currentcolor, unfinishedcolor):
    """
    Handles writing messages to a text widget taking into accound
    ANSI colors, message types, session scoping, and a variety of
    other things.

    @param message: the Message to write to the buffer
    @type  message: Message

    @param txtbuffer: the text buffer to write to
    @type  txtbuffer: Text

    @param currentcolor: the current color that we should start with
    @type  currentcolor: color (list of ints)

    @param unfinishedcolor: the string of unfinished ANSI color stuff
        that we'll prepend to the string we're printing
    @type  unfinishedcolor: string

    @returns: the new color and unfinished color
    @rtype: list of ints, string
    """
    line = msg.data
    ses = msg.session

    if msg.type == message.ERROR:
        if line.endswith("\n"):
            line = "%s%s%s\n" % (ansi.get_color("b blue"), 
                          line[:-1], 
                          ansi.get_color("default"))
        else:
            line = "%s%s%s" % (ansi.get_color("b blue"), 
                        line[:-1], 
                        ansi.get_color("default"))

    elif msg.type == message.USERDATA:
        if myui._do_i_echo == 1:
            if line.endswith("\n"):
                line = "%s%s%s\n" % (ansi.get_color("b blue"), 
                            line[:-1], 
                            ansi.get_color("default"))
            else:
                line = "%s%s%s" % (ansi.get_color("b blue"), 
                          line[:-1], 
                          ansi.get_color("default"))
        else:
            # if echo is not on--we don't print this
            return currentcolor, unfinishedcolor

    elif msg.type == message.LTDATA:
        if line.endswith("\n"):
            line = "# %s\n" % line[:-1].replace("\n", "\n# ")
        else:
            line = "# %s" % line.replace("\n", "\n# ")


    # now we go through and handle writing all the data
    index = 0
    start = 0

    # we prepend the session name to the text if this is not the 
    # current session sending text and if the Message is session
    # scoped.
    if (ses != None and ses != exported.get_current_session()):
        pretext = "[%s]" % ses.getName()
 
        if line.endswith("\n"):
            line = (pretext + line[:-1].replace("\n", "\n" + pretext) + "\n")
        else:
            line = pretext + line.replace("\n", "\n" + pretext)


    # we remove all \\r stuff because it's icky
    line = line.replace("\r", "")

    tokens = ansi.split_ansi_from_text(line)

    # each session has a saved current color for MUDDATA.  we grab
    # that current color--or use our default if we don't have one
    # for the session yet.  additionally, some sessions have an
    # unfinished color as well--in case we got a part of an ansi 
    # color code in a mud message, and the other part is in another 
    # message.
    if msg.type == message.MUDDATA:
        color = currentcolor.get(ses, list(DEFAULT_COLOR))
        leftover = unfinishedcolor.get(ses, "")

    else:
        color = list(DEFAULT_COLOR)
        leftover = ""


    for mem in tokens:
        if ansi.is_color_token(mem):
            color, leftover = ansi.figure_color([mem], color, leftover)

        else:
            format = []
            fg = ""
            bg = ""

            # handle reverse
            if color[ansi.PLACE_REVERSE] == 0:
                if color[ansi.PLACE_FG] == -1:
                    fg = "37"
                else:
                    fg = str(color[ansi.PLACE_FG])

                if color[ansi.PLACE_BG] != -1:
                    bg = str(color[ansi.PLACE_BG])
                elif color[ansi.PLACE_BG] == -1:
                    bg = "40"
                    

            else:
                if color[ansi.PLACE_BG] == -1:
                    fg = "30"

                else:
                    fg = str(color[ansi.PLACE_BG] - 10)

                if color[ansi.PLACE_FG] == -1:
                    bg = "47"
                else:
                    bg = str(color[ansi.PLACE_FG] + 10)

            # handle bold
            if color[ansi.PLACE_BOLD] == 1:
                fg = "b" + fg

            # handle underline
            if color[ansi.PLACE_UNDERLINE] == 1:
                format.append("u")

            txtbuffer.GetDefaultStyle().SetTextColour(fg_color_codes[fg])
            if bg:
                txtbuffer.GetDefaultStyle().SetBackgroundColour(bg_color_codes[bg])

#            mem = my_filters(mem)

            #following line used for wxTextCtrl
            txtbuffer.AppendText(mem)

    return color, leftover

    
def fix_unicode(text):
    """
    Unicode to standard string translation--fixes unicode bug.
    """
    if type(text) == str:
        return text
    else:
        return text

def colorcheck_cmd(ses, args, input):
    """
    Prints out all the colors so you can verify that things are working
    properly.
    """
    myengine = exported.get_engine()
    myengine._ui._event_queue.put(_ColorCheckEvent())

def colorcheck_cmd(ses, args, input):
    """
    Prints out all the colors so you can verify that things are working
    properly.
    """
    myengine = exported.get_engine()
    myengine._ui._event_queue.put(_ColorCheckEvent())

