-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathui.py
1449 lines (1172 loc) · 60.8 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
import inspect
import tkinter as tk
import tkinter.filedialog as filedialog
from tkinter import ttk
from calc import Calculator
import engnum
from copy import copy
import pickle
from enum import Enum
from platform import system as platform_system
try:
from logger import Logger
logger = Logger(log_to_console=True)
log = logger.print_to_console
except ImportError:
log = print
class OsType(Enum):
LINUX = 0
MAC = 1
WINDOWS = 2
OTHER = 3
class UiFrame(tk.Frame):
""" extends the TkFrame class to add a no nonsense flag for indicating if the widget is visible or not in this
context
Warning, the coverage for self.visible is not complete, it is only set in the pack, pack_forget, and destroy methods
"""
def __init__(self, parent, **kwargs):
super().__init__(parent, **kwargs)
self.visible = None # set to True or False to indicate if the widget is visible or not
def pack_forget(self):
super().pack_forget()
self.visible = False
def destroy(self):
super().destroy()
self.visible = False
def pack(self, **kwargs):
super().pack(**kwargs)
self.visible = True
class UiVisibleState(Enum):
STANDARD = 0
MINI = 1
CUSTOM = 2
class CalculatorUiSettings:
def __init__(self):
""" the default settings for the calculator
Note: changing the default settings here will only change the settings at launch if there is no
last_state_autosave.pycalc file found. To force the settings to change on launch, delete the
last_state_autosave.pycalc file before launching the calculator.
"""
self.save_state_on_exit = True
self.float_format_string = '0.6f'
self.use_engineering_notation_format = False
self.eng_format_num_length = 7
self.integer_format_string = ','
self.plot_options_string = '-o'
self.last_user_function_edit_name = None
# window size and appearance
self.stack_rows = 2
self.locals_rows = 10
self.locals_width_key = 100
self.locals_width_value = 160
self.stack_index_width = 20
self.stack_value_width = 200
self.stack_type_width = 50
self.message_width = 30
self.background_color = 'default' # set to 'default' or <color>, default matches the system theme
self.stack_font = ('Arial', 24)
self.locals_font = ('Arial', 12)
self.message_font = ('Arial', 12)
self.button_font = ('Arial', 12)
self.ui_visible_state = UiVisibleState.STANDARD
self.show_message_field = False
self.show_locals_table = False
self.show_buttons = False
class CalculatorUiState:
def __init__(self):
self.stack = []
self.locals = dict()
self.settings = CalculatorUiSettings()
self.functions = dict()
class MainWindow:
def __init__(self, settings: CalculatorUiSettings = None):
""" creates the main window for the calculator
@param settings: CalculatorUiSettings, the settings for the calculator UI, passing a value besides None here
overrides the 'load settings on launch' behavior and uses the passed settings """
# check the OS type, tkinter has different behavior on different OS's
sys = platform_system()
if sys == 'Linux':
self._os_type = OsType.LINUX
elif sys == 'Darwin':
self._os_type = OsType.MAC
elif sys == 'Windows':
self._os_type = OsType.WINDOWS
else: # includes null, '', and Java
self._os_type = OsType.OTHER
self._autosave_path = 'last_state_autosave.pycalc'
self._c = Calculator()
self._root = tk.Tk()
self._root.title("PyCalc")
self._settings = CalculatorUiSettings() # for linting just instantiate this here overwrite if necessary
# handle the settings
if settings is None:
self._load_settings_on_launch()
else:
self._settings = settings
# handle the UI colors
if self._settings.background_color == 'default':
self._background_color = self._root.cget('bg')
else:
self._background_color = self._settings.background_color
# apply the color to the root window
self._root.config(bg=self._background_color)
self._top_frame = UiFrame(self._root, background=self._background_color, padx=5, pady=5)
self._top_frame.pack(fill='x', expand=True)
""" ------------------------------------- User Menu ---------------------------------------"""
# create menu bar with a file and options menu
self._menu_bar = tk.Menu(self._root)
self._root.config(menu=self._menu_bar)
self._file_menu = tk.Menu(self._menu_bar)
self._menu_bar.add_cascade(label='File', menu=self._file_menu)
self._edit_menu = tk.Menu(self._menu_bar)
self._menu_bar.add_cascade(label='Edit', menu=self._edit_menu)
self._view_menu = tk.Menu(self._menu_bar)
self._menu_bar.add_cascade(label='View', menu=self._view_menu)
self._options_menu = tk.Menu(self._menu_bar)
self._menu_bar.add_cascade(label='Options', menu=self._options_menu)
# FILE MENU ........................
# add a quit option to the file menu
self._file_menu.add_command(label='Quit', command=self._root.quit)
# add a 'load state' option to the file menu
self._file_menu.add_command(label='Load state', command=self.menu_load_state)
# add a 'save state' option to the file menu
self._file_menu.add_command(label='Save state', command=self.menu_save_state)
# EDIT MENU ........................
# add a 'undo' option to the edit menu
self._edit_menu.add_command(label='Undo (ctrl+z)', command=self.undo_last_action)
# add a 'clear stack' option to the edit menu
self._edit_menu.add_command(label='Clear stack', command=self.clear_stack)
# add a 'clear all variables' option to the file menu
self._edit_menu.add_command(label='Clear all variables', command=self.menu_clear_all_variables)
# VIEW MENU ........................
# add a 'show user functions' option to the view menu that opens a popup window
self._view_menu.add_command(label='Show user functions', command=self.popup_show_user_functions)
# add a 'show all functions' option to the view menu that opens a popup window
self._view_menu.add_command(label='Show all functions', command=self.popup_show_all_functions)
# add a seperator line
self._view_menu.add_separator()
# add a 'show message field' option to the view menu
self._tk_var_menu_view_show_message_field = tk.BooleanVar()
self._view_menu.add_checkbutton(label='Show message field',
onvalue=True,
offvalue=False,
variable=self._tk_var_menu_view_show_message_field,
command=self._menu_view_show_message_field, )
# add a 'show locals table' option to the view menu
self._tk_var_menu_view_show_locals_table = tk.BooleanVar()
self._view_menu.add_checkbutton(label='Show locals table',
onvalue=True,
offvalue=False,
variable=self._tk_var_menu_view_show_locals_table,
command=self._menu_view_show_locals_table, )
# add a 'show buttons' option to the view menu
self._tk_var_menu_view_show_buttons = tk.BooleanVar()
self._view_menu.add_checkbutton(label='Show buttons',
onvalue=True,
offvalue=False,
variable=self._tk_var_menu_view_show_buttons,
command=self._menu_view_show_buttons, )
# add a seperator
self._view_menu.add_separator()
# add a 'Standard View' option to the view menu
self._view_menu.add_command(label='Standard View', command=self._apply_standard_view)
# add a 'Mini View' option to the view menu
self._view_menu.add_command(label='Mini View', command=self._apply_mini_view)
# OPTIONS MENU ........................
# add a check option to the menu for 'save state on exit'
self._options_menu.add_checkbutton(label='Save state on exit', onvalue=True, offvalue=False)
# add a separator
self._options_menu.add_separator()
# add an option to "edit the float format string" that calls the method edit_float_format_string
self._options_menu.add_command(label='Edit numeric display format', command=self.popup_edit_numeric_display_format)
# add an option to "edit the plot options string" that calls the method edit_plot_options_string
self._options_menu.add_command(label='Edit plot options string', command=self.popup_edit_plot_options_string)
# add a line separator
self._options_menu.add_separator()
# add an option to open the add function popup window that calls the method popup_add_function
self._options_menu.add_command(label='Add function', command=self.popup_add_function)
# add an option to 'remove user function' that calls the method remove_user_function
self._options_menu.add_command(label='Remove function', command=self.popup_remove_user_function)
# add an option to 'clear all user functions' that calls the method clear_all_user_functions
self._options_menu.add_command(label='Clear all functions', command=self.popup_confirm_clear_all_user_functions)
self._options_menu.add_separator()
# add option to open the 'function buttons' popup
self._options_menu.add_command(label='Function buttons', command=self.popup_function_buttons)
# MENU BINDINGS ........................
# <none>
""" ------------------------------------- KEY BINDINGS --------------------------------------- """
# bind enter key to the enter method
self._root.bind('<Return>', lambda event: self.enter_press())
# bind the letter keys to the button press methods
lower_case_letters = [chr(i) for i in range(97, 123)]
upper_case_letters = [chr(i) for i in range(65, 91)]
special_chars = ['!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '[', ']',
'{', '}', '|', '\\', ';', ':', "'", '"', ',', '<', '.', '>', '/', '?', '`', '~']
numeric_chars = [str(i) for i in range(10)]
all_chars = lower_case_letters + upper_case_letters + special_chars + numeric_chars
for char in all_chars:
try:
self._root.bind(char, lambda event, ch=char: self.button_press(ch))
except Exception as ex:
log(f"Error binding key: {char} to button press method: {ex}")
# bind the delete button to delete last char method
self._root.bind('<BackSpace>', lambda event: self.delete_last_char())
self._root.bind('<Delete>', lambda event: self.delete_last_char())
# bind the space bar to a space keypress
self._root.bind('<space>', lambda event: self.button_press(' '))
# add binding for sift delete to clear stack at X
self._root.bind('<Shift-BackSpace>', lambda event: self.clear_x())
# add binding to clear the entire stack, protect with jitsu key combo
self._root.bind('<Command-Shift-BackSpace>', lambda event: self.clear_stack())
# add binding for paste from os clipboard
self._root.bind('<<Paste>>', lambda event: self.paste(self._root.clipboard_get()))
# add a binding for undo
self._root.bind('<Control-z>', lambda event: self.undo_last_action())
self._root.bind('<Command-z>', lambda event: self.undo_last_action())
# add a binding for save state
self._root.bind('<Control-s>', lambda event: self.menu_save_state())
# bind the program exit to the exit method
self._root.protocol("WM_DELETE_WINDOW", self.user_exit)
# bind command+c to the copy method
self._root.bind('<Command-c>', lambda event: self.copy_stack_value())
""" ---------------------------- Stack, Messages, Locals, Buttons --------------------------------------- """
stack_rows = self._settings.stack_rows
self._update_visible_ui_object_stack(number_visible_rows=stack_rows) # sets up the visible UI objects based on the settings
vis = self._settings.show_message_field
self._set_visibility_message_field(vis)
vis = self._settings.show_locals_table
self._set_visibility_locals_table(vis)
vis = self._settings.show_buttons
self._set_visibility_buttons(vis)
""" ------------------------------------- END __init__() ------------------------------------------------- """
def _update_visible_ui_object_stack(self, number_visible_rows=6):
""" updates the visible UI objects based on the settings """
""" ------------------------------------- STACK --------------------------------------- """
exists = hasattr(self, '_frame_stack') # the way this gets called we need to check before creating
if not exists:
# create a frame for the stack display
self._frame_stack = UiFrame(self._top_frame, background=self._background_color, padx=5, pady=5)
self._frame_stack.pack(fill='x', expand=True) # fill='x', expand=True
# add a table with 10 rows and 4 columns named 'index', 'value', 'hex', 'bin' to display the stack
self._stack_table = ttk.Treeview(self._frame_stack, columns=('value', 'type', ))
self._stack_table.heading('#0', text='Index')
self._stack_table.heading('value', text='Value')
self._stack_table.heading('type', text='Type')
self._stack_table.pack(fill='x', expand=True)
# add a graphic line below the stack table
ttk.Separator(self._frame_stack, orient='horizontal').pack()
# set table number of visible rows
if number_visible_rows is not None:
self._settings.stack_rows = number_visible_rows
self._stack_table['height'] = self._settings.stack_rows
self._stack_table.column('#0', width=self._settings.stack_index_width, anchor='w',)
self._stack_table.column('value', width=self._settings.stack_value_width, anchor='e')
self._stack_table.column('type', width=self._settings.stack_type_width, anchor=tk.CENTER)
if self._os_type == OsType.WINDOWS:
btn = '<Button-3>'
elif self._os_type == OsType.LINUX or self._os_type == OsType.MAC:
btn = '<Button-2>'
else:
log(f"Error setting right click menu for locals table, unknown OS type: {self._os_type}")
btn = '<Button-2>'
# add right click menu to stack
self._stack_table.bind(btn, self._right_click_menu_stack_table)
self._update_stack_display()
log(f"Stack Table column width: {self._stack_table.column('value', 'width')}")
""" ---------------------------- END __init__ and constructors ----------------------------------------------- """
@ staticmethod
def _get_menu_item_by_label( menu: tk.Menu, label: str):
""" returns a menu item by passing the menu object and the label of the item
@param menu: tk.Menu, the menu object to search
@param label: str, the label of the menu item to search for"""
for item in menu:
if item.cget('label') == label:
return item
def _set_visibility_locals_table(self, state: bool, number_of_visible_rows=10):
""" sets the visibility of the locals table based on the state """
if state is True:
self._settings.show_locals_table = True
self._tk_var_menu_view_show_locals_table.set(True)
else:
self._settings.show_locals_table = False
self._tk_var_menu_view_show_locals_table.set(False)
""" ------------------------------------- Locals --------------------------------------- """
if self._settings.show_locals_table is True:
self._view_menu.entryconfig('Show locals table', state='normal')
# create a frame for the locals display
self._frame_locals = UiFrame(self._top_frame, background=self._background_color, padx=5, pady=5)
if self._settings.show_locals_table is True:
self._frame_locals.pack(fill='x', expand=True)
# add a table with 10 rows and 2 columns named 'key', 'value', to display the locals
self._locals_table = ttk.Treeview(self._frame_locals, columns=('value',))
# set the font for the locals table
# add gray background to the locals table
self._locals_table['style'] = 'Treeview'
self._locals_table.tag_configure('Treeview', background='pink')
# set table number of visible rows
if number_of_visible_rows is not None:
self._settings.locals_rows = number_of_visible_rows
self._locals_table['height'] = self._settings.locals_rows
self._locals_table.heading('#0', text='Key', )
self._locals_table.heading('value', text='Value')
self._locals_table.column('#0', width=self._settings.locals_width_key)
self._locals_table.column('value', width=self._settings.locals_width_value)
self._locals_table.pack(fill='x', expand=True)
# add a graphic line below the locals table
ttk.Separator(self._frame_locals, orient='horizontal').pack(fill='x')
if self._os_type == OsType.WINDOWS:
btn = '<Button-3>'
elif self._os_type == OsType.LINUX or self._os_type == OsType.MAC:
btn = '<Button-2>'
else:
log(f"Error setting right click menu for locals table, unknown OS type: {self._os_type}")
btn = '<Button-2>'
# add right click menu to locals
self._locals_table.bind(btn, self._right_click_menu_locals_table)
self._update_locals_display()
else:
exists = hasattr(self, '_frame_locals')
if exists:
self._frame_locals.destroy()
def _right_click_menu_locals_table(self, event):
""" creates a right click menu for the locals table """
# create a right click menu
right_click_menu = tk.Menu(self._root, tearoff=0)
right_click_menu.add_command(label='Insert value to stack at X', command=self._insert_value_to_stack_at_x)
right_click_menu.add_command(label='Edit value', command=self._edit_variable_value)
right_click_menu.add_command(label='Copy value', command=self._copy_variable_value)
# add a line seperator to the menu
right_click_menu.add_separator()
# add item: "remove selected item"
right_click_menu.add_command(label='Remove selected item', command=self._remove_selected_item_from_locals_table)
right_click_menu.post(event.x_root, event.y_root)
def _right_click_menu_stack_table(self, event):
""" creates a right click menu for the stack table """
# create a right click menu
right_click_menu = tk.Menu(self._root, tearoff=0)
right_click_menu.add_command(label='Edit value', command=self._edit_stack_value)
right_click_menu.add_command(label='Copy Value', command=self.copy_stack_value)
# add a line seperator to the menu
right_click_menu.add_separator()
# add item: "remove selected item"
right_click_menu.add_command(label='Clear Stack', command=self.clear_stack)
right_click_menu.post(event.x_root, event.y_root)
def _insert_value_to_stack_at_x(self):
""" inserts the value of the selected item in the locals table to the stack at X """
selected = self._locals_table.selection()
if len(selected) == 0:
return
key = self._locals_table.item(selected)['text']
value = self._locals_table.item(selected)['values'][0]
self._c.user_entry(value)
self._update_stack_display()
self._update_message_display(f"Inserted value at x: {key}={value}")
def _copy_variable_value(self):
""" copies the value of the selected item in the locals table to the clipboard """
selected = self._locals_table.selection()
if len(selected) == 0:
return
value = self._locals_table.item(selected)['values'][0]
self._root.clipboard_clear()
self._root.clipboard_append(value)
self._root.update()
def _edit_variable_value(self):
""" opens a popup window to edit the value of the selected item in the locals table """
selected = self._locals_table.selection()
if len(selected) == 0:
return
key = self._locals_table.item(selected)['text']
value = self._locals_table.item(selected)['values'][0]
self.popup_edit_variable_value(key, value)
def popup_edit_variable_value(self, key, value):
""" opens a popup window to edit the value of the selected item in the locals table """
# create a new window
window = tk.Toplevel(self._root)
window.title('Edit Variable Value')
# create a label to ask the user to edit the value
label = ttk.Label(window, text=f'Edit the value for: {key}')
label.pack()
# create a text entry field
entry = ttk.Entry(window)
entry.insert(0, value)
# expand with window
entry.pack(expand=True, fill='x')
def apply_value():
new_value = entry.get()
self._c.user_entry(f"{key}={new_value}")
self._c.enter_press()
self._update_message_display()
self._update_locals_display()
self._update_stack_display()
window.destroy()
# create a button to save the changes
ttk.Button(window, text='OK', command=apply_value).pack()
# create a button to cancel the changes
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def _remove_selected_item_from_locals_table(self):
""" removes the selected item from the locals table """
selected = self._locals_table.selection()
if len(selected) == 0:
return
key = self._locals_table.item(selected)['text']
value = self._locals_table.item(selected)['values'][0]
self._c.delete_local(key)
self._update_locals_display()
self._update_message_display()
def _edit_stack_value(self):
""" opens a popup window to edit the value of the selected item in the stack table """
selected = self._stack_table.selection()
if len(selected) == 0:
return
key = self._stack_table.item(selected)['text']
value = self._stack_table.item(selected)['values'][0]
self.popup_edit_stack_value(key, value)
def popup_edit_stack_value(self, key, value):
""" opens a popup window to edit the value of the selected item in the stack table """
# create a new window
window = tk.Toplevel(self._root)
window.title('Edit Stack Value')
# create a label to ask the user to edit the value
label = ttk.Label(window, text=f'Edit the value for: {key}')
label.pack()
# create a text entry field
entry = ttk.Entry(window)
entry.insert(0, value)
entry.pack(expand=True, fill='x')
def apply_value():
new_value = entry.get()
# self._c.user_entry(f"{key}={new_value}")
self._c.clear_stack_level()
self._c.user_entry(new_value)
# self._c.enter_press()
self._update_message_display()
self._update_locals_display()
self._update_stack_display()
window.destroy()
# bind an enter keypress ro the apply value method
entry.bind('<Return>', lambda event: apply_value())
# create a button to save the changes
ttk.Button(window, text='OK', command=apply_value).pack()
# create a button to cancel the changes
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def _set_visibility_buttons(self, state: bool):
""" sets the visibility of the buttons based on the state """
# ttk buttons ane not the same across OS, need to adjust the width of the buttons
if self._os_type == OsType.WINDOWS:
button_width_mod = 4
elif self._os_type == OsType.LINUX:
button_width_mod = 2
elif self._os_type == OsType.MAC:
button_width_mod = 0 # the original was written on a MAC so the mods are for Windows and Linux
else:
button_width_mod = 0
if state is True:
self._settings.show_buttons = True
self._tk_var_menu_view_show_buttons.set(True)
else:
self._settings.show_buttons = False
self._tk_var_menu_view_show_buttons.set(False)
if self._settings.show_buttons is True:
bg_color = self._background_color
self._bottom_button_frame = UiFrame(self._root, background=bg_color, padx=5, pady=5)
self._bottom_button_frame.pack(fill='x', expand=True)
self._left_frame = UiFrame(self._bottom_button_frame, width=100, background=bg_color, padx=5, pady=5)
self._left_frame.pack(side='left')
self._right_frame = UiFrame(self._bottom_button_frame, width=100, background=bg_color, padx=5, pady=5)
self._right_frame.pack(side='right')
else:
pass # do this at the end of the method too to destroy the buttons
# Numeric buttons --------------------------------
# ttk buttons ane not the same across OS, need to adjust the width of the buttons
if self._os_type == OsType.WINDOWS:
button_width_mod = 5
elif self._os_type == OsType.LINUX:
button_width_mod = 2
elif self._os_type == OsType.MAC:
button_width_mod = 0 # the original was written on a MAC so the mods are for Windows and Linux
else:
button_width_mod = 0
if self._settings.show_buttons is True:
# create a frame for the math buttons
self._numeric_buttons = UiFrame(self._right_frame, background=self._background_color, padx=5, pady=5)
numbers = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '.', '0', '+/-']
# arrange the buttons on a grid in a standard calculator layout
for i, button in enumerate(numbers):
ttk.Button(self._numeric_buttons,
text=button,
command=lambda btn=button: self.button_press(btn),
width=2+button_width_mod,
).grid(row=i // 3, column=i % 3,)
self._numeric_buttons.pack()
else:
exists = hasattr(self, '_numeric_buttons')
if exists:
self._numeric_buttons.destroy()
# Calculation Buttons ---------------------------
if self._settings.show_buttons is True:
# create a frame for the calc buttons
self._calc_buttons = UiFrame(self._right_frame, background=self._background_color, padx=5, pady=5)
calc_buttons = ['delete', 'clear', 'x<->y', '1/x', 'enter', ]
more_buttons = ['x^2', 'x^y', 'e^x', 'pi', 'euler']
# arrange the buttons on a grid with the calc buttons on the right and the more buttons on the left
for i, button in enumerate(more_buttons):
ttk.Button(self._calc_buttons,
text=button,
command=lambda btn=button: self.button_press(btn),
width=5+button_width_mod,
).grid(row=i, column=0)
for i, button in enumerate(calc_buttons):
ttk.Button(self._calc_buttons,
text=button,
command=lambda btn=button: self.button_press(btn),
width=5+button_width_mod,
).grid(row=i, column=1)
self._calc_buttons.pack()
else:
exists = hasattr(self, '_calc_buttons')
if exists:
self._calc_buttons.destroy()
# Operation Buttons ---------------------------
if self._settings.show_buttons is True:
# create a frame for operation buttons
self._operation_buttons = UiFrame(self._left_frame, background=self._background_color, padx=5, pady=5)
operations = {'sqrt': 'sqrt', 'sin': 'sin', 'cos': 'cos', 'tan': 'tan', 'log': 'log10', 'ln': 'ln', }
# arrange the buttons on a grid in a standard calculator layout
indexs = range(len(operations))
names = operations.keys()
buttons = operations.values()
for i, name, button in zip(indexs, names, buttons):
ttk.Button(self._operation_buttons,
text=name,
width=3+button_width_mod,
command=lambda btn=button: self.button_press(btn),
).grid(row=i // 2, column=i % 2)
self._operation_buttons.pack()
else:
exists = hasattr(self, '_operation_buttons')
if exists:
self._operation_buttons.destroy()
# Special Buttons ---------------------------
if self._settings.show_buttons is True:
# create a frame for the special buttons
self._special_buttons = UiFrame(self._left_frame, background=self._background_color, padx=5, pady=5)
# place to the right of the numeric buttons
# create a button for 'stack to list'
ttk.Button(self._special_buttons,
text='stack to list',
command=lambda: self.button_press('stack_to_list'),
).pack(fill='x')
# create a button for 'iterable to stack'
ttk.Button(self._special_buttons,
text='iterable to stack',
command=lambda: self.button_press('iterable_to_stack'),
).pack(fill='x')
# create a button for 'stack to array'
ttk.Button(self._special_buttons,
text='stack to array',
command=lambda: self.button_press('stack_to_array'),
).pack(fill='x')
# create a button for rolling the stack
ttk.Button(self._special_buttons,
text='roll up',
command=lambda: self.button_press('roll_up'),
).pack(fill='x')
# create a button for rolling the stack down
ttk.Button(self._special_buttons,
text='roll down',
command=lambda: self.button_press('roll_down'),
).pack(fill='x')
# create a button for showing a plot
ttk.Button(self._special_buttons,
text='plot',
command=lambda: self.show_plot(),
).pack(fill='x')
self._special_buttons.pack()
else:
exists = hasattr(self, '_special_buttons')
if exists:
self._special_buttons.destroy()
if self._settings.show_buttons is False:
exists = hasattr(self, '_left_frame')
if exists:
self._left_frame.destroy()
exists = hasattr(self, '_right_frame')
if exists:
self._right_frame.destroy()
exists = hasattr(self, '_bottom_button_frame')
if exists:
self._bottom_button_frame.destroy()
def _set_visibility_message_field(self, state: bool):
""" sets the visibility of the message field based on the state """
if state is True:
# add a field at the bottom for text messages
self._message_field = tk.Text(self._top_frame, state='normal', height=2, font=self._settings.message_font)
# set width with settings
self._message_field.config(width=self._settings.message_width)
self._message_field.pack(expand=True, fill='x', padx=3)
self._settings.show_message_field = True
self._tk_var_menu_view_show_message_field.set(True)
self._update_message_display()
else:
exists = hasattr(self, '_message_field')
if exists:
self._message_field.destroy()
self._settings.show_message_field = False
self._tk_var_menu_view_show_message_field.set(False)
def _menu_view_show_message_field(self):
""" toggles the visibility of the message field """
self._settings.ui_visible_state = UiVisibleState.CUSTOM
if self._settings.show_message_field is True:
self._set_visibility_message_field(False)
else:
self._set_visibility_message_field(True)
def _menu_view_show_locals_table(self):
""" toggles the visibility of the locals table """
self._settings.ui_visible_state = UiVisibleState.CUSTOM
if self._settings.show_locals_table is True:
self._set_visibility_locals_table(False)
else:
self._set_visibility_locals_table(True)
def _menu_view_show_buttons(self):
""" toggles the visibility of the buttons """
self._settings.ui_visible_state = UiVisibleState.CUSTOM
if self._settings.show_buttons is True:
self._set_visibility_buttons(False)
else:
self._set_visibility_buttons(True)
def popup_confirm_clear_all_user_functions(self):
""" opens a popup window to confirm the user wants to clear all user functions """
# create a new window
window = tk.Toplevel(self._root)
window.title('Confirm Clear All Functions')
# create a label to ask the user if they are sure
label = ttk.Label(window, text='Are you sure you want to clear all user functions?')
label.pack()
def clear_all_user_functions():
self._c.clear_user_functions()
window.destroy()
# create a button to confirm the clear all user functions
ttk.Button(window, text='OK', command=clear_all_user_functions).pack()
# create a button to cancel the clear all user functions
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def popup_remove_user_function(self):
""" popup that has a list of user functions and a button to remove the selected function """
# create a new window
window = tk.Toplevel(self._root)
window.title('Remove User Function')
# create a list box to show the user functions
list_box = tk.Listbox(window, height=10, width=50)
for key in self._c.return_user_functions().keys():
list_box.insert('end', key)
list_box.pack()
def remove_user_function():
selected = list_box.curselection()
if len(selected) == 0:
return
key = list_box.get(selected)
self._c.clear_user_functions(key)
window.destroy()
# create a button to remove the selected function
ttk.Button(window, text='Remove', command=remove_user_function).pack()
# create a button to cancel the remove function
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def popup_add_function(self, function_string=None, parent_object=None):
""" opens a popup window to add a function to the calculator """
# create a new window
if parent_object is None:
parent = self._root
else:
parent = parent_object
window = tk.Toplevel(parent)
window.title('Add Function')
# create a text entry field
entry = tk.Text(window, height=25, width=50)
if function_string is None:
default_text = 'def sqr_x(x):\n return x**2'
txt = self._c.return_user_functions().get(self._settings.last_user_function_edit_name, default_text)
entry.insert('1.0', txt)
else:
entry.insert('1.0', function_string)
entry.focus()
entry.pack()
def apply_function():
function_string = entry.get('1.0', 'end')
try:
self._c.add_user_function(function_string)
except Exception as ex:
message = f"Error adding function: {ex}"
self._update_message_display(message)
else:
self._settings.last_user_function_edit_name = function_string.split('(')[0].split(' ')[1]
window.destroy()
# create a button to save the changes
ttk.Button(window, text='OK', command=apply_function).pack()
# create a button to cancel the changes
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def popup_show_user_functions(self):
""" opens a popup window to show the user defined functions """
# create a new window
window = tk.Toplevel(self._root)
window.title('User Functions')
# create a text entry field
entry = tk.Text(window, height=42, width=50)
func_dict = self._c.return_user_functions_for_display()
for key, value in func_dict.items():
entry.insert('end', f"Name: '{key}':\n{value}____________________________________________\n")
entry.pack()
# create a button to cancel the changes
ttk.Button(window, text='Cancel', command=window.destroy).pack()
def popup_show_all_functions(self):
""" opens a popup window to show the all functions available to the calculator """
# create a new window
window = tk.Toplevel(self._root)
window.title('All Functions')
# create a text entry field
entry = tk.Text(window, height=50, width=75)
func_dict = self._c.return_all_functions()
sorted_dict = dict(sorted(func_dict.items()))
for key, value in sorted_dict.items():
if '__' not in key:
try:
sig = inspect.signature(value)
except Exception as ex:
sig = '()'
entry.insert('end',
f"{key}{sig}:"
f"\n{value.__doc__}"
f"\n__________________________________________________________________________\n")
# add scroll bars to the text field
scroll = tk.Scrollbar(window)
scroll.pack(side='right', fill='y')
entry.config(yscrollcommand=scroll.set)
scroll.config(command=entry.yview)
entry.pack()
# add a numeric filed at the bottom of the window that shows the number of functions
ttk.Label(window, text=f"Number of functions: {len(func_dict)}").pack()
# create a button to cancel the changes
ttk.Button(window, text='Close', command=window.destroy).pack()
def popup_function_buttons(self):
""" opens a popup window to show the all user functions available to the calculator """
# create a new window
window = tk.Toplevel(self._root)
window.title('Function Buttons')
# create a frame for the function buttons
frame = UiFrame(window, background=self._background_color, padx=5, pady=5)
frame.pack()
# create a button for each function
func_dict = self._c.return_user_functions()
sorted_dict = dict(sorted(func_dict.items()))
for key, value in sorted_dict.items():
if '__' not in key:
ttk.Button(frame,
text=f"{key}",
command=lambda btn=key: self._popup_function_button_press(btn),
).pack(fill='x')
# create a button to cancel the changes
ttk.Button(window, text='Close', command=window.destroy).pack()
def _popup_function_button_press(self, function: str):
""" this method gets bound to the function buttons in the popup window """
self._c.enter_press()
self._c.user_entry(function)
self._c.enter_press()
self._update_stack_display()
self._update_message_display()
self._update_locals_display()
def _load_settings_on_launch(self):
""" looks for the settings file 'last_state_autosave' in the local directory and loads it if the user has
selected to save state on exit """
try:
file = open(self._autosave_path, 'rb')
except FileNotFoundError:
return # on a new system or if user never saves this is the expected behavior
except Exception as ex:
log(f"Error loading settings on launch: {ex}")
return
file_in_b = file.read()
file.close()
try:
calc_state = pickle.loads(file_in_b) # type: CalculatorUiState
log(f"loaded settings from file: {self._autosave_path}")
# only apply settings if the user has selected to save state on exit
if self._settings.save_state_on_exit is True:
self._load_calc_state(calc_state)
log(f"applied settings from file: {self._autosave_path}")
except Exception as ex:
self._update_message_display(f"Error loading settings on launch: {ex}")
def user_exit(self):
""" exits the program, saves the state if the settings are set to save state on exit """
if self._settings.save_state_on_exit:
self.menu_save_state(save_path=self._autosave_path)
log(f"clean exit")
self._root.quit()