-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
3160 lines (2534 loc) · 153 KB
/
gui.py
File metadata and controls
3160 lines (2534 loc) · 153 KB
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 sys
import os
import re
import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog, messagebox, font
from tktooltip import ToolTip
import ttkbootstrap as tb
from ttkbootstrap.constants import *
from PIL import ImageTk, Image
import atexit
import time
import json
from decimal import Decimal, ROUND_DOWN
from dataclasses import dataclass, field
from typing import Optional
import webbrowser
from datetime import datetime
import logging
import threading
# Get the absolute path of the directory containing the current script.
dir_path = os.path.dirname(os.path.realpath(__file__))
# Insert folder paths for modules
sys.path.insert(0, dir_path + "/denaro")
sys.path.insert(0, dir_path + "/denaro/wallet")
sys.path.insert(0, dir_path + "/denaro/wallet/utils")
import wallet_client
from denaro.wallet.utils.wallet_generation_util import sha256, generate_bip39_mnemonic_pattern
from denaro.wallet.utils.thread_manager import WalletThreadManager
from denaro.wallet.utils.tkinter_utils.custom_auto_complete_combobox import AutocompleteCombobox
from denaro.wallet.utils.tkinter_utils.custom_dialog import CustomDialog
from denaro.wallet.utils.tkinter_utils.dialogs import Dialogs
from denaro.wallet.utils.tkinter_utils.custom_popup import CustomPopup
from denaro.wallet.utils.tkinter_utils.mutually_exclusive_checkbox import MutuallyExclusiveCheckbox
import denaro.wallet.utils.tkinter_utils.universal_language_translator as universal_language_translator
# Patterns for SENSITIVE data that must be redacted from logs and securely deleted.
sensitive_patterns = [
re.compile(wallet_client.ADDRESS_PATTERN), # Denaro Wallet Address
re.compile(generate_bip39_mnemonic_pattern()), # 12-word BIP39 Mnemonic
re.compile(r'^(0x)?[0-9a-fA-F]{32,}$'), # Long Hex (Private Keys, Hashes)
]
# Patterns for NON-SENSITIVE data that should simply not be translated.
non_translatable_patterns = [
re.compile(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}(:\d+)?$'), # IP Addresses
re.compile(r'^(https?://|ftp://|www\.)[^\s]+$'), # URLs
re.compile(r'^Denaro Wallet Client v[0-9\.\-a-zA-Z]+\sGUI.*$'), # Title
]
class BasePage(ttk.Frame):
def __init__(self, parent, root, *args, **kwargs):
super().__init__(parent, *args, **kwargs)
self.root = root
#self.create_widgets()
#def create_widgets(self):
# pass
class AccountPage(BasePage):
def __init__(self, parent, root):
super().__init__(parent, root)
if self.root.disable_exchange_rate_features:
self.column_sort_order = {"Balance": False, "Pending": False}
else:
self.column_sort_order = {"Balance": False, "Pending": False, "Value": False}
self.create_widgets() # Create and place widgets
self.configure_layout() # Configure the grid layout of the AccountPage
# Dynamically identify selectable widgets
self.root.selectable_widgets.extend(self.root.gui_utils.identify_selectable_widgets(self))
def configure_layout(self):
# Grid and column layout for page
self.grid_rowconfigure(1, weight=1)
self.grid_columnconfigure(0, weight=1)
# Balance frame
self.balance_frame.grid_rowconfigure(0, weight=1)
self.balance_frame.grid_rowconfigure(1, weight=1)
self.balance_frame.grid_columnconfigure(0, weight=0) # Logo column
self.balance_frame.grid_columnconfigure(1, weight=1) # Text column
self.balance_frame.grid(row=0, column=0, sticky='ew')
# Logo placement
self.logo_container.grid(row=0, column=0, rowspan=2, sticky='nw')
# Balance and value labels
if self.root.disable_exchange_rate_features:
self.total_balance_text.grid(row=0, column=1, sticky='nw', padx=5,)
else:
self.denaro_price_text.grid(row=0, column=1, sticky='nw', padx=5, pady=5)
self.total_balance_text.grid(row=1, column=1, sticky='nw', padx=5,)
self.total_value_text.grid(row=1, column=1, sticky='sw', padx=5, pady=(0, 5))
# Accounts frame
self.accounts_frame.grid_columnconfigure(0, weight=1)
self.accounts_frame.grid_rowconfigure(0, weight=1)
self.accounts_frame.grid(row=1, column=0, sticky='nsew')
# TreeView and scrollbar
self.accounts_tree.grid(row=0, column=0, sticky='nsew')
self.accounts_tree_scrollbar.grid(row=0, column=1, sticky='ns')
# Refresh balance button
self.refresh_balance_button.grid(row=1, column=2, sticky='w', padx=5, pady=5)
def create_widgets(self):
# Balance and accounts view for the "Account" page
self.balance_frame = tb.Frame(self, style='balance_frame.TFrame')
# Logo container frame
self.logo_container = tb.Frame(self.balance_frame, borderwidth=2, relief="solid", padding=1, style='balance_frame.TFrame')
logo = Image.open("./denaro/gui_assets/denaro_logo.png")
logo = logo.resize((60, 60), Image.LANCZOS)
logo = ImageTk.PhotoImage(logo)
self.logo_label = tb.Label(self.logo_container, image=logo, background='black')
self.logo_label.image = logo
self.logo_label.pack(padx=1, pady=1) # Padding inside the container
#Balance and value labels
self.total_balance_text = tb.Label(self.balance_frame, text="Total balance:", foreground='white', background='black')
if not self.root.disable_exchange_rate_features:
self.denaro_price_text = tb.Label(self.balance_frame, text="DNR/USD Price:", foreground='white', background='black')
self.total_value_text = tb.Label(self.balance_frame, text="Total Value:", foreground='white', background='black')
# Accounts frame
self.accounts_frame = tb.Frame(self)
# TreeView and scrollbar
if self.root.disable_exchange_rate_features:
self.columns = ("Address", "Balance", "Pending")
else:
self.columns = ("Address", "Balance", "Pending", "Value")
self.accounts_tree = ttk.Treeview(self.accounts_frame, columns=self.columns, show='headings', selectmode='browse')
self.accounts_tree_scrollbar = ttk.Scrollbar(self.accounts_frame, orient="vertical", command=self.accounts_tree.yview)
self.accounts_tree.configure(yscrollcommand=self.accounts_tree_scrollbar.set)
# Bind the click event to the Treeview widget
self.accounts_tree.bind("<Button-1>", self.root.gui_utils.on_treeview_click)
# Create a font object for measuring text width
self.treeview_font = font.nametofont("TkDefaultFont")
# Calculate minimum width for each column based on the title
self.column_min_widths = {}
for col in self.columns:
self.accounts_tree.heading(col, text=col)
title_width = self.treeview_font.measure(col) + 40 # Extra space for padding
self.column_min_widths[col] = title_width
self.accounts_tree.column(col, minwidth=self.column_min_widths[col], stretch=tk.YES)
# Configure the striped row tags
self.accounts_tree.tag_configure('oddrow', background='white') # Light gray color for odd rows
self.accounts_tree.tag_configure('evenrow', background='#cee0e7') # A slightly different shade for even row
if self.root.disable_exchange_rate_features:
heading_names = ["Balance", "Pending"]
else:
heading_names = ["Balance", "Pending", "Value"]
for col in heading_names:
self.accounts_tree.heading(col, text=col+" ⥮", command=lambda _col=col: self.root.gui_utils.sort_treeview_column(self.accounts_tree, _col))
# Refresh balance button
self.refresh_balance_button = tb.Button(self.balance_frame, text="Refresh Balance", state='disabled')
self.refresh_balance_button.config(command=lambda: self.root.gui_utils.refresh_balance())
class SendPage(BasePage):
def __init__(self, parent, root):
super().__init__(parent, root)
self.create_widgets() # Create and place widgets
self.configure_layout() # Configure the grid layout of the AccountPage
# Dynamically identify selectable widgets
self.root.selectable_widgets.extend(self.root.gui_utils.identify_selectable_widgets(self))
def configure_layout(self):
# Grid and column layout for page
for i in range(4):
self.grid_rowconfigure(i, weight=0)
self.grid_rowconfigure(6, weight=1) # Allow the tx_log row to expand
self.grid_columnconfigure(0, weight=0) # Adjust if you want the first column to also expand
self.grid_columnconfigure(1, weight=1) # Ensure column 1 can expand
self.grid_columnconfigure(2, weight=1) # Ensure column 2 can expand, for tx_log and valid_recipient_address
# Send from
self.send_from_label.grid(row=0, column=0, sticky='w', padx=10, pady=5)
self.send_from_combobox.grid(row=0, column=1, sticky='w', padx=5, pady=5)
# Amount
self.amount_label.grid(row=1, column=0, sticky='w', padx=10, pady=0)
self.amount_inner_frame.grid(row=1, column=1, sticky='w', padx=5, pady=0)
self.amount_entry.pack(side='left')
self.half_amount_button.pack(side='left', padx=(5, 0), pady=0)
self.max_amount_button.pack(side='left', padx=(5, 0), pady=0)
#self.amount_entry.grid(row=1, column=1, sticky='w', padx=5, pady=0)
#self.max_amount_button.grid(row=1, column=2)
# Recipient
self.recipient_label.grid(row=2, column=0, sticky='w', padx=10, pady=5)
self.recipient_inner_frame.grid(row=2, column=1, sticky='w', padx=5, pady=5)
self.recipient_entry.pack(side='left')
self.valid_recipient_address.pack(side='left', padx=(5, 0))
# Transaction message
self.message_label.grid(row=3, column=0, sticky='w', padx=10, pady=5)
self.message_inner_frame.grid(row=3, column=1, sticky='w', padx=5, pady=5)
self.message_entry.pack(side='left')
self.max_message_entry_length_message.pack(side='left', padx=(5, 0))
#self.message_entry.grid(row=3, column=1, sticky='w', padx=5, pady=5)
#Send button
self.send_button.grid(row=4, column=0, padx=0, pady=10)
#Transaction log
self.tx_log_label.grid(row=5, column=0, sticky='w', padx=10, pady=5)
self.tx_log.grid(row=6, column=0, columnspan=3, sticky='nsew')
#Clear transaction log button
self.clear_tx_log.grid(row=5, column=0, columnspan=4,sticky='e', padx=5, pady=5)
def create_widgets(self):
# Send from
self.send_from_label = tb.Label(self, text="Send From:")
self.send_from_combobox_text = tk.StringVar()
self.send_from_combobox_text.trace_add("write", self.check_send_params)
self.send_from_combobox = ttk.Combobox(self, textvariable=self.send_from_combobox_text, width=50, state='disabled')
self.send_from_combobox['values'] = []
# Amount
self.amount_inner_frame = tb.Frame(self)
self.amount_label = tb.Label(self, text="Amount:")
vcmd = self.register(self.validate_send_amount_input)
self.amount_entry_text = tk.StringVar()
self.amount_entry_text.trace_add("write", self.check_send_params)
self.amount_entry = tb.Entry(self.amount_inner_frame, validate="key", validatecommand=(vcmd, '%P'), textvariable=self.amount_entry_text, width=10,state='disabled')
self.half_amount_button = tb.Button(self.amount_inner_frame, text="Half", state='disabled')
self.half_amount_button.config(command=lambda: self.set_send_amount(half=True))
self.max_amount_button = tb.Button(self.amount_inner_frame, text="Max", state='disabled')
self.max_amount_button.config(command=lambda: self.set_send_amount())
# Recipient
self.recipient_inner_frame = tb.Frame(self)
self.recipient_label = tb.Label(self, text="Recipient Address:")
self.recipient_entry_text = tb.StringVar()
self.recipient_entry_text.trace_add("write", self.check_send_params)
self.recipient_entry = tb.Entry(self.recipient_inner_frame, validate="focusout", textvariable=self.recipient_entry_text, width=50, state='disabled')
self.valid_recipient_address = tb.Label(self.recipient_inner_frame)
# Transaction message
self.message_inner_frame = tb.Frame(self)
self.message_label = tb.Label(self, text="Transaction Message:")
self.message_entry_text = tb.StringVar()
self.message_entry_text.trace_add("write", self.check_send_params)
self.message_entry = tb.Entry(self.message_inner_frame, width=30, textvariable=self.message_entry_text, state='disabled')
self.max_message_entry_length_message = tb.Label(self.message_inner_frame)
# Send button
self.send_button = tb.Button(self, text="Send", state='disabled')
self.send_button.config(command=lambda: self.root.wallet_operations.tx_auth())
#Transaction log
self.tx_log_label = tb.Label(self, text="Log:")
self.tx_log = scrolledtext.ScrolledText(self)
tx_log_separator = f'----------------------------------------------------------------\n'
self.tx_log.insert(tk.INSERT, tx_log_separator)
self.tx_log.config(state='disabled')
#Clear transaction log button
self.clear_tx_log = tb.Button(self, text="Clear")
self.clear_tx_log.config(command=lambda: (self.clear_tx_log.focus_set(), self.tx_log.config(state='normal'), self.tx_log.delete('1.0', tk.END), self.tx_log.insert(tk.INSERT, tx_log_separator), self.tx_log.config(state='disabled')))
def check_send_params(self, *args):
if self.recipient_entry.get() and self.validate_recipient_address(self.recipient_entry.get()):
self.valid_recipient_address.config(text="Valid Denaro Address ✓", foreground='green')
if self.send_from_combobox.get() and self.amount_entry.get():
if float(self.amount_entry.get()) != 0.0 and self.root.stored_data.wallet_loaded:
self.send_button.config(state='normal')
else:
self.send_button.config(state='disabled')
else:
self.send_button.config(state='disabled')
else:
if self.recipient_entry.get():
self.valid_recipient_address.config(text="Invalid Denaro Address ✖", foreground='red')
else:
self.valid_recipient_address.config(text="", foreground='')
self.send_button.config(state='disabled')
if self.send_from_combobox.get() == "":
self.max_amount_button.config(state='disabled')
self.half_amount_button.config(state='disabled')
else:
self.max_amount_button.config(state='normal')
self.half_amount_button.config(state='normal')
message_extension = wallet_client.transaction_message_extension
max_message_length = 255 - len(message_extension) + 3
max_len_str = f'{abs(len(self.message_entry_text.get()))}/{max_message_length}'
if len(self.message_entry_text.get()) >= int(max_message_length):
self.max_message_entry_length_message.config(text=f"{max_message_length}/{max_message_length} (Max Message Length Reached)", foreground='red')
self.message_entry_text.set(self.message_entry_text.get()[:int(max_message_length)])
if len(self.message_entry_text.get()) < int(max_message_length):
self.max_message_entry_length_message.config(text=max_len_str, foreground='')
def validate_recipient_address(self, content):
if re.match(wallet_client.ADDRESS_PATTERN, content):
return True
return False
def validate_send_amount_input(self, P):
# P is the value of the entry if the edit is allowed
if P.strip() == "":
# Allow the empty string so that it can clear the entry field
return True
try:
float(P)
return True
except ValueError:
return False
def set_send_amount(self, half=False):
"""
Set the maximum amount to send based on the balance of the selected address.
This function retrieves the sender address from the combobox, then searches through the stored
balance data to find the matching address. It sets the amount entry text to the balance of the
selected address. If the `half` parameter is True, it will set the amount to half of the current amount.
"""
sender = self.send_from_combobox.get()
# Define the decimal places
decimal_places = Decimal('0.000000')
# Handle halving the current amount if requested
if half and self.amount_entry_text.get():
try:
current_amount = Decimal(self.amount_entry_text.get())
if current_amount != Decimal('0.000000'):
balance_amount = (current_amount / 2).quantize(decimal_places, rounding=ROUND_DOWN)
self.amount_entry_text.set(str(balance_amount))
return
except ValueError as e:
print(f"Error converting current amount: {e}")
return
# Check if balance data is available
if not half and self.root.stored_data.balance_data:
balance_data = self.root.stored_data.balance_data['balance_data']
# Combine 'addresses' and 'imported_addresses' into one list for iteration
all_addresses = balance_data.get('addresses', []) + balance_data.get('imported_addresses', [])
# Loop through all addresses to find the sender address
for address in all_addresses:
if sender == address['address']:
# Convert balance to Decimal and set the amount with controlled decimal places
try:
balance_amount = Decimal(address['balance']['amount']).quantize(decimal_places, rounding=ROUND_DOWN)
self.amount_entry_text.set(str(balance_amount))
except ValueError as e:
print(f"Error converting balance amount for address {sender}: {e}")
break # Exit the loop once the sender address is found
class SettingsPage(BasePage):
def __init__(self, parent, root):
super().__init__(parent, root)
# Currency related attributes
self.prev_currency_code = None
self.currency_code_valid = False
self.currency_code = ""
self.currency_symbol = ""
# --- Language related attributes ---
self.prev_language = None
self.language_valid = False
self.language = ""
# ----------------------------------------
# --- Translation module change handling flags ---
self._is_updating_translation_module = False
# ----------------------------------------
self.keep_save_button_disabled = False
self.create_widgets() # Create and place widgets
self.configure_layout() # Configure the grid layout of the AccountPage
self.update_save_button_state()
# Dynamically identify selectable widgets
self.root.selectable_widgets.extend(self.root.gui_utils.identify_selectable_widgets(self))
def configure_layout(self):
# Position the currency code related widgets
if not self.root.disable_exchange_rate_features:
self.currency_code_inner_frame.grid(row=0, column=0, sticky='ew', padx=10)
self.currency_code_label.pack(side='left', padx=5, pady=5)
self.currency_code_combobox.pack(side='left', padx=5, pady=5)
self.valid_currency_code.pack(side='left', padx=5, pady=5)
# Position the Denaro Node widgets within the denaro_node_frame
self.denaro_node_frame.grid(row=1, column=0, sticky='w', padx=15, pady=10, ipady=5)
# Address label and entry
self.denaro_node_address_label.grid(row=1, column=0, sticky='w', padx=5, pady=(10, 0))
self.denaro_node_address_frame.grid(row=2, column=0, sticky='ew', padx=5)
self.denaro_node_address_entry.pack(side='left', fill='x', expand=True)
# Colon (:) label
self.denaro_node_colon.grid(row=2, column=1, sticky='ew') # Ensure it sticks to east-west to center the colon
# Port label and entry
self.denaro_node_port_label.grid(row=1, column=2, sticky='w', padx=5, pady=(10, 0))
self.denaro_node_port_frame.grid(row=2, column=2, sticky='ew', padx=5)
self.denaro_node_port_entry.pack(side='left', fill='x', expand=True)
# Node validation checkbox
self.disable_node_validation_checkbox.grid(row=3, column=0, sticky='w', padx=5, pady=10)
self.test_connection_button.grid(row=3, column=2, sticky='e', padx=5, pady=10)
self.node_validation_msg_label.grid(row=3, column=0, sticky='w', padx=5, pady=(75,0))
# Ensure the denaro_node_frame columns do not affect the overall layout
self.denaro_node_frame.columnconfigure(0, weight=1)
self.denaro_node_frame.columnconfigure(1, weight=0)
self.denaro_node_frame.columnconfigure(2, weight=1)
# --- Position the language translation settings frame ---
self.language_translation_frame.grid(row=2, column=0, sticky='ew', padx=10, pady=5)
# Translation Module section
self.translation_module_section_label.pack(fill='x', padx=5, pady=(5, 2))
self.translation_module_frame.pack(fill='x', padx=(25, 5), pady=2)
self.argostranslate_checkbox.pack(side='left', padx=5, pady=2)
self.deep_translator_checkbox.pack(side='left', padx=5, pady=2)
# Translation module label (below checkboxes)
self.translation_module_label.pack(fill='x', padx=(25, 5), pady=(0, 5))
# Language selection widgets inside the frame
self.language_frame.pack(fill='x', padx=5, pady=5)
self.language_label.pack(side='left', padx=5, pady=5)
self.language_combobox.pack(side='left', padx=5, pady=5)
self.valid_language_label.pack(side='left', padx=5, pady=5)
# Language cache widgets
self.language_cache_frame.pack(fill='x', padx=5, pady=5)
self.language_cache_label.pack(side='left', padx=5, pady=5)
self.language_cache_combobox.pack(side='left', padx=5, pady=5)
self.clear_cache_button.pack(side='left', padx=5, pady=5)
# ---------------------------------------------
# Save config button
self.save_config_frame.grid(row=3, column=0, sticky='we', padx=10)
self.save_config_button.pack(pady=10, side='right')
def create_widgets(self):
# Settings Page Layout
#######################################################################################
#Currency code
if not self.root.disable_exchange_rate_features:
self.currency_code_inner_frame = tb.Frame(self)
self.currency_code_label = tb.Label(self.currency_code_inner_frame, text="Default Currency:")
self.valid_currency_code = tb.Label(self.currency_code_inner_frame)
#Initialize currency code function
wallet_client.is_valid_currency_code()
#Get list of valid codes
self.currency_codes = list(wallet_client.is_valid_currency_code.valid_codes.keys())
# Create custom Combobox
self.currency_code_combobox = AutocompleteCombobox(self.currency_code_inner_frame, width=20, completevalues=self.currency_codes, state='normal')
# Add separators at specific indices
self.separators = ["--- Fiat Currencies ---", "--- Crypto Currencies ---"]
self.root.gui_utils.add_combobox_separator_at_index(self.currency_code_combobox, self.separators[0], 0) # Adds the first separator
self.root.gui_utils.add_combobox_separator_at_index(self.currency_code_combobox, self.separators[1], 162) # Adds the second separator
self.currency_code_combobox.current(147)
self.last_valid_selection = self.currency_code_combobox.current()
self.currency_code_combobox.bind('<<ComboboxSelected>>', self.root.gui_utils.on_currency_code_combobox_select)
# Validate currency code on init
self.after(100, self.validate_currency_code)
#Validate currency code on each write
self.currency_code_combobox.var.trace_add("write", self.validate_currency_code)
self.denaro_node_frame = tb.LabelFrame(self, text="Denaro Node Configuration", width=20)
self.denaro_node_address_label = tb.Label(self.denaro_node_frame, text="Address")
self.denaro_node_address_frame = tb.Frame(self.denaro_node_frame)
self.denaro_node_address_entry = tb.Entry(self.denaro_node_address_frame, validate="focusout", width=30)#, state='disabled')
self.denaro_node_address_entry_text = tb.StringVar()
self.denaro_node_address_entry_text.trace_add("write", self.on_node_field_change)
self.denaro_node_address_entry["textvariable"] = self.denaro_node_address_entry_text
self.denaro_node_colon = tb.Label(self.denaro_node_frame, text=":")
self.denaro_node_port_label = tb.Label(self.denaro_node_frame, text="Port")
self.denaro_node_port_frame = tb.Frame(self.denaro_node_frame)
self.denaro_node_port_entry = tb.Entry(self.denaro_node_port_frame, validate="focusout", width=30)
self.denaro_node_port_entry_text = tb.StringVar()
self.denaro_node_port_entry_text.trace_add("write", self.on_node_field_change)
self.denaro_node_port_entry["textvariable"] = self.denaro_node_port_entry_text
self.disable_node_validation_checkbox = tk.Checkbutton(self.denaro_node_frame, text='Disable Node Validation')
self.disable_node_validation_var = tk.BooleanVar()
self.disable_node_validation_var.trace_add("write", self.on_node_field_change)
self.disable_node_validation_checkbox["variable"] = self.disable_node_validation_var
self.test_connection_button = tb.Button(self.denaro_node_frame, text="Test Connection")
self.test_connection_button.config(command=lambda: self.test_node_connection())
self.node_validation_msg_label = tb.Label(self.denaro_node_frame, text="")
# --- Language Translation Settings LabelFrame ---
self.language_translation_frame = tb.LabelFrame(self, text="Language Translation Settings")
# --- Translation Module section ---
self.translation_module_section_label = tb.Label(self.language_translation_frame, text="Translation Module:")
self.translation_module_frame = tb.Frame(self.language_translation_frame)
with self.root.translation_engine.no_translate():
self.argostranslate_checkbox = MutuallyExclusiveCheckbox(
self.translation_module_frame,
text='Argos Translate',
callback=self.on_translation_module_change
)
with self.root.translation_engine.no_translate():
self.deep_translator_checkbox = MutuallyExclusiveCheckbox(
self.translation_module_frame,
text='Deep Translator',
callback=self.on_translation_module_change
)
# Bind the checkboxes together for mutual exclusivity
MutuallyExclusiveCheckbox.bind_group(self.argostranslate_checkbox, self.deep_translator_checkbox)
self.translation_module_label = tb.Label(self.language_translation_frame, text="", foreground='gray')
# ------------------------------------------
# --- Language widget creation ---
self.language_frame = tb.Frame(self.language_translation_frame)
self.language_label = tb.Label(self.language_frame, text="Language:")
# The combobox uses the display names (the dictionary values)
#with translation_engine.no_translate():
self.language_display_names = list(self.root.translation_engine.language_map.values())
self.language_combobox = AutocompleteCombobox(self.language_frame, width=20, completevalues=self.language_display_names, state='normal')
# Validate language on init
self.after(100, self.validate_language)
# Validate language on each write
self.language_combobox.var.trace_add("write", self.validate_language)
self.valid_language_label = tb.Label(self.language_frame)
# ------------------------------------------
# --- Language cache widgets ---
self.language_cache_frame = tb.Frame(self.language_translation_frame)
self.language_cache_label = tb.Label(self.language_cache_frame, text="Language Cache:")
self.language_cache_combobox = tb.Combobox(self.language_cache_frame, state='readonly', width=30)
self.language_cache_combobox.bind('<<ComboboxSelected>>', lambda e: self.update_clear_cache_button_state())
self.clear_cache_button = tb.Button(self.language_cache_frame, text="Clear", command=self.clear_language_cache)
self.update_language_cache_list()
# ------------------------------------------
# Save config button
self.save_config_frame = tb.Frame(self)
self.save_config_button = tb.Button(self.save_config_frame, text="Save Settings", state='disabled')
self.save_config_button.config(command=lambda: self.root.config_handler.save_config())
#######################################################################################
# End of Settings Page Layout
def validate_currency_code(self, *args):
self.current_selection = self.currency_code_combobox.get()
# Check if the combo box selection has changed since the last check
if self.current_selection != self.prev_currency_code:
self.currency_code_valid, self.currency_symbol = wallet_client.is_valid_currency_code(code=self.current_selection, get_return=True) if self.current_selection else (False, "$")
self.root.stored_data.currency_symbol = self.currency_symbol
if self.currency_code_valid:
self.valid_currency_code.config(text="Valid Currency Code ✓", foreground='green')
#self.save_config_button.config(state='normal')
self.currency_code = self.current_selection
self.root.stored_data.currency_code = self.current_selection
self.last_valid_selection = self.currency_code_combobox.current()
self.root.account_page.denaro_price_text.config(text=f'DNR/{self.currency_code_combobox.get()} Price: {self.root.stored_data.currency_symbol}')
else:
self.valid_currency_code.config(text="Invalid Currency Code ✖", foreground='red')
#self.save_config_button.config(state='disabled')
self.currency_code = "USD"
self.root.account_page.denaro_price_text.config(text=f'DNR/USD Price: {self.root.stored_data.currency_symbol}')
self.root.event_handler.price_timer = 0
# Update last valid selection
#last_valid_selection = currency_code_combobox.current()
self.prev_currency_code = self.current_selection
self.update_save_button_state() # Update button state on validation change
if not self.currency_code_combobox['values'][0] == self.separators[0]:
self.root.gui_utils.add_combobox_separator_at_index(self.currency_code_combobox, self.separators[0], 0)
if not self.currency_code_combobox['values'][162] == self.separators[1]:
self.root.gui_utils.add_combobox_separator_at_index(self.currency_code_combobox, self.separators[1], 162)
# --- Language validation method ---
def validate_language(self, *args):
# The value from the combobox is the display name (e.g., "Deutsch")
current_display_name = self.language_combobox.get()
# Use the display name for the change-check to prevent re-validation loops
if current_display_name != self.prev_language:
# Validate that the display name is one of the valid options
if current_display_name in self.root.translation_engine.language_map.values():
self.language_valid = True
self.valid_language_label.config(text="Valid Language ✓", foreground='green')
# Find the corresponding language code (e.g., "de") to store internally
for code, name in self.root.translation_engine.language_map.items():
if name == current_display_name:
# self.language now holds the language code
self.language = code
break
else:
self.language_valid = False
self.valid_language_label.config(text="Invalid Language ✖", foreground='red')
# Fallback to the English language code
self.language = "en"
# prev_language should track the display name
self.prev_language = current_display_name
self.update_save_button_state()
def _set_translation_module_state(self, module, update_prev_state=True):
"""Helper method to set translation module checkbox state"""
self._is_updating_translation_module = True
try:
if module == 'argostranslate':
self.argostranslate_checkbox.set(True)
self.update_translation_module_label('argostranslate')
elif module == 'deep-translator':
self.deep_translator_checkbox.set(True)
self.update_translation_module_label('deep-translator')
else:
# Uncheck both (translation disabled)
self.argostranslate_checkbox.set(False)
self.deep_translator_checkbox.set(False)
self.update_translation_module_label(None)
finally:
self._is_updating_translation_module = False
def on_translation_module_change(self, checkbox, is_checked):
"""Handle changes to translation module checkboxes"""
# Prevent recursive calls during programmatic updates
if self._is_updating_translation_module:
return
argostranslate_checked = self.argostranslate_checkbox.get()
deep_translator_checked = self.deep_translator_checkbox.get()
# Handle normal state: one checkbox is checked
if argostranslate_checked:
self.update_translation_module_label('argostranslate')
self.language_combobox.config(state='normal')
self.update_save_button_state()
elif deep_translator_checked:
self.update_translation_module_label('deep-translator')
self.language_combobox.config(state='normal')
self.update_save_button_state()
else:
# Both are unchecked - show confirmation if user manually unchecked one
# But only if translation is currently enabled (not already disabled)
current_translation_module = self.root.config_handler.config_values.get('translation_module')
translation_already_disabled = (current_translation_module is None or current_translation_module == '')
# Determine which module was just unchecked
module_to_restore = 'argostranslate' if checkbox is self.argostranslate_checkbox else 'deep-translator'
# If translation is already disabled, just update the UI state without showing dialog
if translation_already_disabled:
self.update_translation_module_label(None)
self.language_combobox.config(state='disabled')
self.update_save_button_state()
return
def on_user_confirmation(confirmed):
if not confirmed:
# User canceled - restore the checkbox that was just unchecked
self._is_updating_translation_module = True
try:
self._set_translation_module_state(module_to_restore)
self.language_combobox.config(state='normal')
finally:
self._is_updating_translation_module = False
else:
# User confirmed - translation is disabled
self.update_translation_module_label(None)
self.language_combobox.config(state='disabled')
self.update_save_button_state()
# Show confirmation dialog
self.root.dialogs.confirmation_prompt(
title="Disable Language Translation",
msg="Leaving the Translation Module unset will disable language translation and set the current language to English once the settings are saved.\nDo you want to continue?",
on_complete=on_user_confirmation
)
def update_translation_module_label(self, module):
"""Update the translation module label based on selected module"""
if module == 'argostranslate':
self.translation_module_label.config(
text="Argos Translate uses PyTorch and can be resource intensive on slower systems.",
foreground='green'
)
elif module == 'deep-translator':
self.translation_module_label.config(
text="Deep Translator may reduce privacy as it uses the Internet and Google Translate.",
foreground='green'
)
else:
self.translation_module_label.config(text="", foreground='gray')
def update_language_cache_list(self):
"""Update the language cache combobox with available cache files"""
cache_dir = "language_cache"
cache_files = []
if os.path.exists(cache_dir):
for filename in os.listdir(cache_dir):
if filename.endswith('.json'):
cache_files.append(filename)
cache_files.sort()
self.language_cache_combobox['values'] = cache_files
if cache_files:
self.language_cache_combobox.current(0)
self.update_clear_cache_button_state()
else:
self.clear_cache_button.config(state='disabled')
def update_clear_cache_button_state(self):
"""Update the Clear Language Cache button state based on selected cache file content"""
selected_file = self.language_cache_combobox.get()
if not selected_file:
self.clear_cache_button.config(state='disabled')
return
cache_dir = "language_cache"
cache_file_path = os.path.join(cache_dir, selected_file)
if os.path.exists(cache_file_path):
try:
with open(cache_file_path, 'r', encoding='utf-8') as f:
cache_data = json.load(f)
if cache_data and len(cache_data) > 0:
# Cache has content - enable button
self.clear_cache_button.config(state='normal')
else:
# Cache is empty - disable button
self.clear_cache_button.config(state='disabled')
except (json.JSONDecodeError, ValueError, IOError):
# If file is invalid JSON or can't be read, disable button
self.clear_cache_button.config(state='disabled')
else:
# File doesn't exist - disable button
self.clear_cache_button.config(state='disabled')
def clear_language_cache(self):
"""Clear the selected language cache file"""
selected_file = self.language_cache_combobox.get()
if not selected_file:
return
cache_dir = "language_cache"
cache_file_path = os.path.join(cache_dir, selected_file)
if os.path.exists(cache_file_path):
try:
# Check if cache file has content before clearing
cache_has_content = False
try:
with open(cache_file_path, 'r', encoding='utf-8') as f:
cache_data = json.load(f)
if cache_data and len(cache_data) > 0:
cache_has_content = True
except (json.JSONDecodeError, ValueError):
# If file is invalid JSON or empty, consider it already cleared
cache_has_content = False
# Clear the file contents but don't delete it
with open(cache_file_path, 'w', encoding='utf-8') as f:
json.dump({}, f, indent=2, ensure_ascii=False)
# Update the cache in the translation engine if it's the current cache
if hasattr(self.root.translation_engine, 'cache_file') and self.root.translation_engine.cache_file == cache_file_path:
self.root.translation_engine.cache = {}
self.root.translation_engine.reverse_cache = {}
# Update button state after clearing
self.update_clear_cache_button_state()
# Show popup notification only if cache had content
if cache_has_content:
self.root.custom_popup.add_popup(
timeout=5000,
prompt=[{"label_config":"text='Language Cache Cleared', background='#2780e3', anchor='center', font='Calibri 10 bold'", "grid_config":"sticky='nsew'"}],
grid_layout_config=[{"grid_row_config":"index=0, weight=1"}, {"grid_column_config":"index=0, weight=1"}]
)
except Exception as e:
# Silently fail - the button should be disabled if there are no files anyway
pass
def validate_node_fields(self, *args):
check_connection = False
try:
if args[1]:
check_connection = True
except Exception:
pass
address = self.denaro_node_address_entry.get().strip()
port = self.denaro_node_port_entry.get().strip()
# Construct the address:port string conditionally including the port
node = f"{address}:{port}" if port else address
node_validation_enabled = self.disable_node_validation_var.get()
_ , node_str, string_valid, return_msg = wallet_client.Verification.validate_node_address([node, False], from_gui=True, check_connection=check_connection, referer="validate_node_fields")
if return_msg != "":
self.node_validation_msg_label.config(text=return_msg)
if "ERROR" in return_msg:
self.node_validation_msg_label.config(foreground='#ff0000')
else:
self.node_validation_msg_label.config(foreground='#008000')
if 'fade_node_validation_msg_label' in self.root.event_handler.thread_event and 'node_validation_msg_label' in self.root.gui_utils.fade_text_widgets:
self.root.gui_utils.fade_text_widgets['node_validation_msg_label']['step'] = 1
else:
self.root.wallet_thread_manager.start_thread("fade_node_validation_msg_label", self.root.gui_utils.fade_text, args=(self.node_validation_msg_label, 'node_validation_msg_label', 5,),)
if node_str is None:
node_str = node
if check_connection:
self.test_connection_button.config(state='normal')
return node_str, string_valid, node_validation_enabled
def test_node_connection(self):
self.test_connection_button.config(state='disabled')
if 'fade_node_validation_msg_label' in self.root.event_handler.thread_event:
self.root.wallet_thread_manager.stop_thread('fade_node_validation_msg_label')
self.node_validation_msg_label.config(foreground='#008000')
self.node_validation_msg_label.config(text="Testing connection to node. Please wait...")
if self.node_validation_msg_label['text'] == "Testing connection to node. Please wait...":
self.root.update()
time.sleep(1)
self.root.wallet_thread_manager.start_thread("validate_node_fields", self.validate_node_fields, args=(True,),)
def on_node_field_change(self, *args):
# Resets the flag to re-enable save button upon field change
if self.keep_save_button_disabled:
self.keep_save_button_disabled = False
self.update_save_button_state()
def update_save_button_state(self):
# Dynamically updates the 'Save Settings' button state based on validation
if self.check_setting_changes():
self.save_config_button.config(state='normal')
else:
self.save_config_button.config(state='disabled')
def check_setting_changes(self):
# Checks for changes in settings compared to the current configuration
current_config = self.root.config_handler.config_values
language_selection = self.language_combobox.get().strip()
# Find the corresponding ISO code (e.g., "es") for the selected display name
selected_language_code = None
for code, name in self.root.translation_engine.language_map.items():
if name == language_selection:
selected_language_code = code
break
# Compare the selected ISO code with the one stored in the config
language_changed = (selected_language_code != current_config.get('language'))
if not self.root.disable_exchange_rate_features:
currency_code = self.currency_code_combobox.get().strip()
currency_code_changed = (currency_code != current_config.get('default_currency'))
node_address = self.denaro_node_address_entry.get().strip()
node_port = self.denaro_node_port_entry.get().strip()
# Construct the address:port string conditionally including the port
node = f"{node_address}:{node_port}" if node_port else node_address
node_changed = (node != current_config.get('default_node', ''))
node_validation = not self.disable_node_validation_var.get()
node_validation_changed = (str(node_validation) != current_config.get('node_validation', ''))
# Check translation module changes
current_translation_module = current_config.get('translation_module')
if self.argostranslate_checkbox.get():
new_translation_module = 'argostranslate'
elif self.deep_translator_checkbox.get():
new_translation_module = 'deep-translator'
else:
# Both are unchecked - translation is disabled
new_translation_module = None
# Check if translation module changed
if new_translation_module is None:
# Translation is disabled - check if it was previously enabled
translation_module_changed = (current_translation_module is not None and current_translation_module != '')
else:
# Translation is enabled - check if it changed
translation_module_changed = (current_translation_module != new_translation_module)
# --- UPDATED: Final check for enabling save button ---
if self.root.disable_exchange_rate_features:
# Check for changes and ensure language is valid
settings_changed = self.language_valid and (node_changed or node_validation_changed or language_changed or translation_module_changed) and not self.keep_save_button_disabled
else:
# Check for changes and ensure BOTH currency and language are valid
settings_changed = (self.currency_code_valid and self.language_valid) and \
(currency_code_changed or node_changed or node_validation_changed or language_changed or translation_module_changed) and \
not self.keep_save_button_disabled
# --------------------------------------------------------
return settings_changed
class BlankPage(BasePage):
def __init__(self, parent, root):
super().__init__(parent, root)
ttk.Label(self, text="TBA").pack(expand=True)
class DenaroWalletGUI(tk.Tk):
def __init__(self):
super().__init__()
self.config_handler = ConfigHandler(self)
self.language = self.config_handler.config_values.get('language', 'en')
translation_module = self.config_handler.config_values.get('translation_module', 'deep-translator')
self.translation_engine = universal_language_translator.activate_tkinter_translation(target_language=self.language, translation_module=translation_module, sensitive_patterns=sensitive_patterns, non_translatable_patterns=non_translatable_patterns)
self.wallet_client_version = f"{wallet_client.wallet_client_version} GUI"
self.title(self.wallet_client_version)
self.geometry("1024x576")
self.minsize(780, 390)
icon = tk.PhotoImage(file="./denaro/gui_assets/denaro_logo.png")
self.iconphoto(True, icon)
self.pages = {}
self.sidebar_buttons = {}
self.current_page = None
self.selectable_widgets = []
self.active_button = None
self.disable_exchange_rate_features = True
self.styles = tb.Style()
self.stored_data = StoredData()
self.gui_utils = GUIUtils(self)
self.wallet_thread_manager = WalletThreadManager(self)
atexit.register(self.wallet_thread_manager.stop_all_threads)
self.wallet_operations = WalletOperations(self)
self.dialogs = Dialogs(self)
self.custom_popup = CustomPopup(self)
self.menu_items = {}
self.create_menus()
self.configure_styles()
self.create_main_content_area()
self.create_sidebar()
self.create_status_bar()