-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
1712 lines (1443 loc) · 66.8 KB
/
main.py
File metadata and controls
1712 lines (1443 loc) · 66.8 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
#!/usr/bin/env python3
"""
Programmer's Calculator - A polished calculator with decimal/hex conversion
Updated with JSON config, pending op display, smart ESC, and Memory functions.
Enhanced with 3D buttons, gradient background, button animations, and LCD display.
Now with configurable hex display modes (Relative, Signed, Unsigned) and integer sizes.
"""
import os
import sys
import json
import time
import base64
import platform
from pathlib import Path
from platformdirs import user_config_dir
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout,
QGridLayout, QPushButton, QLabel, QDialog, QDialogButtonBox,
QCheckBox, QFontDialog, QScrollArea, QFrame, QMessageBox,
QGraphicsColorizeEffect, QSizePolicy, QComboBox, QGroupBox,
QGraphicsDropShadowEffect
)
from PyQt6.QtCore import (
Qt, QByteArray, pyqtSignal, QPropertyAnimation, QSequentialAnimationGroup, QPauseAnimation,
qInstallMessageHandler
)
from PyQt6.QtGui import QFont, QKeyEvent, QAction, QIcon, QPixmap, QColor, QPalette, QLinearGradient
try:
import qdarktheme
except ImportError:
qdarktheme = None
from icon import ICON_PNG_BASE64
import platformdirs
if platform.system() == 'Windows':
import ctypes
ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
"tatertech.proggycalc"
)
APP_NAME = "ProggyCalc"
APP_AUTHOR = "Tatertech"
# Global constants for UI customization
BUTTON_MIN_WIDTH = 30 # Minimum button width
BUTTON_MIN_HEIGHT = 25 # Minimum button height
GRADIENT_INTENSITY = 0.65 # Gradient intensity multiplier (0.0 to 2.0, where 1.0 is default)
BUTTON_HISTORY_RATIO = 0.385 # Ratio of width for buttons vs history (0.0 to 1.0, where 0.5 is equal split)
WINDOW_MARGINS = 5 # Margin between window border and contents (in pixels)
LAYOUT_SPACING = 4 # Spacing between widgets and layouts (in pixels)
CONFIG_DIR = Path(user_config_dir(APP_NAME, APP_AUTHOR))
def suppress_painter_warnings(msg_type, context, message):
# Suppress only QPainter and QWidgetEffectSourcePrivate warnings
if "QPainter::" in message or "QWidgetEffectSourcePrivate" in message:
return
# Let everything else through normally
print(message)
# Install before creating QApplication
qInstallMessageHandler(suppress_painter_warnings)
def icon_from_base64_png(b64: str) -> QIcon:
raw = base64.b64decode(b64)
ba = QByteArray(raw)
pixmap = QPixmap()
pixmap.loadFromData(ba, "PNG")
return QIcon(pixmap)
def get_app_path():
"""Resolve the correct path for both script and frozen (PyInstaller) execution."""
if getattr(sys, 'frozen', False):
return Path(sys.executable).parent
else:
return Path(__file__).parent
def adjust_gradient_color(color_hex, intensity):
"""Adjust a hex color based on gradient intensity"""
color = QColor(color_hex)
h, s, v, a = color.getHsv()
# Adjust value (brightness) based on intensity
# intensity < 1.0 makes gradients flatter
# intensity > 1.0 makes gradients more pronounced
if intensity < 1.0:
# Move toward middle value (128)
v = int(v + (128 - v) * (1.0 - intensity))
else:
# Enhance the existing value
if v > 128:
v = min(255, int(v + (255 - v) * (intensity - 1.0) * 0.5))
else:
v = max(0, int(v - v * (intensity - 1.0) * 0.5))
adjusted = QColor()
adjusted.setHsv(h, s, v, a)
return adjusted.name()
class ClickableLabel(QLabel):
"""A QLabel that emits a signal when clicked"""
clicked = pyqtSignal(str)
def __init__(self, text, parent=None):
super().__init__(text, parent)
# Keep your existing styling here...
self.setStyleSheet("padding: 4px; background-color: #101010; border-radius: 3px;")
# Setup the color effect for flashing
self.effect = QGraphicsColorizeEffect(self)
self.setGraphicsEffect(self.effect)
self.effect.setStrength(0) # Invisible by default
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
self.clicked.emit(self.text())
super().mousePressEvent(event)
self.flash()
def flash(self):
# Set the flash color (Green for success/copy)
self.effect.setColor(QColor("#4CAF50"))
# Create the "Fade In" animation
self.anim_in = QPropertyAnimation(self.effect, b"strength")
self.anim_in.setDuration(50)
self.anim_in.setStartValue(0)
self.anim_in.setEndValue(0.8)
# Create the "Fade Out" animation
self.anim_out = QPropertyAnimation(self.effect, b"strength")
self.anim_out.setDuration(500)
self.anim_out.setStartValue(0.8)
self.anim_out.setEndValue(0)
# Sequence: Flash on quickly, pause for a split second, then fade out
self.group = QSequentialAnimationGroup()
self.group.addAnimation(self.anim_in)
self.group.addPause(100)
self.group.addAnimation(self.anim_out)
self.group.start()
class AnimatedButton(QPushButton):
"""A QPushButton with a color flash animation when pressed"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
# Setup the color effect for flashing
self.effect = QGraphicsColorizeEffect(self)
self.setGraphicsEffect(self.effect)
self.effect.setStrength(0)
def flash(self):
"""Flash the button with a light gray color"""
self.effect.setColor(QColor("#CCCCCC")) # Light gray
# Create the "Fade In" animation
self.anim_in = QPropertyAnimation(self.effect, b"strength")
self.anim_in.setDuration(50)
self.anim_in.setStartValue(0)
self.anim_in.setEndValue(0.6)
# Create the "Fade Out" animation
self.anim_out = QPropertyAnimation(self.effect, b"strength")
self.anim_out.setDuration(300)
self.anim_out.setStartValue(0.6)
self.anim_out.setEndValue(0)
# Sequence: Flash on quickly, then fade out
self.group = QSequentialAnimationGroup()
self.group.addAnimation(self.anim_in)
self.group.addAnimation(self.anim_out)
self.group.start()
def mousePressEvent(self, event):
super().mousePressEvent(event)
self.flash()
class SettingsDialog(QDialog):
"""Settings dialog for calculator preferences"""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Settings")
self.setModal(True)
self.resize(350, 300)
layout = QVBoxLayout()
# Hex prefix option
self.hex_prefix_check = QCheckBox("Show '0x' prefix for hex numbers")
self.hex_prefix_check.setChecked(parent.config.get("hex_prefix", True))
layout.addWidget(self.hex_prefix_check)
# Binary prefix option
self.bin_prefix_check = QCheckBox("Show '0b' prefix for binary numbers")
self.bin_prefix_check.setChecked(parent.config.get("bin_prefix", True))
layout.addWidget(self.bin_prefix_check)
# Commas option
self.commas_check = QCheckBox("Show thousands separator (e.g. 1,000)")
self.commas_check.setChecked(parent.config.get("show_commas", False))
layout.addWidget(self.commas_check)
layout.addSpacing(10)
# Hex Display Mode Group
hex_group = QGroupBox("Hexadecimal Display Mode")
hex_layout = QVBoxLayout()
# Hex display mode selector
mode_layout = QHBoxLayout()
mode_label = QLabel("Mode:")
self.hex_mode_combo = QComboBox()
self.hex_mode_combo.addItems(["Relative", "Signed", "Unsigned"])
current_mode = parent.config.get("hex_display_mode", "relative")
mode_index = {"relative": 0, "signed": 1, "unsigned": 2}.get(current_mode, 0)
self.hex_mode_combo.setCurrentIndex(mode_index)
self.hex_mode_combo.currentIndexChanged.connect(self.on_hex_mode_changed)
mode_layout.addWidget(mode_label)
mode_layout.addWidget(self.hex_mode_combo)
mode_layout.addStretch()
hex_layout.addLayout(mode_layout)
# Integer size selector
size_layout = QHBoxLayout()
size_label = QLabel("Integer Size:")
self.int_size_combo = QComboBox()
self.int_size_combo.addItems(["8-bit", "16-bit", "32-bit", "64-bit", "128-bit"])
current_size = parent.config.get("integer_size", 64)
size_index = {8: 0, 16: 1, 32: 2, 64: 3, 128: 4}.get(current_size, 3)
self.int_size_combo.setCurrentIndex(size_index)
size_layout.addWidget(size_label)
size_layout.addWidget(self.int_size_combo)
size_layout.addStretch()
hex_layout.addLayout(size_layout)
# Info label
self.mode_info_label = QLabel()
self.mode_info_label.setWordWrap(True)
self.mode_info_label.setStyleSheet("color: #888; font-size: 9pt; padding: 5px;")
hex_layout.addWidget(self.mode_info_label)
hex_group.setLayout(hex_layout)
layout.addWidget(hex_group)
# Update info label and size combo state
self.on_hex_mode_changed()
layout.addSpacing(10)
# Font selection
font_layout = QHBoxLayout()
font_label = QLabel("Display Font:")
self.font_button = QPushButton("Choose Font...")
self.font_button.clicked.connect(self.choose_font)
font_layout.addWidget(font_label)
font_layout.addWidget(self.font_button)
font_layout.addStretch()
layout.addLayout(font_layout)
hist_font_layout = QHBoxLayout()
hist_font_label = QLabel("History Font:")
self.hist_font_button = QPushButton("Choose History Font...")
self.hist_font_button.clicked.connect(self.choose_history_font)
hist_font_layout.addWidget(hist_font_label)
hist_font_layout.addWidget(self.hist_font_button)
hist_font_layout.addStretch()
layout.addLayout(hist_font_layout)
layout.addStretch()
# Dialog buttons
button_box = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok |
QDialogButtonBox.StandardButton.Cancel
)
button_box.accepted.connect(self.accept)
button_box.rejected.connect(self.reject)
layout.addWidget(button_box)
self.setLayout(layout)
self.selected_font = None
self.selected_hist_font = None
def on_hex_mode_changed(self):
"""Update UI when hex display mode changes"""
mode = self.hex_mode_combo.currentText().lower()
# Enable/disable integer size based on mode
is_relative = (mode == "relative")
self.int_size_combo.setEnabled(not is_relative)
# Update info label
if mode == "relative":
info = "Negative values shown with minus sign (e.g., -0x15)"
elif mode == "signed":
info = "Signed arithmetic: allows negative results (e.g., 0x0 - 0x1 = -0x1)"
else: # unsigned
info = "Unsigned arithmetic: wraps around (e.g., 0x0 - 0x1 = 0xFF...)"
self.mode_info_label.setText(info)
def choose_font(self):
"""Open font dialog"""
current_font = self.parent().display.font()
font, ok = QFontDialog.getFont(current_font, self)
if ok:
self.selected_font = font
def choose_history_font(self):
"""Open font dialog for History"""
# Get current history font from parent's config or panel
current = self.parent().history_panel.current_font
font, ok = QFontDialog.getFont(current, self)
if ok:
self.selected_hist_font = font
class HistoryPanel(QFrame):
"""History panel showing previous calculations"""
entry_clicked = pyqtSignal(str)
def __init__(self, parent=None):
super().__init__(parent)
self.setFrameStyle(QFrame.Shape.StyledPanel | QFrame.Shadow.Sunken)
# Remove fixed width constraints - now controlled by layout stretch
layout = QVBoxLayout()
layout.setContentsMargins(8, 8, 8, 8)
# Title
title = QLabel("History")
title_font = QFont()
title_font.setBold(True)
title.setFont(title_font)
layout.addWidget(title)
# Scroll area for history items
scroll = QScrollArea()
scroll.setWidgetResizable(True)
scroll.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
self.history_widget = QWidget()
self.history_layout = QVBoxLayout()
self.history_layout.setSpacing(4)
self.history_layout.addStretch()
self.history_widget.setLayout(self.history_layout)
scroll.setWidget(self.history_widget)
layout.addWidget(scroll)
self.setLayout(layout)
self.history_items = []
self.current_font = QFont("Consolas", 9)
def add_entry(self, text):
"""Add a history entry"""
label = ClickableLabel(text)
label.clicked.connect(self.entry_clicked.emit) # Connect to panel signal
label.setWordWrap(True)
label.setStyleSheet("""
QLabel {
padding: 4px;
background-color: #101010;
border-radius: 3px;
}
QLabel:hover {
background-color: #2a2a2a;
}
""")
# Apply the current configured font
label.setFont(self.current_font)
# Insert at the top (before stretch)
self.history_layout.insertWidget(0, label)
self.history_items.insert(0, label)
# Keep only last 50 items
if len(self.history_items) > 50:
old_label = self.history_items.pop()
self.history_layout.removeWidget(old_label)
old_label.deleteLater()
def set_history_font(self, font: QFont):
"""Update font for all existing and future items"""
self.current_font = font
for label in self.history_items:
label.setFont(font)
def clear_history(self):
"""Clear all history"""
for label in self.history_items:
self.history_layout.removeWidget(label)
label.deleteLater()
self.history_items.clear()
class ProgrammerCalculator(QMainWindow):
"""Main calculator window"""
def __init__(self):
super().__init__()
# Default config
self.config = {
"hex_prefix": True,
"bin_prefix": True,
"show_commas": False,
"display_font": None,
"hex_mode": False,
"hex_display_mode": "relative", # relative, signed, unsigned
"integer_size": 64 # 8, 16, 32, 64, 128 bits
}
config_path = Path(CONFIG_DIR)
self.config_file = Path(CONFIG_DIR) / "config.json"
if not config_path.exists():
config_path.mkdir(parents=True, exist_ok=True)
# Calculator state
self.current_value = 0
self.stored_value = 0
self.operation = None
self.memory_value = 0
self.clear_press_count = 0
self.last_clear_time = 0
self.manual_ce_click = False
# Repeat operation state
self.last_operation = None
self.last_operand = None
self.shift_btn: AnimatedButton = None
self.hex_mode = False # False = decimal, True = hex
self.new_number = True
self.load_settings()
self.init_ui()
self.load_settings()
def get_bit_mask(self):
"""Get the bit mask for current integer size"""
size = self.config.get("integer_size", 64)
return (1 << size) - 1
def get_sign_bit(self):
"""Get the sign bit position for current integer size"""
size = self.config.get("integer_size", 64)
return 1 << (size - 1)
def apply_integer_size(self, value):
"""Apply integer size constraints based on hex display mode"""
mode = self.config.get("hex_display_mode", "relative")
if mode == "relative":
# No constraints in relative mode
return value
size = self.config.get("integer_size", 64)
mask = self.get_bit_mask()
if mode == "unsigned":
# Wrap to unsigned range [0, 2^size - 1]
# Always positive, wraps around
return value & mask
else: # signed
# Signed range: [-2^(size-1), 2^(size-1) - 1]
max_positive = (1 << (size - 1)) - 1 # e.g., 127 for 8-bit
min_negative = -(1 << (size - 1)) # e.g., -128 for 8-bit
# First normalize to signed range
if value > max_positive:
# Wrap down from positive overflow
range_size = (1 << size)
while value > max_positive:
value -= range_size
elif value < min_negative:
# Wrap up from negative overflow
range_size = (1 << size)
while value < min_negative:
value += range_size
return value
def update_text_shadows(self):
mode_shadow = QGraphicsDropShadowEffect()
mode_shadow.setBlurRadius(2) # 0 = Sharp edges (No glow)
mode_shadow.setOffset(2.0, 2.0) # Offset: 4px right, 4px down
mode_shadow.setColor(QColor(0, 0, 0)) # Shadow color: Black
self.mode_label.setGraphicsEffect(mode_shadow)
op_label_shadow = QGraphicsDropShadowEffect()
op_label_shadow.setBlurRadius(2) # 0 = Sharp edges (No glow)
op_label_shadow.setOffset(2.0, 2.0) # Offset: 4px right, 4px down
op_label_shadow.setColor(QColor(0, 0, 0)) # Shadow color: Black
self.op_label.setGraphicsEffect(op_label_shadow)
display_shadow = QGraphicsDropShadowEffect()
display_shadow.setBlurRadius(1) # 0 = Sharp edges (No glow)
display_shadow.setOffset(2.0, 4.0) # Offset: 4px right, 4px down
display_shadow.setColor(QColor(0, 0, 0)) # Shadow color: Black
self.display.setGraphicsEffect(display_shadow)
def init_ui(self):
"""Initialize the user interface"""
self.setWindowTitle("ProggyCalc")
# Central widget and main layout
central = QWidget()
self.setCentralWidget(central)
# Set gradient background on central widget
central.setAutoFillBackground(True)
palette = central.palette()
gradient = QLinearGradient(0, 0, 0, 600)
gradient.setColorAt(0.0, QColor("#1a1a2e"))
gradient.setColorAt(1.0, QColor("#0f0f1e"))
palette.setBrush(QPalette.ColorRole.Window, gradient)
central.setPalette(palette)
# Main vertical layout
main_layout = QVBoxLayout()
main_layout.setSpacing(LAYOUT_SPACING)
main_layout.setContentsMargins(WINDOW_MARGINS, WINDOW_MARGINS, WINDOW_MARGINS, WINDOW_MARGINS)
# Display area (full width at top)
self.display_frame = QFrame()
self.display_frame.setFrameStyle(QFrame.Shape.StyledPanel | QFrame.Shadow.Sunken)
# LCD-style background with subtle grid pattern
self.display_frame.setStyleSheet("""
QFrame {
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 #1a3a1a, stop:0.5 #132813, stop:1 #0d1f0d);
border: 2px solid #0a0a0a;
border-radius: 8px;
}
""")
self.display_layout = QVBoxLayout()
self.display_layout.setContentsMargins(5, 5, 5, 5)
# Top info row (Mode + Pending Op)
info_layout = QHBoxLayout()
# Mode indicator
self.mode_label = QLabel("DEC")
mode_font = QFont()
mode_font.setBold(True)
mode_font.setPointSize(9)
self.mode_label.setFont(mode_font)
self.mode_label.setStyleSheet("color: #00ff00; background: transparent; border: 0px solid #0a0a0a;")
info_layout.addWidget(self.mode_label)
info_layout.addStretch()
# Pending Operation Indicator
self.op_label = QLabel("")
op_font = QFont("Tahoma", 14)
op_font.setBold(True)
self.op_label.setFont(op_font)
self.op_label.setStyleSheet("color: #00ff00; background: transparent; border: 0px solid #0a0a0a;")
self.op_label.setMaximumHeight(22)
self.op_label.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
info_layout.addWidget(self.op_label)
self.display_layout.addLayout(info_layout)
self.display_effect = None
# Main display with LCD-style text
self.display = QLabel("0")
self.display.setAlignment(Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter)
display_font = QFont("Consolas", 24)
display_font.setWeight(QFont.Weight.Bold)
self.display.setFont(display_font)
self.display.setMinimumHeight(60)
# LCD green glow effect
self.display.setStyleSheet("""
QLabel {
color: #00ff00;
background: transparent;
border: 0px solid #0a0a0a;
}
""")
self.display_layout.addWidget(self.display)
# Alternative representations with LCD styling
self.alt_display = QLabel("HEX: 0x0 BIN: 0b0")
alt_font = QFont("Consolas", 9)
self.alt_display.setFont(alt_font)
self.alt_display.setStyleSheet("""
QLabel {
padding: 0px;
background: rgba(50, 80, 50, 60);
color: #66ff66;
border-radius: 3px;
border: 1px groove #0a0a0a;
}
""")
self.alt_display.setMaximumHeight(20)
self.display_layout.addWidget(self.alt_display)
self.display_frame.setLayout(self.display_layout)
main_layout.addWidget(self.display_frame)
# Horizontal layout for buttons and history (side by side)
bottom_layout = QHBoxLayout()
bottom_layout.setSpacing(LAYOUT_SPACING)
# Left side - calculator buttons
self.calc_layout = QVBoxLayout()
self.calc_layout.setSpacing(LAYOUT_SPACING)
self.calc_layout.setContentsMargins(0, 0, 0, 0)
self.update_text_shadows()
# Button grid
button_layout = QGridLayout()
button_layout.setSpacing(4)
# 3D Button styling with adjustable gradient intensity
button_3d_style = f"""
QPushButton {{
border: 1px solid #00000066;
border-radius: 5px;
font-size: 12pt;
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#4a4a4a', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#3a3a3a', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#2a2a2a', GRADIENT_INTENSITY)});
color: #ffffff;
padding: 2px;
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#5a5a5a', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a4a4a', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a3a3a', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#2a2a2a', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#3a3a3a', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#4a4a4a', GRADIENT_INTENSITY)});
border: 1px solid #666666;
}}
QPushButton:disabled {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#333333', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#282828', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#1e1e1e', GRADIENT_INTENSITY)});
color: #666666;
}}
"""
# Button definitions (text, row, col, operation/value)
buttons = [
# Row 0 - Memory
("MS", 0, 0, "mem_store"), ("MR", 0, 1, "mem_recall"), ("M+", 0, 2, "mem_add"), ("M-", 0, 3, "mem_sub"),
# Row 1
("C", 1, 0, "clear"), ("CE", 1, 1, "clear_entry"), ("%", 1, 2, "mod"), ("/", 1, 3, "div"),
# Row 2
("7", 2, 0, 7), ("8", 2, 1, 8), ("9", 2, 2, 9), ("*", 2, 3, "mul"),
# Row 3
("4", 3, 0, 4), ("5", 3, 1, 5), ("6", 3, 2, 6), ("-", 3, 3, "sub"),
# Row 4
("1", 4, 0, 1), ("2", 4, 1, 2), ("3", 4, 2, 3), ("+", 4, 3, "add"),
# Row 5
("A", 5, 0, "A"), ("B", 5, 1, "B"), ("0", 5, 2, 0), ("=", 5, 3, "equals"),
# Row 6 - Hex digits
("C", 6, 0, "C"), ("D", 6, 1, "D"), ("AND", 6, 2, "and"), ("OR", 6, 3, "or"),
# Row 7
("E", 7, 0, "E"), ("F", 7, 1, "F"), ("XOR", 7, 2, "xor"), ("<<", 7, 3, "lshift"),
]
self.buttons = {}
self.button_map = {} # Map actions to buttons for keyboard flash
for text, row, col, action in buttons:
btn = AnimatedButton(text)
btn.setMinimumSize(BUTTON_MIN_WIDTH, BUTTON_MIN_HEIGHT)
btn.setSizePolicy(
QSizePolicy.Policy.Expanding,
QSizePolicy.Policy.Expanding
)
btn.setStyleSheet(button_3d_style)
if text == "<<":
self.shift_btn = btn # Save reference for later
if isinstance(action, int):
btn.clicked.connect(lambda checked, a=action: self.number_pressed(a))
self.button_map[str(action)] = btn
elif action in ["A", "B", "C", "D", "E", "F"]:
btn.clicked.connect(lambda checked, a=action: self.hex_digit_pressed(a))
self.buttons[action] = btn
self.button_map[action] = btn
elif action in ["add", "sub", "mul", "div", "mod", "and", "or", "xor", "lshift"]:
btn.clicked.connect(lambda checked, a=action: self.operation_pressed(a))
self.button_map[action] = btn
if action in ["add", "sub", "mul", "div", "mod"]:
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3a4a56', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#2a3a46', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#1a2a36', GRADIENT_INTENSITY)});
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#4a5a66', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#3a4a56', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#2a3a46', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#1a2a36', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#2a3a46', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a4a56', GRADIENT_INTENSITY)});
}}
""")
elif action == "equals":
btn.clicked.connect(self.equals_pressed)
self.button_map["equals"] = btn
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#2f4a37', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#1f3a27', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#0f2a17', GRADIENT_INTENSITY)});
font-weight: bold;
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3f5a47', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#2f4a37', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#1f3a27', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#0f2a17', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#1f3a27', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#2f4a37', GRADIENT_INTENSITY)});
}}
""")
elif action == "clear":
btn.clicked.connect(self.clear_all)
self.button_map["clear"] = btn
elif action == "clear_entry":
def handle_ce_button():
self.manual_ce_click = True
self.handle_escape()
btn.clicked.connect(handle_ce_button)
self.button_map["clear_entry"] = btn
elif action == "mem_store":
btn.clicked.connect(self.memory_store)
self.button_map["mem_store"] = btn
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)});
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#6a5a40', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)});
}}
""")
elif action == "mem_recall":
btn.clicked.connect(self.memory_recall)
self.button_map["mem_recall"] = btn
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)});
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#6a5a40', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)});
}}
""")
elif action == "mem_add":
btn.clicked.connect(self.memory_add)
self.button_map["mem_add"] = btn
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)});
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#6a5a40', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)});
}}
""")
elif action == "mem_sub":
btn.clicked.connect(self.memory_sub)
self.button_map["mem_sub"] = btn
btn.setStyleSheet(button_3d_style + f"""
QPushButton {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)});
}}
QPushButton:hover {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#6a5a40', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)});
}}
QPushButton:pressed {{
background: qlineargradient(x1:0, y1:0, x2:0, y2:1,
stop:0 {adjust_gradient_color('#3a2a10', GRADIENT_INTENSITY)},
stop:0.5 {adjust_gradient_color('#4a3a20', GRADIENT_INTENSITY)},
stop:1 {adjust_gradient_color('#5a4a30', GRADIENT_INTENSITY)});
}}
""")
button_layout.addWidget(btn, row, col)
def handle_lshift():
if self.shift_btn.text() == "<<":
self.operation_pressed('lshift')
elif self.shift_btn.text() == ">>":
self.operation_pressed('rshift')
# Remove existing connections
self.shift_btn.clicked.disconnect()
self.shift_btn.clicked.connect(handle_lshift)
self.button_map["rshift"] = self.shift_btn
self.calc_layout.addLayout(button_layout)
# Create a container widget for buttons to control its width
button_container = QWidget()
button_container.setLayout(self.calc_layout)
# Make sure buttons expand to fill available space
for i in range(4): # 4 columns
button_layout.setColumnStretch(i, 1)
for i in range(8): # 8 rows
button_layout.setRowStretch(i, 1)
# Right side - history panel (now next to buttons)
self.history_panel = HistoryPanel()
self.history_panel.entry_clicked.connect(self.copy_history_value)
# Add buttons and history to bottom layout with stretch factors based on ratio
# Calculate stretch factors from ratio (e.g., 0.6 means buttons get 60%, history gets 40%)
button_stretch = int(BUTTON_HISTORY_RATIO * 100)
history_stretch = int((1.0 - BUTTON_HISTORY_RATIO) * 100)
bottom_layout.addWidget(button_container, button_stretch)
bottom_layout.addWidget(self.history_panel, history_stretch)
# Add bottom layout to main layout
main_layout.addLayout(bottom_layout)
central.setLayout(main_layout)
# Menu bar
menubar = self.menuBar()
# File menu with quit
file_menu = menubar.addMenu("&File")
quit_action = QAction("&Quit", self)
quit_action.triggered.connect(self.close)
file_menu.addAction(quit_action)
# Edit menu
edit_menu = menubar.addMenu("&Edit")
copy_action = QAction("&Copy", self)
copy_action.setShortcut("Ctrl+C")
copy_action.triggered.connect(self.copy_to_clipboard)
edit_menu.addAction(copy_action)
paste_action = QAction("&Paste", self)
paste_action.setShortcut("Ctrl+V")
paste_action.triggered.connect(self.paste_from_clipboard)
edit_menu.addAction(paste_action)
edit_menu.addSeparator()
clear_history_action = QAction("Clear &History", self)
clear_history_action.triggered.connect(self.history_panel.clear_history)
edit_menu.addAction(clear_history_action)
edit_menu.addSeparator()
settings_action = QAction("&Settings...", self)
settings_action.triggered.connect(self.show_settings)
edit_menu.addAction(settings_action)
# Help menu
help_menu = menubar.addMenu("&Help")
shortcuts_action = QAction("&Keyboard Shortcuts", self)
shortcuts_action.triggered.connect(self.show_shortcuts)
help_menu.addAction(shortcuts_action)
# Set window properties
size_w = 700
size_h = 480
self.setMinimumSize(size_w, size_h)
self.setMaximumSize(size_w, size_h)
self.resize(size_w, size_h)
# Prevent resize
self.setFixedSize(size_w, size_h)
# Prevent maximize
self.setWindowFlags(self.windowFlags() & ~Qt.WindowType.WindowMaximizeButtonHint)
self.update_display()
self.update_hex_buttons()
self.update_mode_label()
def backspace(self):
"""Remove the rightmost digit from current_value"""
if self.new_number:
# If we're starting a new number, backspace does nothing
return
if self.hex_mode:
# In hex mode, divide by 16 to remove rightmost hex digit
self.current_value = self.current_value // 16
else:
# In decimal mode, divide by 10 to remove rightmost digit
self.current_value = self.current_value // 10
self.update_display()
def flash_display(self, color_hex):
"""Creates a brief color flash on the main display."""
# Create effect if it doesn't exist, or reuse
if not hasattr(self, 'display_effect') or self.display_effect is None:
self.display_effect = QGraphicsColorizeEffect(self.display_frame)
self.display_frame.setGraphicsEffect(self.display_effect)
self.display_effect.setColor(QColor(color_hex))
# Animation: Quick fade in, then fade out
self.anim_in = QPropertyAnimation(self.display_effect, b"strength")
self.anim_in.setDuration(50)
self.anim_in.setStartValue(0)
self.anim_in.setEndValue(0.7)
self.anim_out = QPropertyAnimation(self.display_effect, b"strength")
self.anim_out.setDuration(400)
self.anim_out.setStartValue(0.7)
self.anim_out.setEndValue(0)
self.flash_group = QSequentialAnimationGroup()
self.flash_group.addAnimation(self.anim_in)
self.flash_group.addAnimation(self.anim_out)
self.flash_group.start()