generated from navdeep-G/samplemod
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusbkeyboard.py
293 lines (231 loc) · 8.97 KB
/
usbkeyboard.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
import argparse
import tkinter as tk
KEY_CODES = {
0x04: ["a", "A"],
0x05: ["b", "B"],
0x06: ["c", "C"],
0x07: ["d", "D"],
0x08: ["e", "E"],
0x09: ["f", "F"],
0x0A: ["g", "G"],
0x0B: ["h", "H"],
0x0C: ["i", "I"],
0x0D: ["j", "J"],
0x0E: ["k", "K"],
0x0F: ["l", "L"],
0x10: ["m", "M"],
0x11: ["n", "N"],
0x12: ["o", "O"],
0x13: ["p", "P"],
0x14: ["q", "Q"],
0x15: ["r", "R"],
0x16: ["s", "S"],
0x17: ["t", "T"],
0x18: ["u", "U"],
0x19: ["v", "V"],
0x1A: ["w", "W"],
0x1B: ["x", "X"],
0x1C: ["y", "Y"],
0x1D: ["z", "Z"],
0x1E: ["1", "!"],
0x1F: ["2", "@"],
0x20: ["3", "#"],
0x21: ["4", "$"],
0x22: ["5", "%"],
0x23: ["6", "^"],
0x24: ["7", "&"],
0x25: ["8", "*"],
0x26: ["9", "("],
0x27: ["0", ")"],
0x28: ["\n", "\n"],
0x29: ["[ESC]", "[ESC]"],
0x2A: ["[BACKSPACE]", "[BACKSPACE]"],
0x2C: [" ", " "],
0x2D: ["-", "_"],
0x2E: ["=", "+"],
0x2F: ["[", "{"],
0x30: ["]", "}"],
0x32: ["#", "~"],
0x33: [";", ":"],
0x34: ["'", '"'],
0x36: [",", "<"],
0x37: [".", ">"],
0x38: ["/", "?"],
0x39: ["[CAPSLOCK]", "[CAPSLOCK]"],
0x2B: ["\t", "\t"],
0x4F: ["→", "→"],
0x50: ["←", "←"],
0x51: ["↓", "↓"],
0x52: ["↑", "↑"],
}
def parse_keyboard(file : str) -> list[str]:
'''
### Function arguments:
- file: path to file to read
### Function returns:
- list of strings rappresenting the history of the keyboard (in the form of key pressed)
'''
with open(file, "r") as f:
datas = f.read().split("\n")
datas = [d.strip() for d in datas if d]
history = []
skip_next = False
history.append('Cursor')
for data in datas:
shift = int(data.split(":")[0], 16) # 0x2 is left shift 0x20 is right shift
key = int(data.split(":")[2], 16)
if skip_next:
skip_next = False
continue
if key == 0 or int(data.split(":")[3], 16) > 0:
continue
if shift != 0:
shift = 1
skip_next = True
history.append(KEY_CODES[key][shift])
return history
class MyWindow:
def __init__(self, win : tk.Tk, data : list[str], instruction_number : int =0):
"""
### Function parameters:
- win: tkinter window
- data: list of keys pressed
- instruction_number: index of the key pressed
### Function description:
Constructor of the class MyWindow, generates a tkinter window with a 3x2 grid layout, it includes:
- two labels, one for the instruction number and one for the key pressed
- a text box, to display text composed and where the user can modify it
- a slider, to navigate through the instructions
- two buttons, one to go to the next instruction and one to go to the previous instruction
"""
#window config
win.geometry("500x300")
win.title("Keyboard")
win.grid_rowconfigure((0,2), weight=0)
win.grid_rowconfigure(1, weight=1)
win.grid_columnconfigure((0,1), weight=1)
self.instruction_number = instruction_number
self.data = data
self.CAPSLOCK = False
self.stack = []
#first row: labels
self.i_number = tk.Label(win, text=f'Number: {self.instruction_number}')
self.i_number.grid(row=0, column=0)
self.key = tk.Label(win, text=f'Key: {self.data[self.instruction_number]}')
self.key.grid(row=0, column=1)
#second row: textbox
self.textbox = tk.Text(win,undo=True,autoseparators=True)
self.textbox.grid(row=1, column=0, columnspan=2, padx=20, pady=(20, 0), sticky="nsew")
self.stack.append((True,''))
#third row: slider
self.slider = tk.Scale(win, from_=0, to=len(self.data)-1, orient=tk.HORIZONTAL, command=self.slider_callback)
self.slider.grid(row=2, column=0, columnspan=2, padx=20, pady=(0, 20), sticky="nsew")
#fourth row: buttons
self.prev = tk.Button(win, text="Previous", command=self.press_prev)
self.prev.grid(row=3, column=0, padx=20, pady=20, sticky="ew")
self.next = tk.Button(win, text="Next", command=self.press_next)
self.next.grid(row=3, column=1, padx=20, pady=20, sticky="ew")
def press_prev(self) -> None:
"""
### Function description:
Function called when the user presses the previous button, it updates the instruction number and the key pressed labels and the slider
then it updates the textbox restoring the previous text saved in the stack
"""
if self.instruction_number == 0:
return
self.instruction_number -= 1
self.i_number.configure(text=f'Number: {self.instruction_number}')
if(self.data[self.instruction_number] == ' '):
self.key.configure(text=f'Key: [SPACE]')
else:
self.key.configure(text=f'Key: {self.data[self.instruction_number]}')
self.slider.set(self.instruction_number)
if(self.stack[-1][0] == True):
if(self.textbox.get("1.0", "end-1c") == self.stack[-1][1]):
self.stack.pop()
self.textbox.delete("1.0", "end-1c")
self.textbox.insert("1.0", self.stack[-1][1])
self.stack.pop()
if not self.stack:
self.stack.append((True,''))
#print(self.stack)
def press_next(self) -> None:
""""
### Function description:
Function called when the user presses the next button, it updates the instruction number and the key pressed labels and the slider
then it updates the textbox saving the current text in the stack and adding the new key pressed considering the CAPSLOCK status
and all the special keys (backspace, enter, tab, capslock, space)
"""
if(self.instruction_number > len(self.data)):
return
self.instruction_number += 1
#LABELS
self.i_number.configure(text=f'Number: {self.instruction_number}')
if(self.data[self.instruction_number] == ' '):
self.key.configure(text=f'Key: [SPACE]')
else:
self.key.configure(text=f'Key: {self.data[self.instruction_number]}')
#SLIDER
self.slider.set(self.instruction_number)
normal_push = True
#TEXTBOX
if(self.data[self.instruction_number] == '[BACKSPACE]'):
#delete last char before cursor
self.textbox.delete("insert-1c")
elif(self.data[self.instruction_number] == '[CAPSLOCK]'):
#set or unset capslock
self.CAPSLOCK = not self.CAPSLOCK
normal_push = False
elif(self.data[self.instruction_number] == '←'):
#move cursor left
self.textbox.mark_set("insert", "insert-1c")
normal_push = False
elif(self.data[self.instruction_number] == '→'):
#move cursor right
self.textbox.mark_set("insert", "insert+1c")
normal_push = False
elif(self.data[self.instruction_number] == '↑'):
#move cursor up
self.textbox.mark_set("insert", "insert-1l")
normal_push = False
elif(self.data[self.instruction_number] == '↓'):
#move cursor to the end of the line
self.textbox.mark_set("insert", "end")
normal_push = False
elif(self.CAPSLOCK):
self.textbox.insert("insert", self.data[self.instruction_number].upper())
else:
self.textbox.insert("insert", self.data[self.instruction_number])
self.textbox.focus_set()
self.stack.append((normal_push, self.textbox.get("1.0", "end-1c")))
#print(self.stack)
def slider_callback(self, value):
"""
### Function description:
Function called when the user moves the slider, it uses press_next and press_prev function
"""
while(self.instruction_number != int(value)):
if(self.instruction_number < int(value)):
self.press_next()
else:
self.press_prev()
def main():
#parsing command line arguments
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('-f', '--file', type=str, help='path of the file to open')
parser.add_argument('-o', '--output', type=str, help='path of the output file for the keys log')
args = parser.parse_args()
if(args.file == None):
print("Error: file path not specified")
exit(1)
history = parse_keyboard(args.file)
if(args.output != None):
with open(args.output, 'w') as f:
for i in range(0,len(history)):
f.write(f'{i} {history[i]}\n')
#GUI
window=tk.Tk()
MyWindow(window,history)
window.mainloop()
if __name__ == "__main__":
main()