/
main_window.py
515 lines (390 loc) · 13.5 KB
/
main_window.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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
import tkinter
from tkinter import messagebox
import os
import sys
import config
import ls_connection as con
import note_reader as noter
import setting_handler
runtime_info = {
"ls_connected": False,
"timer_running": False,
"active_split": -1,
"notes": [],
"server_port": 0,
"force_reset": False,
"double_layout": False,
"settings": {}
}
root = tkinter.Tk()
red_path = os.path.join(
str(os.path.dirname(os.path.realpath(sys.argv[0]))),
config.RESOURCE_FOLDER,
config.ICONS["RED"]
)
green_path = os.path.join(
str(os.path.dirname(os.path.realpath(sys.argv[0]))),
config.RESOURCE_FOLDER,
config.ICONS["GREEN"]
)
red_icon = tkinter.Image("photo", file=red_path)
green_icon = tkinter.Image("photo", file=green_path)
def update(window, com_socket, text1, text2):
"""
Function to loop along tkinter mainloop.
"""
if runtime_info["force_reset"]:
# Boolean flag to force a connection reset
com_socket = reset_connection(com_socket, window, text1, text2)
runtime_info["force_reset"] = False
elif not runtime_info["ls_connected"]:
# try connecting to ls
con.ls_connect(com_socket, server_found, window, runtime_info["server_port"])
else:
# is_connected
if runtime_info["notes"]:
# notes loaded
# get index of current split
new_index = con.get_split_index(com_socket)
if isinstance(new_index, bool):
# Connection error
com_socket = test_connection(com_socket, window, text1, text2)
else:
# index retrieved succesfully
if new_index == -1:
# timer not running
if runtime_info["timer_running"]:
runtime_info["timer_running"] = False
runtime_info["active_split"] = new_index
update_GUI(window, com_socket, text1, text2)
else:
# timer is running
if not runtime_info["timer_running"]:
runtime_info["timer_running"] = True
# special case to fix scrolling
if runtime_info["active_split"] == 0:
runtime_info["active_split"] = -1
if not runtime_info["active_split"] == new_index:
# new split, need to update
runtime_info["active_split"] = new_index
update_GUI(window, com_socket, text1, text2)
else:
# notes not yet loaded
com_socket = test_connection(com_socket, window, text1, text2)
# self looping
window.after(int(config.POLLING_TIME * 1000),
update, window, com_socket, text1, text2)
def update_GUI(window, com_socket, text1, text2):
"""
Updates all graphics according to current runtime_info.
Sets window title and Text-box content.
Does NOT set window icon.
"""
index = runtime_info["active_split"]
if index == -1:
index = 0
if runtime_info["timer_running"]:
# Does not test connection if it fails
split_name = con.get_split_name(com_socket)
else:
split_name = False
if runtime_info["notes"]:
set_title_notes(window, index, split_name)
update_notes(text1, text2, index)
else:
update_title(config.DEFAULT_WINDOW["TITLE"], window)
def test_connection(com_socket, window, text1, text2):
"""
Runs a connection test to ls using given socket.
If test is unsuccessful, resets connection.
Returns a socket that should be used for communication with ls.
"""
if con.check_connection(com_socket):
return com_socket
else:
return reset_connection(com_socket, window, text1, text2)
def reset_connection(com_socket, window, text1, text2):
"""
Resets all variables and closes given socket.
Updates GUI to respond to connection loss.
Returns a fresh socket that can be used to connect to ls.
"""
if runtime_info["timer_running"]:
runtime_info["timer_running"] = False
runtime_info["active_split"] = -1
runtime_info["ls_connected"] = False
update_icon(False, window)
update_GUI(window, com_socket, text1, text2)
# Close old and return a fresh socket
con.close_socket(com_socket)
return con.init_socket()
def server_found(window):
"""
Executes correct settings for when
ls connection has been established.
"""
runtime_info["ls_connected"] = True
update_icon(True, window)
def update_icon(active, window):
"""Updates icon of window depending on "active" variable"""
if active:
window.tk.call('wm', 'iconphoto', window._w, green_icon)
else:
window.tk.call('wm', 'iconphoto', window._w, red_icon)
def update_title(name, window):
"""Sets the title of given window to name."""
window.wm_title(name)
def adjust_content(window, box1, box2):
"""
Adjusts size of box1 and box2 according to
layout and size of window.
"""
if runtime_info["double_layout"]:
set_double_layout(window, box1, box2)
else:
set_single_layout(window, box1, box2)
def set_double_layout(window, box1, box2):
"""
Configures boxes in the window to fit as in double layout.
"""
runtime_info["double_layout"] = True
w_width = window.winfo_width()
w_height = window.winfo_height()
box1.place(height=(w_height // 2), width=w_width)
box2.place(height=(w_height // 2), width=w_width, y=(w_height // 2))
def set_single_layout(window, box1, box2):
"""
Configures boxes in the window to fit as in single layout.
"""
runtime_info["double_layout"] = False
box2.place_forget()
box1.place(height=window.winfo_height(), width=window.winfo_width())
def show_popup(event, menu):
"""Displays given popup menu at cursor position."""
menu.post(event.x_root, event.y_root)
def menu_load_notes(window, text1, text2, com_socket):
"""Menu selected load notes option."""
load_notes(window, text1, text2, com_socket)
def load_notes(window, text1, text2, com_socket):
"""
Prompts user to select notes and then tries to load these into the UI.
"""
file = noter.select_file()
if file:
notes = noter.get_notes(file, runtime_info["settings"]["separator"])
if notes:
# Notes loaded correctly
runtime_info["notes"] = notes
# Save notes to settings
settings = setting_handler.load_settings()
settings["notes"] = file
setting_handler.save_settings(settings)
split_c = len(notes)
show_info(("Notes Loaded",
("Loaded notes with " + str(split_c) + " splits.")))
if not runtime_info["timer_running"]:
runtime_info["active_split"] = -1
update_GUI(window, com_socket, text1, text2)
else:
show_info(config.ERRORS["NOTES_EMPTY"], True)
def show_info(info, warning=False):
"""
Displays an info popup window.
if warning is True window has a warning triangle.
"""
if warning:
messagebox.showwarning(info[0], info[1])
else:
messagebox.showinfo(info[0], info[1])
def update_notes(text1, text2, index):
"""
Displays notes with the given index in given text widgets.
If index is lower than 0, displays notes for index 0.
If index is higher than the highest index there are
notes for the text widgets are left empty.
text2 is always given the notes at index (index + 1) if existing
"""
max_index = (len(runtime_info["notes"]) - 1)
if index < 0:
index = 0
text1.config(state=tkinter.NORMAL)
text2.config(state=tkinter.NORMAL)
text1.delete("1.0", tkinter.END)
text2.delete("1.0", tkinter.END)
if index <= max_index:
text1.insert(tkinter.END, runtime_info["notes"][index])
# cant disply notes for index+1
if index < max_index:
text2.insert(tkinter.END, runtime_info["notes"][index + 1])
text1.config(state=tkinter.DISABLED)
text2.config(state=tkinter.DISABLED)
def right_arrow(window, com_socket, text1, text2):
"""Event handler for right arrow key."""
change_preview(window, com_socket, text1, text2, 1)
def left_arrow(window, com_socket, text1, text2):
"""Event handler for left arrow key."""
change_preview(window, com_socket, text1, text2, -1)
def change_preview(window, com_socket, text1, text2, move):
"""
Chnges notes that are currently displayed.
Move is either 1 for next or -1 for previous.
"""
if runtime_info["notes"] and (not runtime_info["timer_running"]):
max_index = (len(runtime_info["notes"]) - 1)
index = runtime_info["active_split"]
if index < 0:
index = 0
index += move
if index > max_index:
index = max_index
runtime_info["active_split"] = index
update_GUI(window, com_socket, text1, text2)
def set_title_notes(window, index, split_name=False):
"""
Set window title to fit with displayed notes.
"""
title = config.DEFAULT_WINDOW["TITLE"]
disp_index = str(index + 1) # start at 1
title += " - " + disp_index
if split_name:
title += " - " + split_name
if runtime_info["timer_running"]:
title += " - " + config.RUNNING_ALERT
update_title(title, window)
def menu_open_settings(root_wnd, box1, box2, text1, text2, com_socket):
"""
Opens the settings menu.
"""
setting_handler.edit_settings(root_wnd,
(lambda settings: apply_settings(settings,
root_wnd,
box1, box2,
text1, text2, com_socket)))
def apply_settings(settings, window, box1, box2, text1, text2, com_socket):
"""
Applies the given settings to the given components.
Settings must be a correctly formatted dictionary.
"""
runtime_info["settings"] = settings
# Server port change
if not (runtime_info["server_port"] == int(settings["server_port"])):
runtime_info["server_port"] = int(settings["server_port"])
runtime_info["force_reset"] = True
text_font = (settings["font"], int(settings["font_size"]))
if setting_handler.decode_boolean_setting(settings["double_layout"]):
set_double_layout(window, box1, box2)
else:
set_single_layout(window, box1, box2)
text1.config(font=text_font)
text2.config(font=text_font)
text1.config(fg=settings["text_color"], bg=settings["background_color"])
text2.config(fg=settings["text_color"], bg=settings["background_color"])
old_note_length = len(runtime_info["notes"])
if settings["notes"] and noter.file_exists(settings["notes"]):
new_notes = noter.get_notes(settings["notes"], settings["separator"])
if new_notes:
# Notes loaded correctly
runtime_info["notes"] = new_notes
new_note_length = len(new_notes)
if not (new_note_length == old_note_length):
show_info(("Notes Loaded",
("Loaded notes with " + str(new_note_length) + " splits.")))
if not runtime_info["timer_running"]:
runtime_info["active_split"] = -1
update_GUI(window, com_socket, text1, text2)
else:
show_info(config.ERRORS["NOTES_EMPTY"], True)
def save_geometry_settings(width, height):
"""
Saves given width and height to settigns file.
"""
settings = setting_handler.load_settings()
settings["width"] = str(width)
settings["height"] = str(height)
setting_handler.save_settings(settings)
def do_on_close(root_wnd):
"""
Function that is called when the main tk window is closed.
Saves root_wnd's width and height to the settings file and
then closes the window.
"""
save_geometry_settings(root_wnd.winfo_width(), root_wnd.winfo_height())
root_wnd.destroy()
def init_UI(root):
"""Draws default UI and creates event bindings."""
# Create communication socket
com_socket = con.init_socket()
# Load Settings
settings = setting_handler.load_settings()
runtime_info["server_port"] = int(settings["server_port"])
runtime_info["settings"] = settings
# Graphical components
root.geometry(settings["width"] + "x" + settings["height"])
box1 = tkinter.Frame(root)
box2 = tkinter.Frame(root)
scroll1 = tkinter.Scrollbar(box1, width=config.SCROLLBAR_WIDTH)
scroll2 = tkinter.Scrollbar(box2, width=config.SCROLLBAR_WIDTH)
scroll1.pack(side=tkinter.RIGHT, fill=tkinter.Y)
scroll2.pack(side=tkinter.RIGHT, fill=tkinter.Y)
text1 = tkinter.Text(
box1,
yscrollcommand=scroll1.set,
wrap=tkinter.WORD,
cursor="arrow"
)
text1.insert(tkinter.END, config.DEFAULT_MSG)
text1.config(state=tkinter.DISABLED)
text1.pack(fill=tkinter.BOTH, expand=True)
text2 = tkinter.Text(
box2,
yscrollcommand=scroll2.set,
wrap=tkinter.WORD,
cursor="arrow"
)
text2.insert(tkinter.END, config.DEFAULT_MSG)
text2.config(state=tkinter.DISABLED)
text2.pack(fill=tkinter.BOTH, expand=True)
scroll1.config(command=text1.yview)
scroll2.config(command=text2.yview)
# Set font and color for text
text_font = (settings["font"], int(settings["font_size"]))
text1.config(font=text_font)
text2.config(font=text_font)
text1.config(fg=settings["text_color"], bg=settings["background_color"])
text2.config(fg=settings["text_color"], bg=settings["background_color"])
if setting_handler.decode_boolean_setting(settings["double_layout"]):
set_double_layout(root, box1, box2)
else:
set_single_layout(root, box1, box2)
# create popup menu
popup = tkinter.Menu(root, tearoff=0)
popup.add_command(
label=config.MENU_OPTIONS["LOAD"],
command=(lambda: menu_load_notes(root, text1, text2, com_socket))
)
popup.add_command(
label=config.MENU_OPTIONS["SETTINGS"],
command=(lambda: menu_open_settings(root, box1, box2, text1, text2, com_socket))
)
# Set default window icon and title
root.tk.call('wm', 'iconphoto', root._w, red_icon)
update_title(config.DEFAULT_WINDOW["TITLE"], root)
# Check if notes can be loaded from settings
settings = setting_handler.load_settings()
if settings["notes"] and noter.file_exists(settings["notes"]):
notes = noter.get_notes(settings["notes"], settings["separator"])
if notes:
runtime_info["notes"] = notes
update_GUI(root, com_socket, text1, text2)
# Event binds
root.bind("<Configure>", (lambda e: adjust_content(root, box1, box2)))
root.bind("<Button-3>", (lambda e: show_popup(e, popup)))
root.bind("<Right>", (lambda e: right_arrow(root, com_socket, text1, text2)))
root.bind("<Left>", (lambda e: left_arrow(root, com_socket, text1, text2)))
# Window close bind
root.protocol("WM_DELETE_WINDOW", (lambda: do_on_close(root)))
# call update loop
update(root, com_socket, text1, text2)
root.geometry(settings["width"] + "x" + settings["height"])
init_UI(root)
root.mainloop()