-
Notifications
You must be signed in to change notification settings - Fork 18
/
ui.py
3312 lines (3084 loc) · 123 KB
/
ui.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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Epson Printer Configuration via SNMP (TCP/IP) - GUI
"""
import os
import sys
import re
import threading
import ipaddress
import inspect
from datetime import datetime
import socket
import traceback
import logging
import webbrowser
import pickle
from code import InteractiveConsole
from contextlib import redirect_stderr, redirect_stdout
from io import StringIO
import black
import tkinter as tk
from tkinter import ttk, Menu
from tkinter.scrolledtext import ScrolledText
import tkinter.font as tkfont
from tkcalendar import DateEntry # Ensure you have: pip install tkcalendar
from tkinter import simpledialog, messagebox, filedialog
import pyperclip
from epson_print_conf import EpsonPrinter, get_printer_models
from parse_devices import generate_config_from_toml, generate_config_from_xml, normalize_config
from find_printers import PrinterScanner
from text_console import TextConsole
VERSION = "5.3.6"
NO_CONF_ERROR = (
" Please select a printer model and a valid IP address,"
" or press 'Detect Printers'.\n"
)
CONFIRM_MESSAGE = (
"Confirm Action",
"Please copy and save the codes in the [NOTE] shown on the screen."
" They can be used to restore the initial configuration"
" in case of problems.\n\n"
"Are you sure you want to proceed?"
)
class EpcTextConsole(TextConsole):
show_about_message = "epson_print_conf Debug Console."
def show_help(self):
"""Open a separate window with help text."""
help_window = tk.Toplevel(self)
help_window.title("Help")
help_window.geometry("1000x400")
# Add a scrollbar and text widget
scrollbar = tk.Scrollbar(help_window)
scrollbar.pack(side="right", fill="y")
help_text = tk.Text(help_window, wrap="word", yscrollcommand=scrollbar.set)
help_text.tag_configure("title", foreground="purple")
help_text.tag_configure("section", foreground="blue")
help_text.insert(
tk.END,
'Welcome to the epson_print_conf Debug Console\n\n',
"title"
)
help_text.insert(
tk.END,
'Features:\n\n',
"section"
)
help_text.insert(
tk.END,
(
"- Clear Console: Clears all text in the console.\n"
"- History: Open a separate window showing the list of"
" successfully executed commands (browse the command history).\n"
"- Context Menu: Right-click for cut, copy, paste, or clear.\n\n"
)
)
help_text.insert(
tk.END,
'Keyboard Shortcuts from the main window:\n\n',
"section"
)
help_text.insert(
tk.END,
(
"- F7: Open the debug console.\n\n"
)
)
help_text.insert(
tk.END,
'Tokens:\n\n',
"section"
)
help_text.insert(
tk.END,
(
"self: EpsonPrinterUI self\n"
"master: TextConsole widget\n"
"kw: kw dictionary ({'width': 50, 'wrap': 'word'})\n"
"local: TextConsole self\n\n"
)
)
help_text.insert(
tk.END,
'Examples of commands:\n\n',
"section"
)
help_text.insert(
tk.END,
(
"self.printer.model\n"
"self.printer.reverse_caesar(b'Hpttzqjv')\n"
'self.printer.reverse_caesar(bytes.fromhex("48 62 7B 62 6F 6A 62 2B"))\n'
'import pprint;pprint.pprint(self.printer.status_parser(self.printer.snmp_mib("1.3.6.1.4.1.1248.1.2.2.1.1.1.4.1")[1]))\n'
"self.printer.read_eeprom_many([0])\n"
"self.printer.read_eeprom(0)\n"
"self.printer.snmp_mib(self.printer.eeprom_oid_read_address(0))\n"
"self.printer.snmp_mib('1.3.6.1.4.1.1248.1.2.2.44.1.1.2.1.124.124.7.0.25.7.65.190.160.0.0')\n"
"self.get_ti_date(cursor=True)"
)
)
help_text.config(state="disabled") # Make the text read-only
help_text.pack(fill="both", expand=True)
scrollbar.config(command=help_text.yview)
class MultiLineInputDialog(simpledialog.Dialog):
def __init__(self, parent, title=None, text=""):
self.text=text
super().__init__(parent, title)
def body(self, frame):
# Add a label with instructions
self.label = tk.Label(frame, text=self.text)
self.label.pack(pady=5)
# Create a Text widget for multiline input
self.textbox = tk.Text(frame, height=5, width=50)
self.textbox.configure(font=("TkDefaultFont"))
self.textbox.pack()
return self.textbox
def apply(self):
# Get the input from the Text widget
self.result = self.textbox.get("1.0", tk.END).strip()
class ToolTip:
def __init__(
self,
widget,
text="widget info",
wrap_length=10,
destroy=True
):
self.widget = widget
self.text = text
self.wrap_length = wrap_length
self.tooltip_window = None
# Check and remove existing bindings if they exist
if destroy:
self.remove_existing_binding("<Enter>")
self.remove_existing_binding("<Leave>")
self.remove_existing_binding("<Button-1>")
# Set new bindings
widget.bind("<Enter>", self.enter, "+") # Show the tooltip on hover
widget.bind("<Leave>", self.leave, "+") # Hide the tooltip on leave
widget.bind("<Button-1>", self.leave, "+") # Hide tooltip on mouse click
def remove_existing_binding(self, event):
# Check if there's already a binding for the event
if self.widget.bind(event):
self.widget.unbind(event) # Remove the existing binding
def enter(self, event=None):
if self.tooltip_window or not self.text:
return
x, y, width, height = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 20
y += self.widget.winfo_rooty() + 20
self.tooltip_window = tw = tk.Toplevel(self.widget)
tw.wm_overrideredirect(True)
# Calculate the position for the tooltip
screen_width = self.widget.winfo_screenwidth()
screen_height = self.widget.winfo_screenheight()
tw.geometry(f"+{x}+{y + height + 2}") # Default position below the widget
label = tk.Label(
tw,
text=self.wrap_text(self.text),
justify="left",
background="LightYellow",
relief="solid",
borderwidth=1,
)
label.pack(ipadx=1)
# Check if the tooltip goes off the screen
tw.update_idletasks() # Ensures the tooltip size is calculated
tw_width = tw.winfo_width()
tw_height = tw.winfo_height()
if x + tw_width > screen_width: # If tooltip goes beyond screen width
x = screen_width - tw_width - 5
if (y + height + tw_height > screen_height): # If tooltip goes below screen height
y = y - tw_height - height - 2 # Position above the widget
tw.geometry(f"+{x}+{y}")
def leave(self, event=None):
if self.tooltip_window:
self.tooltip_window.destroy()
self.tooltip_window = None
def wrap_text(self, text):
words = text.split()
lines = []
current_line = []
for word in words:
if len(current_line) + len(word.split()) <= self.wrap_length:
current_line.append(word)
else:
lines.append(" ".join(current_line))
current_line = [word]
if current_line:
lines.append(" ".join(current_line))
return "\n".join(lines)
class BugFixedDateEntry(DateEntry):
"""
Fixes a bug on the calendar that does not accept mouse selection with Linux
Fixes a drop down bug when the DateEntry widget is not focused
"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def drop_down(self):
self.focus_set() # Set focus to the DateEntry widget
super().drop_down()
if self._top_cal is not None and not self._calendar.winfo_ismapped():
self._top_cal.lift()
class EpsonPrinterUI(tk.Tk):
def __init__(
self,
model: str = None,
hostname: str = None,
conf_dict = {},
replace_conf=False
):
super().__init__()
self.title("Epson Printer Configuration - v" + VERSION)
self.geometry("500x500")
self.minsize(550, 600)
self.printer_scanner = PrinterScanner()
self.ip_list = []
self.ip_list_cycle = None
self.conf_dict = conf_dict
self.replace_conf = replace_conf
self.text_dump = ""
self.mode = black.Mode(line_length=200, magic_trailing_comma=False)
self.printer = None
# configure the main window to be resizable
self.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
# Setup the menu
menubar = Menu(self)
self.config(menu=menubar)
# Create File menu
file_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="File", menu=file_menu)
LOAD_LABEL_NAME = "%s printer configuration file or web URL..."
LOAD_LABEL_TITLE = "Select a %s printer configuration file, or enter a Web URL"
LOAD_LABEL_TYPE = "%s files"
file_menu.add_command(
label=LOAD_LABEL_NAME % "Load a PICKLE",
command=lambda: self.load_from_file(
file_type={
"title": LOAD_LABEL_TITLE % "PICKLE",
"filetypes": [
(LOAD_LABEL_TYPE % "PICKLE", "*.pickle"),
("All files", "*.*")
]
},
type=0
)
)
file_menu.add_command(
label=LOAD_LABEL_NAME % "Import a XML",
command=lambda: self.load_from_file(
file_type={
"title": LOAD_LABEL_TITLE % "XML",
"filetypes": [
(LOAD_LABEL_TYPE % "XML", "*.xml"),
("All files", "*.*")
]
},
type=1
)
)
file_menu.add_command(
label=LOAD_LABEL_NAME % "Import a TOML",
command=lambda: self.load_from_file(
file_type={
"title": LOAD_LABEL_TITLE % "TOML",
"filetypes": [
(LOAD_LABEL_TYPE % "TOML", "*.toml"),
("All files", "*.*")
]
},
type=2
)
)
file_menu.add_command(
label="Save the selected printer configuration to a PICKLE file...",
command=self.save_to_file
)
file_menu.add_command(label="Quit Application", command=self.quit)
# Create Help menu
help_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Settings", menu=help_menu)
help_menu.add_command(label="Show printer parameters of the selected model", command=self.printer_config)
help_menu.entryconfig("Show printer parameters of the selected model", accelerator="F2")
help_menu.add_command(label="Show printer keys of the selected model", command=self.key_values)
help_menu.entryconfig("Show printer keys of the selected model", accelerator="F3")
help_menu.add_command(label="Remove selected printer configuration", command=self.remove_printer_conf)
help_menu.entryconfig("Remove selected printer configuration", accelerator="F4")
help_menu.add_command(label="Keep only selected printer configuration", command=self.keep_printer_conf)
help_menu.entryconfig("Keep only selected printer configuration", accelerator="F5")
help_menu.add_command(label="Clear printer list", command=self.clear_printer_list)
help_menu.entryconfig("Clear printer list", accelerator="F6")
help_menu.add_command(label="Debug shell", command=self.tk_console)
help_menu.entryconfig("Debug shell", accelerator="F7")
help_menu.add_command(label="Get next local IP addresss", command=lambda: self.next_ip(0))
help_menu.entryconfig("Get next local IP addresss", accelerator="F9")
# Create Help menu
help_menu = Menu(menubar, tearoff=0)
menubar.add_cascade(label="Help", menu=help_menu)
help_menu.add_command(label="Help", command=self.open_help_browser)
help_menu.add_command(label="Program Information", command=self.show_program_info)
# Setup frames
FRAME_PAD = 10
PAD = (3, 0)
PADX = 4
PADY = 5
# main Frame
main_frame = ttk.Frame(self, padding=FRAME_PAD)
main_frame.grid(row=0, column=0, sticky=(tk.W, tk.E, tk.N, tk.S))
main_frame.columnconfigure(0, weight=1)
main_frame.rowconfigure(5, weight=1) # Number of rows
row_n = 0
# [row 0] Container frame for the two LabelFrames Power-off timer and TI Received Time
model_ip_frame = ttk.Frame(main_frame, padding=PAD)
model_ip_frame.grid(row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E))
model_ip_frame.columnconfigure(0, weight=1) # Allow column to expand
model_ip_frame.columnconfigure(1, weight=1) # Allow column to expand
# BOX printer model selection
model_frame = ttk.LabelFrame(
model_ip_frame, text="Printer Model", padding=PAD
)
model_frame.grid(
row=0, column=0, pady=PADY, padx=(0, PADX), sticky=(tk.W, tk.E)
)
model_frame.columnconfigure(0, weight=0)
model_frame.columnconfigure(1, weight=1)
# Model combobox
self.model_var = tk.StringVar()
if (
"internal_data" in conf_dict
and "default_model" in conf_dict["internal_data"]
):
self.model_var.set(conf_dict["internal_data"]["default_model"])
if model:
self.model_var.set(model)
ttk.Label(model_frame, text="Model:").grid(
row=0, column=0, sticky=tk.W, padx=PADX
)
self.model_dropdown = ttk.Combobox(
model_frame, textvariable=self.model_var, state="readonly"
)
self.model_dropdown["values"] = sorted(EpsonPrinter(
conf_dict=self.conf_dict,
replace_conf=self.replace_conf
).valid_printers)
self.model_dropdown.grid(
row=0, column=1, pady=PADY, padx=PADX, sticky=(tk.W, tk.E)
)
ToolTip(
self.model_dropdown,
"Select the model of the printer, or press 'Detect Printers'."
" Special features are allowed via F2, F3, F4, F5, or F6.\n"
)
self.bind_all("<F2>", self.printer_config)
self.bind_all("<F3>", self.key_values)
self.bind_all("<F4>", lambda event: self.remove_printer_conf())
self.bind_all("<F5>", lambda event: self.keep_printer_conf())
self.bind_all("<F6>", lambda event: self.clear_printer_list())
self.bind_all("<F7>", lambda event: self.tk_console())
# BOX IP address
ip_frame = ttk.LabelFrame(
model_ip_frame, text="Printer IP Address", padding=PAD
)
ip_frame.grid(
row=0, column=1, pady=PADY, padx=(PADX, 0), sticky=(tk.W, tk.E)
)
ip_frame.columnconfigure(0, weight=0)
ip_frame.columnconfigure(1, weight=1)
# IP address entry
self.ip_var = tk.StringVar()
if (
"internal_data" in conf_dict
and "hostname" in conf_dict["internal_data"]
):
self.ip_var.set(conf_dict["internal_data"]["hostname"])
if hostname:
self.ip_var.set(hostname)
ttk.Label(ip_frame, text="IP Address:").grid(
row=0, column=0, sticky=tk.W, padx=PADX
)
self.ip_entry = ttk.Entry(ip_frame, textvariable=self.ip_var)
self.ip_entry.grid(
row=0, column=1, pady=PADY, padx=PADX, sticky=(tk.W, tk.E)
)
self.ip_entry.bind("<F9>", self.next_ip)
ToolTip(
self.ip_entry,
"Enter the IP address, or press 'Detect Printers'"
" (you can also enter part of the IP address"
" to speed up the detection),"
" or press F9 more times to get the next local IP address,"
" which can then be edited"
" (by removing the last part before pressing 'Detect Printers').",
)
# Create a custom style for the button to center the text
style = ttk.Style()
style.configure("Centered.TButton", justify='center', anchor="center")
# [row 1] Container frame for the two LabelFrames Power-off timer and TI Received Time
row_n += 1
container_frame = ttk.Frame(main_frame, padding=PAD)
container_frame.grid(
row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E)
)
container_frame.columnconfigure(0, weight=1) # Allow column to expand
container_frame.columnconfigure(1, weight=1) # Allow column to expand
# BOX Power-off Timer (minutes)
po_timer_frame = ttk.LabelFrame(
container_frame, text="Power-off Timer (minutes)", padding=PAD
)
po_timer_frame.grid(
row=0, column=0, pady=PADY, padx=(0, PADX), sticky=(tk.W, tk.E)
)
po_timer_frame.columnconfigure(0, weight=0) # Button column on the left
po_timer_frame.columnconfigure(1, weight=1) # Entry column
po_timer_frame.columnconfigure(2, weight=0) # Button column on the right
# Configure validation command for numeric entry
validate_cmd = self.register(self.validate_number_input)
# Power-off timer (minutes) - Get Button
button_width = 7
self.get_po_minutes = ttk.Button(
po_timer_frame,
text="Get",
width=button_width,
command=self.get_po_mins,
)
self.get_po_minutes.grid(
row=0, column=0, padx=PADX, pady=PADY, sticky=tk.W
)
# Power-off timer (minutes) - minutes Entry
self.po_timer_var = tk.StringVar()
self.po_timer_entry = ttk.Entry(
po_timer_frame,
textvariable=self.po_timer_var,
validate="all",
validatecommand=(validate_cmd, "%P"),
width=6,
justify="center",
)
self.po_timer_entry.grid(
row=0, column=1, pady=PADY, padx=PADX, sticky=(tk.W, tk.E)
)
ToolTip(
self.po_timer_entry,
"Enter a number of minutes.",
destroy=False
)
# Power-off timer (minutes) - Set Button
self.set_po_minutes = ttk.Button(
po_timer_frame,
text="Set",
width=button_width,
command=self.set_po_mins,
)
self.set_po_minutes.grid(
row=0, column=2, padx=PADX, pady=PADY, sticky=tk.E
)
# BOX TI Received Time (date)
ti_received_frame = ttk.LabelFrame(
container_frame, text="TI Received Time (date)", padding=PAD
)
ti_received_frame.grid(
row=0, column=1, pady=PADY, padx=(PADX, 0), sticky=(tk.W, tk.E)
)
ti_received_frame.columnconfigure(0, weight=0) # Button column on the left
ti_received_frame.columnconfigure(1, weight=1) # Calendar column
ti_received_frame.columnconfigure(2, weight=0) # Button column on the right
# TI Received Time - Get Button
self.get_ti_received = ttk.Button(
ti_received_frame,
text="Get",
width=button_width,
command=self.get_ti_date,
)
self.get_ti_received.grid(
row=0, column=0, padx=PADX, pady=PADY, sticky=tk.W
)
# TI Received Time - Calendar Widget
self.date_entry = BugFixedDateEntry(
ti_received_frame, date_pattern="yyyy-mm-dd"
)
self.date_entry.grid(
row=0, column=1, padx=PADX, pady=PADY, sticky=(tk.W, tk.E)
)
self.date_entry.delete(0, "end") # blank the field removing the current date
ToolTip(
self.date_entry,
"Enter a valid date with format YYYY-MM-DD.",
destroy=False
)
# TI Received Time - Set Button
self.set_ti_received = ttk.Button(
ti_received_frame,
text="Set",
width=button_width,
command=self.set_ti_date,
)
self.set_ti_received.grid(
row=0, column=2, padx=PADX, pady=PADY, sticky=tk.E
)
# [row 2] Container frame for the two LabelFrames WiFi MAC address and printer serial number
row_n += 1
container_frame = ttk.Frame(main_frame, padding=PAD)
container_frame.grid(
row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E)
)
container_frame.columnconfigure(0, weight=1) # Allow column to expand
container_frame.columnconfigure(1, weight=1) # Allow column to expand
# BOX WiFi MAC Address (6 alphanumeric digits optionally separated by dash)
mac_addr_frame = ttk.LabelFrame(
container_frame, text="WiFi MAC Address", padding=PAD
)
mac_addr_frame.grid(
row=0, column=0, pady=PADY, padx=(0, PADX), sticky=(tk.W, tk.E)
)
mac_addr_frame.columnconfigure(0, weight=0) # Button column on the left
mac_addr_frame.columnconfigure(1, weight=1) # Entry column
mac_addr_frame.columnconfigure(2, weight=0) # Button column on the right
# Configure validation command for MAC address
validate_mac_addr = (self.register(self.validate_mac_address), '%P')
# WiFi MAC Address - Get Button
button_width = 7
self.get_mac_addr = ttk.Button(
mac_addr_frame,
text="Get",
width=button_width,
command=self.get_mac_address,
)
self.get_mac_addr.grid(
row=0, column=0, padx=PADX, pady=PADY, sticky=tk.W
)
# WiFi MAC Address - Entry
self.mac_addr_var = tk.StringVar()
self.mac_addr_entry = ttk.Entry(
mac_addr_frame,
textvariable=self.mac_addr_var,
validate="all",
validatecommand=(validate_mac_addr, "%P"),
width=22, # Full MAC address with separators
justify="center",
)
self.mac_addr_entry.grid(
row=0, column=1, pady=PADY, padx=PADX, sticky=(tk.W, tk.E)
)
ToolTip(
self.mac_addr_entry,
"Enter Enter a valid MAC address"
" (6 hex octets optionally separated by dash).",
destroy=False
)
# WiFi MAC Address - Set Button
self.set_mac_addr = ttk.Button(
mac_addr_frame,
text="Set",
width=button_width,
command=self.set_mac_address,
)
self.set_mac_addr.grid(
row=0, column=2, padx=PADX, pady=PADY, sticky=tk.E
)
# BOX Serial number (10 characters)
ser_num_frame = ttk.LabelFrame(
container_frame, text="Printer Serial Number", padding=PAD
)
ser_num_frame.grid(
row=0, column=1, pady=PADY, padx=(0, PADX), sticky=(tk.W, tk.E)
)
ser_num_frame.columnconfigure(0, weight=0) # Button column on the left
ser_num_frame.columnconfigure(1, weight=1) # Entry column
ser_num_frame.columnconfigure(2, weight=0) # Button column on the right
# Configure validation command for the printer serial number
validate_ser_num = (self.register(self.validate_ser_number), '%P')
# Printer Serial Number - Get Button
button_width = 7
self.get_ser_num = ttk.Button(
ser_num_frame,
text="Get",
width=button_width,
command=self.get_ser_number,
)
self.get_ser_num.grid(
row=0, column=0, padx=PADX, pady=PADY, sticky=tk.W
)
# Printer Serial Number - Entry
self.ser_num_var = tk.StringVar()
self.ser_num_entry = ttk.Entry(
ser_num_frame,
textvariable=self.ser_num_var,
validate="all",
validatecommand=(validate_ser_num, "%P"),
width=14, # 10 characters
justify="center",
)
self.ser_num_entry.grid(
row=0, column=1, pady=PADY, padx=PADX, sticky=(tk.W, tk.E)
)
ToolTip(
self.ser_num_entry,
"Enter Enter a valid printer serial number"
" (10 uppercase or numeric characters).",
destroy=False
)
# Printer Serial Number - Set Button
self.set_ser_num = ttk.Button(
ser_num_frame,
text="Set",
width=button_width,
command=self.set_ser_number,
)
self.set_ser_num.grid(
row=0, column=2, padx=PADX, pady=PADY, sticky=tk.E
)
# [row 3] Query Buttons
row_n += 1
button_frame = ttk.Frame(main_frame, padding=PAD)
button_frame.grid(row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E))
button_frame.columnconfigure((0, 1, 2), weight=1) # expand columns
# Query Printer Status
self.status_button = ttk.Button(
button_frame, text="Printer Status",
command=self.printer_status,
style="Centered.TButton"
)
self.status_button.grid(
row=0, column=0, padx=PADX, pady=PADY, sticky=(tk.W, tk.E)
)
# Query list of cartridge types
self.web_interface_button = ttk.Button(
button_frame,
text="Printer Web interface",
command=self.web_interface,
style="Centered.TButton"
)
self.web_interface_button.grid(
row=0, column=1, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# Detect configuration values
self.detect_configuration_button = ttk.Button(
button_frame,
text="Detect Configuration",
command=self.detect_configuration,
style="Centered.TButton"
)
self.detect_configuration_button.grid(
row=0, column=2, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# [row 4] Tweak Buttons
row_n += 1
tweak_frame = ttk.Frame(main_frame, padding=PAD)
tweak_frame.grid(row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E))
tweak_frame.columnconfigure((0, 1, 2, 3, 4), weight=1) # expand columns
# Detect Printers
self.detect_button = ttk.Button(
tweak_frame,
text="Detect\nPrinters",
command=self.start_detect_printers,
style="Centered.TButton"
)
self.detect_button.grid(
row=0, column=0, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# Detect Access Keys
self.detect_access_key_button = ttk.Button(
tweak_frame,
text="Detect\nAccess Keys",
command=self.detect_access_key,
style="Centered.TButton"
)
self.detect_access_key_button.grid(
row=0, column=1, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# Read EEPROM
self.read_eeprom_button = ttk.Button(
tweak_frame,
text="Read\nEEPROM",
command=self.read_eeprom,
style="Centered.TButton"
)
self.read_eeprom_button.grid(
row=0, column=2, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# Write EEPROM
self.write_eeprom_button = ttk.Button(
tweak_frame,
text="Write\nEEPROM",
command=self.write_eeprom,
style="Centered.TButton"
)
self.write_eeprom_button.grid(
row=0, column=3, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# Reset Waste Ink Levels
self.reset_button = ttk.Button(
tweak_frame,
text="Reset Waste\nInk Levels",
command=self.reset_waste_ink,
style="Centered.TButton"
)
self.reset_button.grid(
row=0, column=4, padx=PADX, pady=PADX, sticky=(tk.W, tk.E)
)
# [row 4] Status display (including ScrolledText and Treeview)
row_n += 1
status_frame = ttk.LabelFrame(main_frame, text="Status", padding=PAD)
status_frame.grid(
row=row_n, column=0, pady=PADY, sticky=(tk.W, tk.E, tk.N, tk.S)
)
status_frame.columnconfigure(0, weight=1)
status_frame.rowconfigure(0, weight=1)
# ScrolledText widget
self.status_text = ScrolledText(
status_frame, wrap=tk.WORD, font=("TkDefaultFont")
)
self.status_text.tag_configure("error", foreground="red")
self.status_text.tag_configure("warn", foreground="blue")
self.status_text.tag_configure("note", foreground="purple")
self.status_text.tag_configure("info", foreground="green")
self.status_text.grid(
row=0,
column=0,
pady=PADY,
padx=PADY,
sticky=(tk.W, tk.E, tk.N, tk.S),
)
self.status_text.bind("<Tab>", self.focus_next)
self.status_text.bind("<Shift-Tab>", self.focus_previous)
self.status_text.bind("<Key>", lambda e: "break") # disable editing text
self.status_text.bind(
"<Control-c>",
lambda event: self.copy_to_clipboard(self.status_text),
)
# self.status_text.bind("<Button-1>", lambda e: "break") # also disable the mouse
# Create a context menu
self.text_context_menu = Menu(self, tearoff=0)
self.text_context_menu.add_command(
label="Clear All", command=self.clear_all_text
)
self.text_context_menu.add_command(
label="Copy", command=self.copy_text
)
self.text_context_menu.add_command(
label="Copy all text", command=self.copy_all_text
)
self.text_context_menu.add_command(
label="Print all text",
command=lambda: self.print_items(
self.status_text.get("1.0", tk.END).strip()
)
)
self.text_context_menu.add_command(
label="Switch to tree view",
command=self.show_treeview
)
self.status_text.bind("<Button-3>", self.show_text_context_menu)
# Create a frame to contain the Treeview and its scrollbar
self.tree_frame = tk.Frame(status_frame)
self.tree_frame.grid(column=0, row=0, sticky=(tk.W, tk.E, tk.N, tk.S))
self.tree_frame.columnconfigure(0, weight=1)
self.tree_frame.rowconfigure(0, weight=1)
# Style configuration for the treeview
style = ttk.Style(self)
treeview_font = style.lookup("Treeview.Heading", "font")
# For the treeview, if the treeview_font is a tuple, split into components
if isinstance(treeview_font, tuple):
treeview_font_name, treeview_font_size = (
treeview_font[0],
treeview_font[1],
)
else:
# If font is not a tuple, it might be a font string or other format.
treeview_font_name, treeview_font_size = tkfont.Font().actual(
"family"
), tkfont.Font().actual("size")
style.configure(
"Treeview.Heading",
font=(treeview_font_name, treeview_font_size - 4, "bold"),
background="lightblue",
foreground="darkblue",
)
# Create and configure the Treeview widget
self.tree = ttk.Treeview(self.tree_frame, style="Treeview")
self.tree.grid(column=0, row=0, sticky=(tk.W, tk.E, tk.N, tk.S))
# Create a vertical scrollbar for the Treeview
tree_scrollbar = ttk.Scrollbar(
self.tree_frame, orient="vertical", command=self.tree.yview
)
tree_scrollbar.grid(column=1, row=0, sticky=(tk.N, tk.S))
# Configure the Treeview to use the scrollbar
self.tree.configure(yscrollcommand=tree_scrollbar.set)
# Create a context menu
self.context_menu = Menu(self, tearoff=0)
self.context_menu.add_command(
label="Copy this item", command=self.copy_selected_item
)
self.context_menu.add_command(
label="Copy all items", command=self.copy_all_items
)
self.context_menu.add_command(
label="Print all items",
command=lambda: self.print_items(self.text_dump)
)
self.context_menu.add_command(
label="Switch to text status",
command=self.show_status_text_view
)
# Bind the right-click event to the Treeview
self.tree.bind("<Button-3>", self.show_context_menu)
# Hide the Treeview initially
self.tree_frame.grid_remove()
self.model_var.trace('w', self.change_widget_states)
self.ip_var.trace('w', self.change_widget_states)
self.change_widget_states()
def save_to_file(self):
if not self.model_var.get():
self.show_status_text_view()
self.status_text.insert(tk.END, '[ERROR]', "error")
self.status_text.insert(
tk.END,
': Unknown printer model.'
)
return
if not self.printer:
self.printer = EpsonPrinter(
conf_dict=self.conf_dict,
model=self.model_var.get(),
)
if not self.printer or not self.printer.parm:
self.show_status_text_view()
self.status_text.insert(tk.END, '[ERROR]', "error")
self.status_text.insert(
tk.END,
': No printer configuration defined.'
)
return
# Open file dialog to enter the file
file_path = filedialog.asksaveasfilename(
defaultextension=".pickle",
title="PICKLE file name",
initialfile=self.model_var.get(),
filetypes=[("PICKLE files", "*.pickle")]
)
if not file_path:
self.show_status_text_view()
self.status_text.insert(
tk.END,
f"[WARNING] File save operation aborted.\n"
)
return
# Ensure the file has the desired extension
if "." not in file_path and not file_path.endswith(".pickle"):
file_path += ".pickle"
normalized_config = { self.model_var.get(): self.printer.parm.copy() }
normalized_config["internal_data"] = {}
normalized_config["internal_data"]["default_model"] = self.model_var.get()
if self.ip_var.get():
normalized_config["internal_data"]["hostname"] = self.ip_var.get()
try:
with open(file_path, "wb") as file:
pickle.dump(normalized_config, file) # serialize the list
except Exception:
self.show_status_text_view()
self.status_text.insert(tk.END, '[ERROR]', "error")
self.status_text.insert(
tk.END,
f" File save operation failed.\n"
)
return
self.status_text.insert(tk.END, '[INFO]', "info")
self.status_text.insert(
tk.END,
f' "{os.path.basename(file_path)}" file save operation completed.\n'
)
def load_from_file(self, file_type, type):
# Open file dialog to select the file
self.show_status_text_view()
file_path = filedialog.askopenfilename(**file_type)