Project

Profile

Help

Download (6.45 KB) Statistics View on GitHub Reload from mirrored respository
| Branch: | Tag: | Revision:

github / src / client.py @ e8ebc4c5

1 2e7e9634 Vincent Le Goff
# Copyright (c) 2016, LE GOFF Vincent
2
# All rights reserved.
3
4
# Redistribution and use in source and binary forms, with or without
5
# modification, are permitted provided that the following conditions are met:
6
7
# * Redistributions of source code must retain the above copyright notice, this
8
#   list of conditions and the following disclaimer.
9
10
# * Redistributions in binary form must reproduce the above copyright notice,
11
#   this list of conditions and the following disclaimer in the documentation
12
#   and/or other materials provided with the distribution.
13
14
# * Neither the name of ytranslate nor the names of its
15
#   contributors may be used to endorse or promote products derived from
16
#   this software without specific prior written permission.
17
18
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
22
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
25
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
27
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28
29
"""This file contains the client that can connect to a MUD.
30 e1d2d0dc Vincent Le Goff

31
It is launched in a new thread, so as not to block the main thread.
32

33
"""
34
35 4d2b7a46 Vincent Le Goff
import os
36 e1d2d0dc Vincent Le Goff
import re
37
from telnetlib import Telnet, WONT, WILL, ECHO
38
import threading
39
import time
40
41
try:
42 11d4f23d Vincent Le Goff
    from UniversalSpeech import say
43
    from UniversalSpeech import braille as display_braille
44 e1d2d0dc Vincent Le Goff
except ImportError:
45
    say = None
46 a4ca19ed Vincent Le Goff
    display_braille = None
47 e1d2d0dc Vincent Le Goff
48 fa348e33 Vincent Le Goff
from sharp.engine import SharpScript
49
50 e1d2d0dc Vincent Le Goff
# Constants
51
ANSI_ESCAPE = re.compile(r'\x1b[^m]*m')
52
53
class Client(threading.Thread):
54
55
    """Class to receive data from the MUD."""
56
57 bf6b6eb0 Vincent Le Goff
    def __init__(self, host, port=4000, timeout=0.1, engine=None):
58 e1d2d0dc Vincent Le Goff
        """Connects to the MUD."""
59
        threading.Thread.__init__(self)
60
        self.client = None
61
        self.timeout = timeout
62 bf6b6eb0 Vincent Le Goff
        self.engine = engine
63 e1d2d0dc Vincent Le Goff
        self.running = False
64 fa348e33 Vincent Le Goff
        self.sharp_engine = SharpScript(engine, self)
65 f6bb9547 Vincent Le Goff
        self.triggers = []
66 e8ebc4c5 Vincent Le Goff
        self.macros = []
67 e1d2d0dc Vincent Le Goff
68
        # Try to connect to the specified host and port
69
        self.client = Telnet(host, port)
70
        self.running = True
71
72
    def run(self):
73
        """Run the thread."""
74
        while self.running:
75
            time.sleep(self.timeout)
76
            msg = self.client.read_very_eager()
77
            if msg:
78 f6bb9547 Vincent Le Goff
                for line in msg.splitlines():
79
                    for trigger in self.triggers:
80
                        trigger.feed(line)
81
82 e1d2d0dc Vincent Le Goff
                self.handle_message(msg)
83
84 a4ca19ed Vincent Le Goff
    def handle_message(self, msg, force_TTS=False, screen=True,
85
            speech=True, braille=True):
86 11d4f23d Vincent Le Goff
        """When the client receives a message.
87

88
        Parameters
89 a4ca19ed Vincent Le Goff
            msg: the text to be displayed (str)
90 11d4f23d Vincent Le Goff
            force_TTS: should the text be spoken regardless?
91 a4ca19ed Vincent Le Goff
            screen: should the text appear on screen?
92 11d4f23d Vincent Le Goff
            speech: should the speech be enabled?
93
            braille: should the braille be enabled?
94

95
        """
96 e1d2d0dc Vincent Le Goff
        pass
97
98 fa348e33 Vincent Le Goff
    def write(self, text):
99
        """Write text to the client."""
100
        if text.startswith("#"):
101
            self.sharp_engine.execute(text)
102
        else:
103
            self.client.write(text)
