-
Notifications
You must be signed in to change notification settings - Fork 0
/
gmidievk.py
executable file
·415 lines (360 loc) · 13 KB
/
gmidievk.py
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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
#!/usr/bin/python3
"""
Gtk GUI to configure midievk
Require xdotool, python3-tk
"""
import logging
from math import floor, log10
from midiev import (MidiKeyboard, MIDITYPE,
CONTROLLER, NOTEON, NOTEOFF, CHANNEL)
from midievk import MidiToXdo
from options import (OPTIONS, NB_CTL_STEPS_IDX, get_all_midi_devices, DEVICE,
CONFIG_FILE, CONFIG_FORMAT, CONFIG_LOADER, TITLE,
NOTE_PRESSURE_MIDDLE_DELTA, NOTE_PRESSURE_STRONG_DELTA,
CTL_DECREASING)
try:
import Tkinter as tk
import tkMessagebox as messagebox
import tkFont
import ttk
except ImportError: # Python 3
import tkinter as tk
from tkinter import messagebox
import tkinter.font as tkFont
import tkinter.ttk as ttk
GUI_DESC_MODE = {
'Note-on': ['keydown', 'key'],
'Note-on(middle)': ['keydown', 'key'],
'Note-on(strong)': ['keydown', 'key'],
'Note-off': ['keyup', 'key'],
'CC+': ['relative', 'absolute'],
'CC-': ['relative', 'absolute']
}
class TkWindow(tk.Frame):
"""TkWindow"""
_tree_selection = None
_tree_sort_order = [(0,False), (1,False)]
midikb = None
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.midixdo = MidiToXdo()
self._programming_mode = tk.IntVar()
# self._programming_mode_live = False
self.init_gui()
self.read_configs()
if len(self._cbox_device.get()):
self.connect_to_device(None)
def init_gui(self):
"""init_gui"""
self.parent.title(TITLE)
self.pack(fill="both", expand=True)
frame_main = ttk.Frame(self)
frame_main.pack(side="left", fill="both", expand=True, padx=5, pady=5)
frame_treeview = ttk.Frame(frame_main)
frame_treeview.pack(side="bottom", fill="both", expand=True)
frame_menu = ttk.Frame(frame_main)
frame_menu.pack(side="top", fill="both", expand=False)
frame_scrollbar = ttk.Frame(self)
frame_scrollbar.pack(side="right", fill="y",
expand=False, padx=5, pady=5)
tree_headers = [
('Type', 90),
('Channel', 10),
('Keybind', 90),
('Mode', 5)
]
self._tree = ttk.Treeview(
frame_treeview,
columns=[name for name, _ in tree_headers],
show="headings",
height=20
)
self._tree.pack(side='left', fill='both', expand=True)
self._tree.bind('<<TreeviewSelect>>', self.selected_item)
self._tree.bind('<<TreeviewClose>>', self._on_mouse_click)
self._tree.bind('<<TreeviewOpen>>', self._on_mouse_click)
self._tree.bind('<KeyPress>', self._on_key_press)
for column, width in tree_headers:
self._tree.heading(column, text=column)
self._tree.column(
column,
width=(
tkFont.Font().measure(column) +
width),
anchor='w')
vsb = ttk.Scrollbar(
frame_scrollbar,
orient="vertical",
command=self._tree.yview)
vsb.pack(side='right', fill='y')
self._tree.configure(yscrollcommand=vsb.set)
ttk.Label(frame_menu,
text="Device : ").pack(side='left', padx=5, pady=5)
self._cbox_device = tk.StringVar()
try:
device_options = get_all_midi_devices()
cbox = ttk.Combobox(
frame_menu,
textvariable=self._cbox_device,
values=device_options,
)
cbox.pack(side='left', padx=5, pady=5)
cbox.set(DEVICE or device_options.split()[0])
cbox.bind("<<ComboboxSelected>>", self.connect_to_device)
except IndexError:
messagebox.showwarning(
TITLE, "No midi device detected ! Leave...")
exit()
ttk.Checkbutton(frame_menu, text='Programming mode',
variable=self._programming_mode
).pack(side='left', padx=5, pady=5)
ttk.Button(frame_menu, text='Quit',
command=self.on_closing
).pack(side='right', padx=5, pady=5)
ttk.Button(frame_menu, text='Save configs',
command=self.save_configs
).pack(side='right', padx=5, pady=5)
self._programming_mode.set(0)
def connect_to_device(self, event):
"""connect_to_device"""
self.midikb = MidiKeyboard(self._cbox_device.get())
self.midixdo.set_midi_device(self.midikb)
def read_configs(self, file_format=CONFIG_FORMAT, file_name=CONFIG_FILE):
"""read_configs
:param file_format:
:param file_name:
"""
if file_format in CONFIG_LOADER:
conf_exists = self.midixdo.read_configs(
file_format,
file_name,
config_line_process=self._gui_insert
)
if not conf_exists:
self._programming_mode.set(1)
else:
self.sort_treeview()
def save_configs(self, file_format=CONFIG_FORMAT, file_name=CONFIG_FILE):
"""save_configs
:param file_format:
:param file_name:
"""
self.midixdo.save_configs(file_format, file_name)
def sort_treeview(self):
for i, r in self._tree_sort_order:
self.sort_treeview_column(i, reverse=r)
def sort_treeview_column(self, column, reverse=False):
"""sort_treeview
:param column:
:param reverse:
"""
new_treeview = [
(self._tree.set(child, column), child)
for child in self._tree.get_children('')]
new_treeview.sort(reverse=reverse)
# rearrange items in sorted positions
for index, (_, child) in enumerate(new_treeview):
self._tree.move(child, '', index)
def selected_item(self, tree_item):
"""selected_item
:param tree_item:
"""
if tree_item:
self._tree_selection = self._tree.selection()
def _gui_insert(self, midikey, values):
"""_gui_ins
:param midikey:
:param values:
"""
typ = values['type']
key_note = values['channel']
keybind = values['keybind']
keymode = values['mode']
mod = None
val = None
if keybind:
keybind_tab = keybind.split('+')
mod = '+'.join(keybind_tab[0:-1])
val = keybind_tab[-1]
mod = mod or ''
val = val or '<Undefined>'
self._tree.insert(
'', 'end', midikey, tags=midikey,
values="{} {} {} {}".format(
typ, key_note,
mod + val,
GUI_DESC_MODE[typ][keymode] if typ in GUI_DESC_MODE else ''
)
)
def _ins(self, midikey, values):
"""_ins
:param midikey:
:param values:
"""
valuest = {'type': values[0],
'channel': values[1],
'keybind': None,
'mode': 0
}
self._gui_insert(midikey, valuest)
self.midixdo.insert(midikey, valuest)
def _update(self, midikey, values):
"""_update
:param midikey:
:param values:
"""
valuest = {'type': values[0],
'channel': values[1],
'keybind': None,
'mode': 0
}
self._gui_insert(midikey, valuest)
self.midixdo.insert(midikey, valuest)
def check_item(self, tree_item):
"""check_item
:param tree_item:
"""
if tree_item:
key = int(tree_item[0])
keytype = self.midixdo.get_key_type(key)
if keytype in GUI_DESC_MODE:
keyoption = self.midixdo.get_key_mode(key)
keyoption = int(not (keyoption or 0))
self._tree.set(tree_item, 3, GUI_DESC_MODE[keytype][keyoption])
self.midixdo.set_key_mode(key, keyoption)
def _on_mouse_click(self, event):
"""_on_mouse_click
:param event:
"""
if event is not None:
self.check_item(self._tree_selection)
def _on_key_press(self, event):
"""_on_key_press
:param event:
"""
key = event.__dict__['keysym']
# if not (self._programming_mode.get() or self._programming_mode_live):
if not self._programming_mode.get():
# if key == 'Return':
# self._programming_mode_live=True
if key == 'BackSpace':
self.set_current_key('', '<Undefined>')
return
if self._tree_selection:
midikey = int(self._tree_selection[0], 16)
keyoption = self.midixdo.get_key_mode(midikey)
# if note off and no event raised on note off ,then do nothing
if midikey >> 8 == 0x8 and not (keyoption or False):
return
state = event.__dict__['state']
modifier = ""
if state & (1 << 2):
modifier = "Ctrl+"
if state & (1 << 3) or state & (1 << 7):
modifier = modifier + "Alt+"
if state & (1 << 0):
modifier = modifier + "Shift+"
if state & (1 << 6):
modifier = modifier + "Super+"
# for child in self._tree.get_children():
# if key == self._tree.item(child, option="values")[2]:
# self._tree.set(child, 2, "<Undefined>")
#
# self._programming_mode_live=False
self.set_current_key(modifier, key)
def set_current_key(self, modifier, key):
"""set_current_key
:param modifier:
:param key:
"""
self._tree.set(self._tree_selection, 2, modifier+key)
self.midixdo.set_keybind(
int(self._tree.item(self._tree_selection, option="tag")[0]),
modifier + key
)
def _update_type(self, midikey, name):
"""set_current_key
:param modifier:
:param key:
"""
self._tree.set(midikey, 0, name)
self.midixdo.set_key_type(midikey, name)
def update_keys_list(self, command, midikey):
"""update_keys_list
:param code:
"""
miditype = command[MIDITYPE]
name = None
if miditype == NOTEOFF:
name = "Note-off"
elif miditype == NOTEON:
name = "Note-on" + (
"(middle)"
if midikey >> 12 == NOTE_PRESSURE_MIDDLE_DELTA
else
"(strong)"
if midikey >> 12 == NOTE_PRESSURE_STRONG_DELTA
else ""
)
elif miditype == CONTROLLER:
if OPTIONS[NB_CTL_STEPS_IDX] > 0:
ndigits = "%0" + \
str(int(floor(log10(OPTIONS[NB_CTL_STEPS_IDX]) + 1))) + "d"
name = "CC" + ndigits % (midikey >> 12) + \
'/' + str(OPTIONS[NB_CTL_STEPS_IDX])
else:
name = "CC" + ('-' if midikey >> 12 == CTL_DECREASING else '+')
if midikey not in self.midixdo:
channel = command[CHANNEL]
self._ins(midikey, (name, channel))
else:
self._update_type(midikey, name)
self.sort_treeview()
def check_midi_device(self):
"""check_midi_device"""
if self.midikb:
if self.midikb.is_running():
self.after(1, self.check_midi_device)
else:
print("Midi device is currently not monitored")
self.after(1000, self.check_midi_device)
return
else:
print("Midi device disappeared")
exit()
(command, key) = self.midixdo.parse_midi()
if key is not None:
if self._programming_mode.get():
# print key, command
self.update_keys_list(command, key)
idx = self._tree.index(key)
treeitem = self._tree.get_children()
movement = float((idx - 5) / len(treeitem))
self._tree.yview('moveto', movement)
self._tree.selection_set(key)
else:
try:
self._tree.selection_set(key)
except:
pass
self.midixdo.send_keystroke(command, key)
logging.debug('Key: %s %s', key, command)
def on_closing(self):
"""on_closing"""
logging.debug('User want to close the app')
self.after(500, self.midikb.stop_thread)
self.after(1000, self.parent.destroy)
logging.debug('Thanks for using this app :)')
def main():
"""main"""
# logging.basicConfig(level=logging.DEBUG)
logging.basicConfig(level=logging.INFO)
root = tk.Tk()
# root.geometry("400x300")
app = TkWindow(root)
root.protocol("WM_DELETE_WINDOW", app.on_closing)
root.after(500, app.check_midi_device)
root.mainloop()
if __name__ == '__main__':
main()