1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
|
#!/usr/bin/env python3
import serial
import tkinter as tk
from tkinter import Text
import pystray
from pystray import MenuItem as item
from PIL import Image, ImageTk
from typing import Dict
import threading
import sys
from zope import component
import interfaces
from interfaces import endpoint
from interfaces.message import IMessage, Debug
import configparser
from os import path
script_path = path.dirname(path.realpath(__file__))
config_file = path.join(script_path, "config.ini")
config = configparser.ConfigParser(delimiters="=")
config.read(config_file)
from collections import OrderedDict
from configuration import Mapping
mapping = Mapping(config)
from queue import Queue
q = Queue()
component.provideAdapter(interfaces.endpoint.EndPoint)
#
# Guess the platform and the load the corresponding event listener
#
#
# How to connect to the peripherical
#
if config.has_section("connection.serial"):
from serial_conn import SerialConnection
endpoint = component.queryAdapter(SerialConnection(config["connection.serial"]), endpoint.IEndpoint)
endpoint.queue = q
endpoint.connect()
component.provideUtility(endpoint, interfaces.endpoint.IEndpoint)
elif config.has_section("connection.socket"):
from socket_conn import SocketConnection
endpoint = component.queryAdapter(SocketConnection(config["connection.socket"]), endpoint.IEndpoint)
endpoint.queue = q
component.provideUtility(endpoint, interfaces.endpoint.IEndpoint)
endpoint.connect()
if config.has_section("socket.serve"):
import socketserver
server = socketserver.Handler(config["socket.serve"], q)
else:
server = None
class Icon(object):
def __init__(self, image):
menu=(
item('Quit', self.quit_window),
item('Show', self.show_window, default=True),
item('Reset',self.reset),
)
self.icon=pystray.Icon("name", image, "Macropad companion", menu)
self.stop = threading.Event()
self.show_hide = threading.Event()
# Start the icon into a new thread in order to keep the main loop
# control
icon_thread = threading.Thread(target=self.icon.run)
self.icon_thread = icon_thread
def start(self):
self.icon_thread.start()
def quit(self):
self.icon.stop()
def quit_window(self):
self.stop.set()
def show_window(self):
self.show_hide.set()
def reset(self):
mapping.reset()
class Application(object):
def __init__(self):
self.window = tk.Tk()
self.text = Text(self.window, height=8)
## State of the #pplication
self.running = True
self.visible = False
self.focused_window = None
self.last_layout = None
component.provideHandler(self.log)
# Window property
self.window.withdraw()
self.window.title("Macropad companion")
icon = path.join(script_path, "favicon.ico")
try:
self.window.iconbitmap(icon)
except:
pass
self.text.pack()
# When closing, return back to the iconified mode
self.window.protocol("WM_DELETE_WINDOW", self.hide)
# Start the application in iconified mode
image=Image.open(icon)
self.icon = Icon(image)
self.icon.start()
component.handle(Debug("Started"))
def connect_desktop(self):
""" Launch the thread listening events from the desktop
"""
from sys import platform
component.handle(Debug(platform))
if platform == "win32":
import win32
window_listener = win32.Listener(mapping, q)
component.provideUtility(window_listener, interfaces.desktopEvent.IDesktop)
window_listener.start()
elif platform == 'linux':
import xlib
xlib_listener = xlib.Listener(mapping, q)
component.provideUtility(xlib_listener, interfaces.desktopEvent.IDesktop)
component.handle(Debug("Starting xlib"))
xlib_listener.start()
def hide(self):
self.icon.show_hide.clear()
self.visible = False
self.window.withdraw()
self.update()
def update(self):
if self.icon.stop.is_set():
self.icon.quit()
self.running = False
self.window.destroy()
component.queryUtility(interfaces.desktopEvent.IDesktop).stop()
return
if self.icon.show_hide.is_set():
if not self.visible:
self.window.deiconify()
else:
self.window.withdraw()
self.icon.show_hide.clear()
self.visible = not self.visible
@component.adapter(IMessage)
def log(self, message : str):
print(message.content)
try:
self.text.insert("1.0", "\n")
self.text.insert("1.0", message.content)
self.text.delete("200.0", "end")
except Exception as e:
print(e)
def send(self, data: str):
""" Send the configuration to the device.
The configuration can be either
- a dictionnary, and will be send as is
- a string, and will be load in a file
If the content is the same, ignore the message and return.
"""
if data == self.last_layout:
return
# Merge the new layout with the previous one, ignoring all the null.
self.last_layout = data
conn = component.queryUtility(interfaces.endpoint.IEndpoint)
if isinstance(data, dict):
conn.send(data)
elif isinstance(data, str):
layer = mapping.get(data, None)
if layer is not None:
conn.send(layer)
def associate(self, layout: Dict, name: str):
mapping[name] = layout
for key in layout.keys():
component.handle(Debug("Associating %s with %s" % (name, key)))
def exec(self):
try:
self.update()
if server is not None: server.update()
conn = component.queryUtility(interfaces.endpoint.IEndpoint)
if not conn.isConnected():
component.handle(Debug("Reconnecting…"))
conn.state = conn.STATE_CONNECTING
self.window.after(1000, conn.connect)
else:
# Check if we have something to read from the server, and by
# the by if the server is still active.
conn.fetch()
except Exception as e:
component.handle(Debug( str(e) ))
print(e)
# Got any error, stop the application properly
self.icon.stop.set()
if app.running:
self.window.after(200, self.exec)
while not q.empty():
last_layout, app_ = q.get(False)
self.send(last_layout)
if app_ is not None: self.associate(last_layout, app_)
if __name__ == '__main__':
# Start the main application, Initializing the message listener before
# listening desktop events
app = Application()
app.connect_desktop()
# Initialize the main loop
app.exec()
component.handle(Debug("Exec runned first"))
try:
app.window.mainloop()
except:
app.running = False
app.window.destroy()
app.icon.quit()
component.queryUtility(interfaces.desktopEvent.IDesktop).stop()
|