home · contact · privacy
Extend, reorganize commands server is capable of.
[plomrogue2-experiments] / client.py
1 #!/usr/bin/env python3
2
3 import urwid
4 import plom_socket_io
5 import socket
6 import threading
7
8
9 class UrwidSetup:
10
11     def __init__(self, socket):
12         """Build client urwid interface around socket communication.
13
14         Sets up all widgets for writing to the socket and representing data
15         from it. Sending via a self.EditToSocket widget is straightforward;
16         polling the socket for input from the server in parallel to the urwid
17         main loop not so much:
18
19         The urwid developers warn against sharing urwid resources among
20         threads, so having a socket polling thread for writing to an urwid
21         widget while other widgets are handled in other threads would be
22         dangerous. Urwid developers recommend using urwid's watch_pipe
23         mechanism instead: using a pipe from non-urwid threads into a single
24         urwid thread. We use self.recv_loop_thread to poll the socket, therein
25         write socket.recv output to an object that is then linked to by
26         self.server_output (which is known to the urwid thread), then use the
27         pipe to urwid to trigger it pulling new data from self.server_output to
28         handle via self.InputHandler. (We *could* pipe socket.recv output
29         directly, but then we get complicated buffering situations here as well
30         as in the urwid code that receives the pipe output. It's easier to just
31         tell the urwid code where it finds full new server messages to handle.)
32         """
33         self.socket = socket
34         self.main_loop = urwid.MainLoop(self.setup_widgets())
35         self.server_output = ['']
36         input_handler = getattr(self.InputHandler(self.reply_widget,
37                                                   self.map_widget,
38                                                   self.server_output),
39                                 'handle_input')
40         self.urwid_pipe_write_fd = self.main_loop.watch_pipe(input_handler)
41         self.recv_loop_thread = threading.Thread(target=self.recv_loop)
42
43     def setup_widgets(self):
44         """Return container widget with all widgets we want on our screen.
45
46         Sets up an urwid.Pile inside a returned urwid.Filler; top to bottom:
47         - an EditToSocket widget, prefixing self.socket input with 'SEND: '
48         - self.reply_widget, a urwid.Text widget printing self.socket replies
49         - a 50-col wide urwid.Padding container for self.map_widget, which is
50           to print clipped map representations
51         """
52         edit_widget = self.EditToSocket(self.socket, 'SEND: ')
53         self.reply_widget = urwid.Text('')
54         self.map_widget = urwid.Text('', wrap='clip')
55         map_box = urwid.Padding(self.map_widget, width=50)
56         widget_pile = urwid.Pile([edit_widget, self.reply_widget, map_box])
57         return urwid.Filler(widget_pile)
58
59     class EditToSocket(urwid.Edit):
60         """Extends urwid.Edit with socket to send input on 'enter' to."""
61
62         def __init__(self, socket, *args, **kwargs):
63             super().__init__(*args, **kwargs)
64             self.socket = socket
65
66         def keypress(self, size, key):
67             """Extend super(): on Enter, send .edit_text, and empty it."""
68             if key != 'enter':
69                 return super().keypress(size, key)
70             plom_socket_io.send(self.socket, self.edit_text)
71             self.edit_text = ''
72
73     class InputHandler:
74         """Delivers data from other thread to widget via message_container.
75
76         The class only exists to provide handle_input as a bound method, with
77         widget and message_container pre-set, as (bound) handle_input is used
78         as a callback in urwid's watch_pipe – which merely provides its
79         callback target with one parameter for a pipe to read data from an
80         urwid-external thread.
81         """
82
83         def __init__(self, widget1, widget2, message_container):
84             self.widget1 = widget1
85             self.widget2 = widget2
86             self.message_container = message_container
87
88         def handle_input(self, trigger):
89             """On input from other thread, either quit or write to widget text.
90
91             Serves as a receiver to urwid's watch_pipe mechanism, with trigger
92             the data that a pipe defined by watch_pipe delivers. To avoid
93             buffering trouble, we don't care for that data beyond the fact that
94             its receival triggers this function: The sender is to write the
95             data it wants to deliver into the container referenced by
96             self.message_container, and just pipe the trigger to inform us
97             about this.
98
99             If the message delivered is 'BYE', quits Urbit.
100             """
101             if self.message_container[0] == 'BYE':
102                 raise urwid.ExitMainLoop()
103                 return
104             self.widget1.set_text('SERVER: ' + self.message_container[0])
105             self.widget2.set_text('loremipsumdolorsitamet '
106                                   'loremipsumdolorsitamet'
107                                   'loremipsumdolorsitamet '
108                                   'loremipsumdolorsitamet\n'
109                                   'loremipsumdolorsitamet '
110                                   'loremipsumdolorsitamet')
111
112     def recv_loop(self):
113         """Loop to receive messages from socket and deliver them to urwid.
114
115         Writes finished messages from the socket to self.server_output[0],
116         then sends a single b' ' through self.urwid_pipe_write_fd to trigger
117         the urwid code to read from it.
118         """
119         import os
120         for msg in plom_socket_io.recv(self.socket):
121             self.server_output[0] = msg
122             os.write(self.urwid_pipe_write_fd, b' ')
123
124     def run(self):
125         """Run in parallel main and recv_loop thread."""
126         self.recv_loop_thread.start()
127         self.main_loop.run()
128         self.recv_loop_thread.join()
129
130
131 s = socket.create_connection(('127.0.0.1', 5000))
132 u = UrwidSetup(s)
133 u.run()
134 s.close()