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
|
#!/usr/bin/env python3
import threading
from os import path
import tkinter as tk
from tkinter import Text
import configparser
from sys import platform
import pystray
from pystray import MenuItem as item
from PIL import Image
from zope import component
import interfaces
from interfaces import endpoint
from interfaces.message import IMessage, Debug
import consumer
from configuration import Mapping
script_path = path.dirname(path.realpath(__file__))
config_file = path.join(script_path, "config.ini")
config = configparser.ConfigParser(delimiters="=")
config.read(config_file)
mapping = Mapping(config)
component.provideUtility(mapping, interfaces.configuration.IConfiguration)
#
# Guess the platform and the load the corresponding event listener
#
#
# How to connect to the peripherical
#
component.provideAdapter(interfaces.endpoint.EndPoint)
if config.has_section("connection.serial"):
from serial_conn import SerialConnection
endpoint = component.queryAdapter(
SerialConnection(config["connection.serial"]), endpoint.IEndpoint)
elif config.has_section("connection.socket"):
from socket_conn import SocketConnection
endpoint = component.queryAdapter(
SocketConnection(config["connection.socket"]), endpoint.IEndpoint)
component.provideUtility(endpoint, interfaces.endpoint.IEndpoint)
endpoint.connect()
if config.has_section("socket.serve"):
import socketserver
server = socketserver.Handler(config["socket.serve"])
else:
server = None
handler = consumer.SocketMessageConsumer()
handler.start()
class Icon():
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):
""" Start the icon.
Handler is runned in a dedicated thread to avoid blocking the
events from the main loop.
"""
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():
def __init__(self):
# Override the default function called when exception are reported
tk.Tk.report_callback_exception = self.report_callback_exception
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
"""
component.handle(Debug(platform))
if platform == "win32":
import win32
listener = win32.Listener(mapping)
elif platform == 'linux':
import xlib
listener = xlib.Listener(mapping)
component.handle(Debug("Starting xlib"))
component.provideUtility(listener, interfaces.desktopEvent.IDesktop)
listener.start()
def report_callback_exception(self, exc, val, tb):
""" Handle exception reported inside the Tk application.
This method overrid the default Tk.tk.report_callback_exception
method.
"""
import traceback
traceback.print_exception(exc, value=val, tb=tb)
self.icon.stop.set()
self.icon.quit()
self.running = False
self.window.destroy()
component.queryUtility(interfaces.desktopEvent.IDesktop).stop()
return
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():
print("stopping")
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 exec(self):
try:
self.update()
if server is not None:
server.update()
except BaseException 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)
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()
try:
app.window.mainloop()
except BaseException as e:
app.running = False
app.window.destroy()
app.icon.quit()
component.queryUtility(interfaces.desktopEvent.IDesktop).stop()
|