-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.py
More file actions
4804 lines (4071 loc) · 219 KB
/
Copy pathgui.py
File metadata and controls
4804 lines (4071 loc) · 219 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
"""
GUI for DigiCal Business Calculator
Tkinter-based interface optimized for Raspberry Pi display
"""
import tkinter as tk
from tkinter import ttk, messagebox, simpledialog
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from datetime import datetime
import json
import os
import subprocess
import platform
import threading
import config
import locales
from PIL import Image, ImageTk, ImageOps
from calculator import Calculator
from database import Database
from transaction_manager import TransactionManager
from history_manager import HistoryManager
from graph_generator import GraphGenerator
from handler_manager import HandlerManager
from updater import Updater
class SystemPanel:
"""Displays system status icons (Battery, Wifi) in the header."""
def __init__(self, parent, theme, is_dark=False):
self.parent = parent
self.T = theme
self.is_dark = is_dark
self.frame = tk.Frame(parent, bg=self.T["hdr_bg"])
self.frame.pack(side=tk.RIGHT, padx=5)
# Icons (Battery, Wifi from right to left)
self.battery_label = tk.Label(self.frame, bg=self.T["hdr_bg"])
self.battery_label.pack(side=tk.RIGHT, padx=2)
self.wifi_label = tk.Label(self.frame, bg=self.T["hdr_bg"])
self.wifi_label.pack(side=tk.RIGHT, padx=2)
self.time_label = tk.Label(self.frame, font=(config.LABEL_FONT[0], max(8, config.LABEL_FONT[1] - 2), "bold"),
bg=self.T["hdr_bg"], fg=self.T["text"])
self.time_label.pack(side=tk.RIGHT, padx=(2, 5))
self.memory_label = tk.Label(self.frame, bg=self.T["hdr_bg"])
self.memory_label.pack(side=tk.RIGHT, padx=4)
self.shift_label = tk.Label(self.frame, bg=self.T["hdr_bg"])
self.shift_label.pack(side=tk.RIGHT, padx=4)
self.icons = {}
self._load_icons()
# Set initial default icons for instant startup
self.battery_label.config(image=self.icons.get("bat100"))
self.wifi_label.config(image=self.icons.get("wifi_off"))
self.time_label.config(text=datetime.now().strftime("%I:%M %p •"))
self.shift_label.config(image="")
self.memory_label.config(image="")
self.refresh()
def show_shift(self):
if "shift" in self.icons:
self.shift_label.config(image=self.icons["shift"])
def hide_shift(self):
self.shift_label.config(image="")
def show_memory(self):
if "memory" in self.icons:
self.memory_label.config(image=self.icons["memory"])
def hide_memory(self):
self.memory_label.config(image="")
def _load_icons(self):
try:
base_dir = os.path.dirname(__file__)
header_assets = os.path.join(base_dir, "assets", "header")
_resample = getattr(Image, 'Resampling', Image).LANCZOS
sz = max(16, int(config.LABEL_FONT[1] * 1.6))
size = (sz, sz)
icon_files = {
"wifi_on": "wifi_on.png", "wifi_off": "wifi_off.png",
"bat0": "battery0.png", "bat10": "battery10.png",
"bat50": "battery50.png", "bat90": "battery90.png", "bat100": "battery100.png",
"shift": "shiftkey.png",
"memory": "memory.png"
}
for key, filename in icon_files.items():
path = os.path.join(header_assets, filename)
if os.path.exists(path):
img = Image.open(path).convert("RGBA").resize(size, _resample)
# Force color to white (in dark mode) or black (in light mode) while preserving alpha
r, g, b, a = img.split()
target_color = 255 if self.is_dark else 0
solid = Image.new('L', img.size, target_color)
img = Image.merge("RGBA", (solid, solid, solid, a))
self.icons[key] = ImageTk.PhotoImage(img)
except Exception as e:
print(f"Error loading system icons: {e}")
def refresh(self):
"""Begin an asynchronous status update."""
if not self.frame.winfo_exists():
return
threading.Thread(target=self._fetch_status, daemon=True).start()
self.frame.after(10000, self.refresh) # Refresh every 10 seconds
def _fetch_status(self):
"""Detect system info across platforms."""
is_win = platform.system() == "Windows"
# 1. Battery
bat_key = "bat100"
try:
if is_win:
out = subprocess.check_output("wmic path win32_battery get estimatedchargeremaining /value", shell=True, text=True)
res = [l.split('=')[1] for l in out.splitlines() if '=' in l]
pct = int(res[0]) if res else 100
else:
with open("/sys/class/power_supply/BAT0/capacity", "r") as f:
pct = int(f.read().strip())
if pct <= 5: bat_key = "bat0"
elif pct <= 25: bat_key = "bat10"
elif pct <= 60: bat_key = "bat50"
elif pct <= 95: bat_key = "bat90"
else: bat_key = "bat100"
except: bat_key = "bat100"
# 2. Wifi
wifi_key = "wifi_off"
try:
if is_win:
out = subprocess.check_output("netsh interface show interface name=\"Wi-Fi\"", shell=True, text=True)
if "Connect state: Connected" in out:
wifi_key = "wifi_on"
else:
# Use 'general status' for better compatibility with older NetworkManager versions
try:
res = subprocess.check_output(["nmcli", "-t", "-f", "STATE", "general"], text=True).strip().lower()
# Check for connected state (includes 'connected' and 'connected (local only)')
if res.startswith("connected"): wifi_key = "wifi_on"
except:
# Fallback for even older systems or if nmcli is missing 'general'
res = subprocess.check_output("hostname -I", shell=True, text=True).strip()
if res: wifi_key = "wifi_on"
except: pass
# Update UI in main thread
now_time = datetime.now().strftime("%I:%M %p •")
self.frame.after(0, lambda: self._apply_icons(bat_key, wifi_key, now_time))
def _apply_icons(self, bat, wifi, time_str):
if not self.frame.winfo_exists():
return
if bat in self.icons: self.battery_label.config(image=self.icons[bat])
if wifi in self.icons: self.wifi_label.config(image=self.icons[wifi])
self.time_label.config(text=time_str)
class DigiCalGUI:
def __init__(self, root):
self.root = root
self.root.title(config.APP_NAME)
self.root.geometry(f"{config.WINDOW_WIDTH}x{config.WINDOW_HEIGHT}")
# Global auto-icursor positioning for keypad navigability
def _set_icursor_end(e):
try: e.widget.icursor(tk.END)
except Exception: pass
if e.widget.winfo_class() == "TCombobox":
self._last_combobox = e.widget
self.root.bind_class("Entry", "<FocusIn>", _set_icursor_end)
self.root.bind_class("TCombobox", "<FocusIn>", _set_icursor_end)
# Initialize components
self.db = Database()
self.calculator = Calculator()
self.transaction_manager = TransactionManager(self.db)
self.history_manager = HistoryManager(self.db)
self.graph_generator = GraphGenerator(self.transaction_manager)
self.handler_manager = HandlerManager(self.db)
# ── Theme state (load before any widget is created) ───────────────
settings = self._load_settings()
self.dark_mode: bool = settings.get("dark_mode", False)
self.language = settings.get("language", "en")
# Fullscreen initialization
self.fullscreen: bool = settings.get("fullscreen", False)
if self.fullscreen:
self.root.attributes("-fullscreen", True)
# Bind F11 for convenience
self.root.bind("<F11>", lambda e: self._toggle_fullscreen(not self.fullscreen))
# Pull font scale early and update global config tuples
self.font_scale = settings.get("font_scale", "Medium")
config.set_font_scale(self.font_scale)
self.current_gst_rate = settings.get("gst_rate", 18)
self.tr = locales.get_translator(self.language)
self.T: dict = config.get_theme(self.dark_mode)
self._apply_ttk_styles()
self.root.configure(bg=self.T["bg"])
# Hide mouse cursor if setting is enabled
self.hide_cursor: bool = settings.get("hide_cursor", False)
# Current mode
self.current_mode = "calculator"
self.current_graph_info = None # (func_name, args, kwargs)
self._f1_memory_value = None
# ── Keypad state ──────────────────────────────────────────────────
# These are set/cleared by show_transaction_dialog so the keypad
# dispatcher can trigger payment cycling and Sale/Expense buttons.
self._active_payment_var = None # tk.StringVar of current dialog
self._active_payment_combo = None # ttk.Combobox widget
self._active_payment_change_fn = None # on_payment_change callback
self._active_save_sale_fn = None # save_as_sale callable
self._active_save_expense_fn = None # save_as_expense callable
self._active_dialog_close_fn = None # close callable
self._transaction_dialog_open = False # True while dialog is visible
self._t9_last_key = None
self._t9_last_time = 0.0
self._t9_index = 0
# ── Navigation history (Back key) ─────────────────────────────────
# Tracks the sequence of modes visited so the Back key can reverse them.
self._nav_stack = [] # list of mode strings e.g. ['calculator', 'sales']
self._nav_back_in_progress = False # guard: don't push while popping
# Create UI
self.create_widgets()
self.switch_mode("calculator")
# Enable app to take standard keyboard input
self.root.bind("<Key>", self._on_keyboard_input)
# Apply global cursor settings robustly
self._apply_global_cursor()
# ── Settings persistence ─────────────────────────────────────────────
_SETTINGS_FILE = "settings.json"
def _load_settings(self):
try:
with open(self._SETTINGS_FILE, "r") as f:
return json.load(f)
except Exception:
return {}
def _save_settings(self, data):
existing = self._load_settings()
existing.update(data)
try:
with open(self._SETTINGS_FILE, "w") as f:
json.dump(existing, f, indent=2)
except Exception:
pass
def _toggle_fullscreen(self, value: bool):
"""Toggle fullscreen state and save to settings."""
self.fullscreen = value
self.root.attributes("-fullscreen", self.fullscreen)
self._save_settings({"fullscreen": self.fullscreen})
self.apply_theme()
# ── Theme helpers ──────────────────────────────────────────────────────────
def _apply_ttk_styles(self):
"""Configure ttk widget styles for the active neumorphic palette."""
self.root.option_add("*highlightColor", "red")
T = self.T
style = ttk.Style()
try:
style.theme_use("clam")
except Exception:
pass
style.configure("TNotebook", background=T["bg"], borderwidth=0)
style.configure("TNotebook.Tab", background=T["bg_dark"], foreground=T["text"],
padding=[8, 3], font=config.LABEL_FONT)
style.map("TNotebook.Tab",
background=[("selected", T["bg"]), ("active", T["shadow_lite"])],
foreground=[("selected", T["accent"])])
style.configure("TCombobox", fieldbackground=T["entry_bg"],
background=T["bg_dark"], foreground=T["entry_fg"],
selectbackground=T["accent"], selectforeground="#FFFFFF",
arrowcolor=T["accent"])
style.map("TCombobox",
fieldbackground=[("focus", T["accent"]), ("readonly", T["entry_bg"])],
foreground=[("focus", T["bg"]), ("readonly", T["entry_fg"])])
# Scale the dropdown listbox popout explicitly
self.root.option_add("*TCombobox*Listbox.font", config.LABEL_FONT)
self.root.option_add("*TCombobox*Listbox.background", T["entry_bg"])
self.root.option_add("*TCombobox*Listbox.foreground", T["entry_fg"])
style.configure("Treeview", background=T["tree_even"],
fieldbackground=T["tree_even"], foreground=T["tree_fg"],
rowheight=int(config.LABEL_FONT[1] * 2.2), font=config.LABEL_FONT)
style.configure("Treeview.Heading", background=T["hdr_bg"],
foreground=T["accent"],
font=(config.LABEL_FONT[0], config.LABEL_FONT[1], "bold"))
style.map("Treeview",
background=[("selected", T["accent"])],
foreground=[("selected", "#FFFFFF")])
style.configure("Vertical.TScrollbar",
background=T["subtext"], troughcolor=T["display_bg"],
borderwidth=0, relief="flat", width=14, arrowsize=0)
style.map("Vertical.TScrollbar",
background=[("active", T["accent"]), ("pressed", T["accent"]),
("!disabled", T["subtext"])],
troughcolor=[("!disabled", T["display_bg"])])
def apply_theme(self):
"""Refresh T, re-style ttk, then destroy+rebuild all widgets."""
self.tr = locales.get_translator(self.language)
self.T = config.get_theme(self.dark_mode)
self._apply_ttk_styles()
self.root.configure(bg=self.T["bg"])
# Destroy everything and rebuild cleanly
for w in self.root.winfo_children():
w.destroy()
self.create_widgets()
self.switch_mode(self.current_mode)
# Re-apply cursor setting after rebuild
if getattr(self, 'hide_cursor', False):
self.root.config(cursor="none")
def _toggle_dark_mode(self, val: bool):
"""Persist dark_mode setting and apply theme immediately."""
self.dark_mode = val
self._save_settings({"dark_mode": val})
self.apply_theme()
def _change_language(self, lang_code: str):
"""Persist language setting and apply immediately."""
self.language = lang_code
self._save_settings({"language": lang_code})
self.apply_theme()
def _change_font_scale(self, scale_name: str):
"""Persist scaled font tuple configuration"""
self.font_scale = scale_name
self._save_settings({"font_scale": scale_name})
config.set_font_scale(scale_name)
self.apply_theme()
def _bind_mousewheel(self, widget, callback):
"""Cross-platform mouse-wheel binding"""
widget.bind_all("<MouseWheel>", callback)
widget.bind_all("<Button-4>", callback)
widget.bind_all("<Button-5>", callback)
def _unbind_mousewheel(self, widget):
"""Cross-platform mouse-wheel unbinding"""
widget.unbind_all("<MouseWheel>")
widget.unbind_all("<Button-4>")
widget.unbind_all("<Button-5>")
def _handle_mousewheel(self, event, canvas, orient="vertical"):
"""Unified scroll handler for Windows/Linux/macOS"""
if event.num == 4: # Linux Scroll Up
delta = 1
elif event.num == 5: # Linux Scroll Down
delta = -1
else: # Windows/macOS event.delta
delta = event.delta / 120
if orient == "vertical":
canvas.yview_scroll(int(-1 * delta), "units")
else:
canvas.xview_scroll(int(-1 * delta), "units")
def _neu_btn(self, parent, text, command=None, kind="normal", **kw):
"""Create a neumorphic styled flat button."""
T = self.T
if kind == "equals":
bg, fg, abg = T["equals_bg"], T["equals_fg"], T["success"]
elif kind == "operator":
bg, fg, abg = T["btn_bg"], T["operator_fg"], T["bg_dark"]
elif kind == "mode":
bg, fg, abg = T["mode_bg"], T["mode_fg"], T["shadow_dark"]
elif kind == "danger":
bg, fg, abg = T["danger"], "#FFFFFF", T["bg_dark"]
else:
bg, fg, abg = T["btn_bg"], T["btn_fg"], T["bg_dark"]
return tk.Button(
parent, text=text, command=command,
font=kw.pop("font", config.BUTTON_FONT),
bg=bg, fg=fg,
activebackground=abg, activeforeground=fg,
relief=tk.FLAT, bd=0, cursor="hand2",
highlightthickness=3,
highlightbackground=T["shadow_dark"],
highlightcolor="red",
**kw
)
# ── Inline toast / confirm (replaces messagebox popups) ──────────────
def _show_toast(self, msg, kind="success", duration=2500):
"""Show an inline toast banner at the top of the window.
kind: 'success' | 'error' | 'warning' | 'info'
"""
T = self.T
colours = {
"success": (T["success"], "#FFFFFF"),
"error": (T["danger"], "#FFFFFF"),
"warning": (T["warning"], "#FFFFFF"),
"info": (T["mode_fg"], "#FFFFFF"),
}
icons = {"warning": "\u26a0", "info": "\u2139"}
bg, fg = colours.get(kind, colours["info"])
toast = tk.Frame(self.root, bg=bg)
toast.place(relx=0.05, y=55, relwidth=0.9, height=42)
toast.lift()
lbl = tk.Label(toast, text=f" {icons.get(kind, '')} {msg}" if kind in icons else f" {msg}",
font=(config.BUTTON_FONT[0], 8, "bold"),
bg=bg, fg=fg, anchor="w")
if kind == "success" and getattr(self, "_icon_success", None):
lbl.config(image=self._icon_success, compound=tk.LEFT, padx=5)
elif kind == "error" and getattr(self, "_icon_error", None):
lbl.config(image=self._icon_error, compound=tk.LEFT, padx=5)
elif kind == "success":
lbl.config(text=f" \u2713 {msg}")
elif kind == "error":
lbl.config(text=f" \u2717 {msg}")
lbl.pack(side=tk.LEFT, fill=tk.X, expand=True)
tk.Button(toast, text="\u2715", font=(config.BUTTON_FONT[0], 8),
bg=bg, fg=fg, relief=tk.FLAT, bd=0,
command=toast.destroy, cursor="hand2",
activebackground=bg).pack(side=tk.RIGHT, padx=4)
self.root.after(duration, lambda: toast.destroy() if toast.winfo_exists() else None)
def _show_confirm(self, msg, on_yes, on_no=None):
"""Show a full-window confirmation prompt."""
T = self.T
ov, body, close_cb = self._open_overlay(self.tr("Confirm Action"))
# Center content frame
content = tk.Frame(body, bg=T["bg"])
content.pack(expand=True)
# Warning icon/text
tk.Label(content, text="\u26a0", font=(config.BUTTON_FONT[0], 48), bg=T["bg"], fg=T["warning"]).pack(pady=(0, 10))
tk.Label(content, text=msg, font=(config.BUTTON_FONT[0], 16, "bold"), bg=T["bg"], fg=T["text"]).pack(pady=(0, 20))
btn_frame = tk.Frame(content, bg=T["bg"])
btn_frame.pack()
def _yes():
close_cb()
on_yes()
def _no():
close_cb()
if on_no:
on_no()
no_btn = self._neu_btn(btn_frame, "No", command=_no, kind="mode", width=12, height=2)
no_btn.pack(side=tk.LEFT, padx=10)
yes_btn = self._neu_btn(btn_frame, "Yes", command=_yes, kind="danger", width=12, height=2)
yes_btn.pack(side=tk.LEFT, padx=10)
# Setup dialog tracking for keypad
self._confirm_dialog_open = True
self._confirm_widgets = [no_btn, yes_btn]
def _on_destroy(e):
if e.widget == ov:
self._confirm_dialog_open = False
ov.bind("<Destroy>", _on_destroy, add="+")
# Auto-focus the 'No' button initially for safety
self.root.after(100, lambda: no_btn.focus_set())
def create_widgets(self):
"""Create main UI components"""
T = self.T
# Top bar
self.top_frame = tk.Frame(self.root, bg=T["hdr_bg"], height=50)
self.top_frame.pack(fill=tk.X, padx=2, pady=2)
# Left: Apps launcher button
try:
base_dir = os.path.dirname(__file__)
_app_img_path = os.path.join(base_dir, "assets", "apps.png")
_resample = getattr(Image, 'Resampling', Image).LANCZOS
app_sz = max(16, int(config.LABEL_FONT[1] * 1.6))
icon_sz = max(12, int(config.LABEL_FONT[1] * 1.25))
_raw_img = Image.open(_app_img_path).resize((app_sz, app_sz), _resample)
self._apps_icon = ImageTk.PhotoImage(_raw_img)
self._icon_success = ImageTk.PhotoImage(Image.open(os.path.join(base_dir, "assets", "right.png")).resize((icon_sz, icon_sz), _resample))
self._icon_error = ImageTk.PhotoImage(Image.open(os.path.join(base_dir, "assets", "wrong.png")).resize((icon_sz, icon_sz), _resample))
except Exception:
self._apps_icon = None
self._icon_success = None
self._icon_error = None
tk.Button(
self.top_frame, text=" " + self.tr("Apps"), image=self._apps_icon, compound=tk.LEFT if self._apps_icon else tk.NONE,
font=(config.LABEL_FONT[0], config.LABEL_FONT[1], "bold"),
bg=T["mode_bg"], fg=T["mode_fg"],
relief=tk.FLAT, bd=0, cursor="hand2",
activebackground=T["shadow_dark"],
highlightthickness=3, highlightbackground=T["shadow_dark"],
command=self._show_app_launcher
).pack(side=tk.LEFT, padx=(4, 2))
# Center: app title (absolutely centered, shifted left slightly for visual weight of 'g')
title_size = max(16, config.BUTTON_FONT[1] + 4)
title_label = tk.Label(
self.top_frame, text=self.tr("DigiCal"),
font=(config.BUTTON_FONT[0], title_size, "bold"),
bg=T["hdr_bg"], fg=T["accent"]
)
title_label.place(relx=0.49, rely=0.45, anchor=tk.CENTER)
# Right: System Panel (Wifi, Bluetooth, Battery)
self.system_panel = SystemPanel(self.top_frame, self.T, is_dark=self.dark_mode)
# Product quick-pick bar
self.product_bar_frame = tk.Frame(self.root, bg=T["bg_dark"], height=36)
self.product_bar_frame.pack(fill=tk.X, padx=2)
self.product_bar_frame.pack_propagate(False)
tk.Button(self.product_bar_frame, text="\u27f3",
font=(config.BUTTON_FONT[0], 10, "bold"),
bg=T["bg_dark"], fg=T["accent"],
relief=tk.FLAT, bd=0, cursor="hand2",
activebackground=T["shadow_dark"],
command=self.refresh_product_bar).pack(side=tk.RIGHT, padx=(2, 4))
self._product_bar_var = tk.StringVar()
self._product_bar_cb = ttk.Combobox(
self.product_bar_frame, textvariable=self._product_bar_var,
font=(config.LABEL_FONT[0], 7), state="readonly"
)
self._product_bar_cb.pack(side=tk.LEFT, padx=2, pady=2, expand=True, fill=tk.X)
self._product_bar_cb.bind("<<ComboboxSelected>>", self._product_bar_select)
self.refresh_product_bar()
# Display area — neumorphic inset card with LCD-style font
outer = tk.Frame(self.root, bg=T["shadow_dark"], bd=0)
outer.pack(fill=tk.BOTH, expand=True, padx=6, pady=(4, 6))
self.outer_display_frame = outer
inner = tk.Frame(outer, bg=T["shadow_lite"], bd=0)
inner.pack(fill=tk.BOTH, expand=True, padx=(1, 0), pady=(1, 0))
self.display_frame = tk.Frame(inner, bg=T["display_bg"], height=140)
self.display_frame.pack(fill=tk.BOTH, expand=True, padx=(0, 1), pady=(0, 1))
self.display_frame.pack_propagate(False)
self.display = tk.Label(
self.display_frame, text="0",
font=("Consolas", 36, "bold"),
bg=T["display_bg"], fg=T["display_fg"],
anchor=tk.E, padx=12, pady=2
)
self.display.pack(side=tk.TOP, fill=tk.X)
# Container for live calculation (right) and handler name (left)
self.live_info_frame = tk.Frame(self.display_frame, bg=T["display_bg"])
self.live_info_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=12, pady=0)
self.handler_status_label = tk.Label(
self.live_info_frame, text="H: None",
font=("Consolas", 14, "bold"),
bg=T["display_bg"], fg=T["subtext"]
)
self.handler_status_label.pack(side=tk.LEFT)
self.live_display = tk.Label(
self.live_info_frame, text="",
font=("Consolas", 20, "bold"),
bg=T["display_bg"], fg=T["subtext"],
anchor=tk.E
)
self.live_display.pack(side=tk.RIGHT, fill=tk.X, expand=True)
self.update_handler_status()
# Content area
self.content_frame = tk.Frame(self.root, bg=T["bg"])
self.content_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=3)
def clear_content_frame(self):
"""Clear the content frame"""
for widget in self.content_frame.winfo_children():
widget.destroy()
def switch_mode(self, mode):
"""Switch between different modes.
Pushes the current mode onto the nav stack before switching so the
Back key can retrace the navigation path.
"""
# Record where we came from (unless this is a Back-navigation or same mode)
if not getattr(self, '_nav_back_in_progress', False):
prev = getattr(self, 'current_mode', None)
if prev and prev != mode:
stack = getattr(self, '_nav_stack', [])
stack.append(prev)
self._nav_stack = stack
self.current_mode = mode
self.clear_content_frame()
if mode == "calculator":
# CRITICAL: hide content_frame FIRST so it releases its expand=True claim
# before outer_display_frame re-takes the full window. Wrong order = tiny display.
self.content_frame.pack_forget()
self.product_bar_frame.pack(fill=tk.X, padx=2, before=self.outer_display_frame)
# Restore product bar combobox key bindings for home mode
if hasattr(self, '_product_bar_cb'):
self._product_bar_cb.unbind('<Down>')
self._product_bar_cb.unbind('<Up>')
# Now safely expand outer_display_frame to fill the whole window
self.outer_display_frame.pack(fill=tk.BOTH, expand=True, padx=6, pady=(4, 0))
self.display_frame.pack_propagate(True) # allow expansion
self.display_frame.config(height=0)
self.display.config(font=("Consolas", 36, "bold"), anchor=tk.E, pady=10)
self.live_display.config(font=("Consolas", 24, "bold"), pady=6)
# Force a geometry pass so Tkinter recalculates sizes immediately
self.root.update_idletasks()
else:
# Block the product bar combobox from opening its dropdown in non-home modes
if hasattr(self, '_product_bar_cb'):
self._product_bar_cb.bind('<Down>', lambda e: "break")
self._product_bar_cb.bind('<Up>', lambda e: "break")
self.product_bar_frame.pack_forget()
self.outer_display_frame.pack(fill=tk.X, expand=False, padx=6, pady=(4, 2))
self.display_frame.config(height=80) # Fixed height for modes like Sales
self.display_frame.pack_propagate(False)
self.display.config(font=("Consolas", 24, "bold"), anchor=tk.CENTER, pady=2)
self.live_display.config(font=("Consolas", 14, "bold"), pady=0)
# Hide calculator-only widgets if they exist
for attr in ('_calc_sep1', '_calc_sep2', 'receipt_frame'):
w = getattr(self, attr, None)
if w and w.winfo_exists():
w.pack_forget()
# Restore live_info_frame packing
self.live_info_frame.pack_forget()
self.live_info_frame.pack(side=tk.BOTTOM, fill=tk.X, padx=12)
self.content_frame.pack(fill=tk.BOTH, expand=True, padx=5, pady=3)
# ESC on any non-home mode returns to Calculator
self.root.bind("<Escape>", lambda e: self.switch_mode("calculator"))
if mode == "calculator":
self.show_calculator_mode()
elif mode == "sales":
self.show_sales_mode()
elif mode == "expense":
self.show_expense_mode()
elif mode == "history":
self.show_history_mode()
elif mode == "graphs":
self.show_graphs_mode()
elif mode == "customers":
self.show_customers_mode()
elif mode == "products":
self.show_products_mode()
elif mode == "handlers":
self.show_handlers_mode()
elif mode == "settings":
self.show_settings_mode()
elif mode == "tester":
self.show_tester_mode()
def show_calculator_mode(self):
"""Show calculator home: top=expression, middle=item list, bottom=live total"""
T = self.T
# Clean up any leftover calculator widgets from a previous call
for attr in ('_calc_sep1', '_calc_sep2', 'receipt_frame'):
w = getattr(self, attr, None)
if w and w.winfo_exists():
w.destroy()
# --- Separator 1 (below expression) ---
self._calc_sep1 = tk.Frame(self.display_frame, bg=T["accent"], height=1)
self._calc_sep1.pack(side=tk.TOP, fill=tk.X, padx=6)
# --- MIDDLE: scrollable receipt list ---
self.receipt_frame = tk.Frame(self.display_frame, bg=T["display_bg"])
self.receipt_frame.pack(side=tk.TOP, fill=tk.BOTH, expand=True, padx=12, pady=2)
# Repack live_display at BOTTOM first, then separator above it
self.live_display.pack_forget()
self.live_display.pack(side=tk.BOTTOM, fill=tk.X)
# --- Separator 2 (above live total) ---
self._calc_sep2 = tk.Frame(self.display_frame, bg=T["accent"], height=2)
self._calc_sep2.pack(side=tk.BOTTOM, fill=tk.X, padx=0)
self.update_display(self.calculator.get_expression())
# On the home screen ESC opens the App Launcher
self.root.bind("<Escape>", lambda e: self._show_app_launcher())
# Reset line products if not set
if not hasattr(self, '_line_products'):
self._line_products = {}
def _on_keyboard_input(self, event):
"""Map standard PC keyboard events globally for text, numbers and enter."""
# Allow native behavior for entries and dropdowns
try:
focused = self.root.focus_get()
if focused and focused.winfo_class() in ("Entry", "Text", "TCombobox"):
return
except KeyError:
return
if self.current_mode == "calculator":
char = event.char
keysym = event.keysym
if keysym in ("Return", "KP_Enter"):
self.calculator_button_click("=")
return "break"
if keysym in ("BackSpace", "Delete"):
self.calculator_button_click("CE")
return "break"
if char in "0123456789.":
self.calculator_button_click(char)
return "break"
op_map = {"*": "×", "x": "×", "X": "×", "/": "÷", "+": "+", "-": "-"}
if char in op_map:
self.calculator_button_click(op_map[char])
return "break"
if char == "%":
self.calculator_button_click("%")
return "break"
def calculator_button_click(self, button):
"""Handle calculator button clicks"""
if button in '0123456789.':
# If starting a fresh expression, clear leftover product names
if self.calculator.get_expression() in ("0", ""):
self._line_products = {}
self.calculator.add_digit(button)
self.update_display(self.calculator.get_expression())
elif button in '+-×÷':
self.calculator.add_operator(button)
self.update_display(self.calculator.get_expression())
elif button == '=':
expression = self.calculator.get_expression()
result = self.calculator.evaluate()
self.update_display(result)
if not result.startswith("Error"):
# Calculate handler incentive
handler = self.handler_manager.get_current_handler()
handler_id = handler['id'] if handler else None
handler_incentive = self.handler_manager.calculate_incentive(result)
# Save calculation with handler info
self.db.add_calculation(expression, result, handler_id, handler_incentive)
# Show transaction categorization dialog
self.show_transaction_dialog(result)
elif button == 'C':
self.calculator.clear()
self._line_products = {}
self.update_display("0")
elif button == 'CE':
self.calculator.clear_entry()
self.update_display(self.calculator.get_expression())
elif button == '%':
self.calculator.add_digit('%')
self.update_display(self.calculator.get_expression())
elif button == 'MC':
self.calculator.clear_memory()
self._show_toast(self.tr("Memory cleared"))
elif button == 'MR':
self.show_gst_rate_dialog()
elif button == 'M+':
try:
expr = self.calculator.get_expression()
if expr == "0" or not expr or "Error" in expr: return
if hasattr(self, '_line_products'):
for k, v in self._line_products.items():
if isinstance(v, dict) and v.get("gst", 0) > 0:
self._show_toast(self.tr("GST is already included in product"), kind="error")
return
live_val = self._evaluate_live(expr)
if live_val is None or "Error" in live_val: return
value = float(live_val)
rate = getattr(self, 'current_gst_rate', 18)
tax_amount = value * (rate / 100)
tax_str = f"{tax_amount:.2f}".rstrip('0').rstrip('.')
if tax_str == "": tax_str = "0"
if expr[-1] in "+-×÷":
self.calculator.clear_entry()
expr = self.calculator.get_expression()
lines_before = len(self._parse_expression_to_receipt(expr))
self.calculator.add_operator('+')
for digit in tax_str:
self.calculator.add_digit(digit)
if not hasattr(self, '_line_products'):
self._line_products = {}
self._line_products[lines_before] = f"GST ({rate:g}%)"
self.update_display(self.calculator.get_expression())
self._show_toast(self.tr("Added {}% GST").format(rate))
except Exception:
pass
elif button == 'M-':
try:
expr = self.calculator.get_expression()
if expr == "0" or not expr or "Error" in expr: return
rate = None
if hasattr(self, '_line_products'):
for k, v in self._line_products.items():
if isinstance(v, dict) and v.get("gst", 0) > 0:
rate = v.get("gst", 0)
break
if rate is None:
self._show_toast(self.tr("No pre-applied GST to subtract"), kind="warning")
return
live_val = self._evaluate_live(expr)
if live_val is None or "Error" in live_val: return
value = float(live_val)
base_value = value / (1 + (rate / 100))
tax_amount = value - base_value
tax_str = f"{tax_amount:.2f}".rstrip('0').rstrip('.')
if tax_str == "": tax_str = "0"
if expr[-1] in "+-×÷":
self.calculator.clear_entry()
expr = self.calculator.get_expression()
lines_before = len(self._parse_expression_to_receipt(expr))
self.calculator.add_operator('-')
for digit in tax_str:
self.calculator.add_digit(digit)
if not hasattr(self, '_line_products'):
self._line_products = {}
self._line_products[lines_before] = f"-GST Base ({rate:g}%)"
self.update_display(self.calculator.get_expression())
self._show_toast(self.tr("Subtracted {}% GST").format(rate))
except Exception:
pass
def show_sales_mode(self):
"""Show sales entry interface"""
T = self.T
self.update_display(self.tr("Add Sales Transaction"))
form_frame = tk.Frame(self.content_frame, bg=T["bg"])
form_frame.pack(pady=5)
tk.Label(form_frame, text=self.tr("Amount:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=0, column=0, sticky=tk.W, pady=5)
amount_entry = tk.Entry(form_frame, font=config.LABEL_FONT, width=20,
bg=T["entry_bg"], fg=T["entry_fg"],
insertbackground=T["text"], relief=tk.FLAT,
highlightthickness=3, highlightbackground=T["shadow_dark"])
amount_entry.grid(row=0, column=1, pady=5, padx=10)
amount_entry.t9_mode = "num"
tk.Label(form_frame, text=self.tr("Category:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=1, column=0, sticky=tk.W, pady=5)
category_var = tk.StringVar()
categories = self.transaction_manager.get_sales_categories()
category_combo = ttk.Combobox(form_frame, textvariable=category_var,
values=categories, font=config.LABEL_FONT, width=18)
category_combo.grid(row=1, column=1, pady=5, padx=10)
if "Product Sales" in categories:
category_var.set("Product Sales")
elif categories:
category_combo.current(0)
tk.Label(form_frame, text=self.tr("Description:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=2, column=0, sticky=tk.W, pady=5)
desc_entry = tk.Entry(form_frame, font=config.LABEL_FONT, width=20,
bg=T["entry_bg"], fg=T["entry_fg"],
insertbackground=T["text"], relief=tk.FLAT,
highlightthickness=3, highlightbackground=T["shadow_dark"])
desc_entry.grid(row=2, column=1, pady=5, padx=10)
desc_entry.t9_mode = "alpha"
tk.Label(form_frame, text=self.tr("Payment:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=3, column=0, sticky=tk.W, pady=5)
payment_var = tk.StringVar(value="Cash")
payment_combo = ttk.Combobox(form_frame, textvariable=payment_var,
values=config.PAYMENT_METHODS, font=config.LABEL_FONT,
width=18, state="readonly")
payment_combo.grid(row=3, column=1, pady=5, padx=10)
due_customer = [None]
def on_payment_change(event=None):
if payment_var.get() == "Due":
def on_customer_confirmed(cid):
due_customer[0] = cid
self.show_due_customer_dialog(on_customer_confirmed)
else:
due_customer[0] = None
payment_combo.bind('<<ComboboxSelected>>', on_payment_change)
def add_sale():
try:
amount = float(amount_entry.get())
category = category_var.get()
description = desc_entry.get()
if not category:
self._show_toast(self.tr("Please select a category"), kind="error")
return
payment_method = payment_var.get()
if payment_method == "Due":
if not due_customer[0]:
self._show_toast(self.tr("Please select a customer for Due payment"), kind="error")
return
description = f"{description} [Due: {due_customer[0]}]".strip()
handler_id = None
current_handler = self.handler_manager.get_current_handler()
if current_handler:
handler_id = current_handler['id']
trans_id = self.transaction_manager.add_sale(amount, category, description, payment_method, handler_id)
if payment_method == "Due" and due_customer[0]:
self.db.add_due_record(trans_id, due_customer[0], amount)
self._deduct_product_quantities()
self._show_toast(f"Sales transaction of ₹{amount:.2f} added") # Skip translate, dynamic
amount_entry.delete(0, tk.END)
desc_entry.delete(0, tk.END)
due_customer[0] = None
payment_var.set("Cash")
self.show_transaction_summary('sales')
except ValueError:
self._show_toast(self.tr("Please enter a valid amount"), kind="error")
self._neu_btn(form_frame, self.tr("Add Sale"), command=add_sale,
kind="equals", width=20, height=2
).grid(row=4, column=0, columnspan=2, pady=5)
self.show_transaction_summary('sales')
self.root.after(250, lambda: amount_entry.focus_force())
def show_expense_mode(self):
"""Show expense entry interface"""
T = self.T
self.update_display(self.tr("Add Expense Transaction"))
form_frame = tk.Frame(self.content_frame, bg=T["bg"])
form_frame.pack(pady=5)
tk.Label(form_frame, text=self.tr("Amount:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=0, column=0, sticky=tk.W, pady=5)
amount_entry = tk.Entry(form_frame, font=config.LABEL_FONT, width=20,
bg=T["entry_bg"], fg=T["entry_fg"],
insertbackground=T["text"], relief=tk.FLAT,
highlightthickness=3, highlightbackground=T["shadow_dark"])
amount_entry.grid(row=0, column=1, pady=5, padx=10)
amount_entry.t9_mode = "num"
tk.Label(form_frame, text=self.tr("Category:"), font=config.LABEL_FONT,
bg=T["bg"], fg=T["text"]).grid(row=1, column=0, sticky=tk.W, pady=5)
category_var = tk.StringVar()
categories = self.transaction_manager.get_expense_categories()
category_combo = ttk.Combobox(form_frame, textvariable=category_var,
values=categories, font=config.LABEL_FONT, width=18)
category_combo.grid(row=1, column=1, pady=5, padx=10)
if "Supplies" in categories:
category_var.set("Supplies")
elif categories:
category_combo.current(0)
tk.Label(form_frame, text=self.tr("Description:"), font=config.LABEL_FONT,