104
105 e1d2d0dc Vincent Le Goff
106
class GUIClient(Client):
107
108
    """Client specifically linked to a GUI window.
109

110
    This client proceeds to send the text it receives to the frame.
111

112
    """
113
114 bf6b6eb0 Vincent Le Goff
    def __init__(self, host, port=4000, timeout=0.1, engine=None):
115
        Client.__init__(self, host, port, timeout, engine)
116
        self.window = None
117 e1d2d0dc Vincent Le Goff
        if self.client:
118
            self.client.set_option_negotiation_callback(self.handle_option)
119
120 4d2b7a46 Vincent Le Goff
    def load_script(self, world):
121
        """Load the config.set script."""
122 fd61b98e Vincent Le Goff
        from game import Level
123
        level = self.engine.level
124
        self.engine.level = Level.world
125 4d2b7a46 Vincent Le Goff
        path = world.path
126
        path = os.path.join(path, "config.set")
127
        if os.path.exists(path):
128
            file = open(path, "r")
129
            content = file.read()
130
            file.close()
131
132
            # Execute the script
133
            self.sharp_engine.execute(content)
134
135 fd61b98e Vincent Le Goff
        # Put the engine level back
136
        self.engine.level = level
137
138 bf6b6eb0 Vincent Le Goff
    def link_window(self, window):
139
        """Link to a window (a GUI object).
140

141
        This objectt can be of various types.  The client only interacts
142
        with it in two ways:  First, whenever it receives a message,
143
        it sends it to the window's 'handle_message' method.  It also
144
        calls the window's 'handle_option' method whenever it receives
145
        a Telnet option that it can recognize.
146

147
        """
148
        self.window = window
149 fa348e33 Vincent Le Goff
        window.client = self
150 4d2b7a46 Vincent Le Goff
        self.load_script(window.world)
151 bf6b6eb0 Vincent Le Goff
152 a4ca19ed Vincent Le Goff
    def handle_message(self, msg, force_TTS=False, screen=True,
153
            speech=True, braille=True):
154 11d4f23d Vincent Le Goff
        """When the client receives a message.
155

156
        Parameters
157
            msg: the text to be displayed (str)
158
            force_TTS: should the text be spoken regardless?
159 a4ca19ed Vincent Le Goff
            screen: should the text appear on screen?
160 11d4f23d Vincent Le Goff
            speech: should the speech be enabled?
161
            braille: should the braille be enabled?
162

163
        """
164 7b7e38e9 Vincent Le Goff
        encoding = self.engine.settings["options.general.encoding"]
165
        msg = msg.decode(encoding, "replace")
166 e1d2d0dc Vincent Le Goff
        msg = ANSI_ESCAPE.sub('', msg)
167 a4ca19ed Vincent Le Goff
        if self.window and screen:
168 bf6b6eb0 Vincent Le Goff
            self.window.handle_message(msg)
169
170
        # In any case, tries to find the TTS
171 11d4f23d Vincent Le Goff
        if self.engine.TTS_on or force_TTS:
172 833f56ad Vincent Le Goff
            # If outside of the window
173
            window = self.window
174
            focus = window.focus if window else True
175
            if not focus and not self.engine.settings["options.TTS.outside"]:
176 11d4f23d Vincent Le Goff
                if not force_TTS:
177
                    return
178 833f56ad Vincent Le Goff
179 11d4f23d Vincent Le Goff
            if say and speech:
180 e1d2d0dc Vincent Le Goff
                say(msg, interrupt=False)
181 a4ca19ed Vincent Le Goff
            if braille and display_braille:
182 11d4f23d Vincent Le Goff
                display_braille(msg)
183 e1d2d0dc Vincent Le Goff
184
    def handle_option(self, socket, command, option):
185
        """Handle a received option."""
186 bf6b6eb0 Vincent Le Goff
        name = ""
187 e1d2d0dc Vincent Le Goff
        if command == WILL and option == ECHO:
188 bf6b6eb0 Vincent Le Goff
            name = "hide"
189 e1d2d0dc Vincent Le Goff
        elif command == WONT and option == ECHO:
190 bf6b6eb0 Vincent Le Goff
            name = "show"
191
192
        if name and self.window:
193
            self.window.handle_option(name)