-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathgui_v4.py
More file actions
2910 lines (2406 loc) · 138 KB
/
Copy pathgui_v4.py
File metadata and controls
2910 lines (2406 loc) · 138 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 ctypes
from PySide6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
QHBoxLayout, QLabel, QPushButton, QComboBox,
QLineEdit, QToolBar, QStatusBar, QFrame, QFormLayout,
QSizePolicy, QScrollArea, QCheckBox, QGridLayout, QTextEdit, QTabWidget, QGroupBox, QSpacerItem)
from PySide6.QtCore import Qt, QSize, QMetaObject, Signal, QTimer, Slot, QUrl
from PySide6.QtGui import QIcon, QAction, QFont, QColor, QFontDatabase, QDesktopServices
import nuitka_compat
from logger import log_debug
from qt_dialogs import askcolor
# --- Modern CustomSpinBox (Replaces unreliable system SpinBoxes) ---
class CustomSpinBox(QWidget):
valueChanged = Signal(float)
def __init__(self, min_val=0, max_val=100, step=1, is_double=False, decimals=2, parent=None):
super().__init__(parent)
self.min_val = min_val
self.max_val = max_val
self.step = step
self.is_double = is_double
self.decimals = decimals
self._value = min_val
layout = QHBoxLayout(self)
layout.setContentsMargins(0, 0, 0, 0)
layout.setSpacing(0)
self.btn_minus = QPushButton("-")
self.btn_plus = QPushButton("+")
self.btn_minus.setCursor(Qt.PointingHandCursor)
self.btn_plus.setCursor(Qt.PointingHandCursor)
self.lbl_value = QLabel(self._format_val(self._value))
self.lbl_value.setAlignment(Qt.AlignCenter)
# Enforce proportions - buttons should not grow indefinitely, they act as icons
self.btn_minus.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
self.btn_plus.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Preferred)
self.lbl_value.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred)
layout.addWidget(self.btn_minus)
layout.addWidget(self.lbl_value)
layout.addWidget(self.btn_plus)
self.btn_minus.clicked.connect(self.decrement)
self.btn_plus.clicked.connect(self.increment)
def _format_val(self, val):
if self.is_double: return f"{val:.{self.decimals}f}"
return str(int(val))
def value(self):
return self._value if self.is_double else int(self._value)
def setValue(self, val):
old_val = self._value
self._value = max(self.min_val, min(self.max_val, float(val)))
if not self.is_double: self._value = int(self._value)
self.lbl_value.setText(self._format_val(self._value))
if old_val != self._value:
self.valueChanged.emit(self._value)
def setRange(self, min_val, max_val):
self.min_val = min_val
self.max_val = max_val
self.setValue(self._value)
def setSingleStep(self, step):
self.step = step
def setDecimals(self, decimals):
self.decimals = decimals
self.lbl_value.setText(self._format_val(self._value))
def decrement(self):
new_val = self._value - self.step
if self.is_double: new_val = round(new_val, self.decimals)
self.setValue(new_val)
def increment(self):
new_val = self._value + self.step
if self.is_double: new_val = round(new_val, self.decimals)
self.setValue(new_val)
# ------------------------------------------------------------------------
class SegmentedToggle(QWidget):
valueChanged = Signal(int)
def __init__(self, parent=None, active_color="#2196F3"):
super().__init__(parent)
self.active_color = active_color
self._current_index = 0
self._dp_func = parent.dp if parent and hasattr(parent, 'dp') else lambda x: x
self._scaled_font_size = parent.scaled_font_size if parent and hasattr(parent, 'scaled_font_size') else 14
self.layout = QHBoxLayout(self)
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(self._dp_func(5)) # Slight spacing between merged buttons
self.btn1 = QPushButton()
self.btn2 = QPushButton()
# Use standard app scaling for icons (base 20px)
fs = self._dp_func(20)
for btn in [self.btn1, self.btn2]:
btn.setCheckable(True)
btn.setCursor(Qt.PointingHandCursor)
btn.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
btn.setIconSize(QSize(fs, fs))
btn.setFont(QFont('Segoe UI', parent.scaled_font_size, QFont.Weight.Bold))
self.layout.addWidget(self.btn1)
self.layout.addWidget(self.btn2)
self.btn1.clicked.connect(self.on_btn_clicked)
self.btn2.clicked.connect(self.on_btn_clicked)
def on_btn_clicked(self):
new_index = 1 if self._current_index == 0 else 0
self.setCurrentIndex(new_index, emit=True)
def set_labels(self, label1, label2):
self.btn1.setText(label1)
self.btn2.setText(label2)
def set_icons(self, icon1, icon2):
self.btn1.setIcon(icon1)
self.btn2.setIcon(icon2)
self._update_styles()
def currentIndex(self):
return self._current_index
def setCurrentIndex(self, index, emit=False):
if self._current_index == index and not emit:
return
self._current_index = index
self._update_styles()
if emit:
self.valueChanged.emit(index)
def _update_styles(self):
dp = self._dp_func
rad = dp(4)
fs = 11 # Default fallback
if hasattr(self.parent(), 'scaled_font_size'):
# Increase base font size slightly to match QToolBar actions
fs = round(self.parent().scaled_font_size * 1.15)
# Base style: Consistent with standard app scaling
style_base = f"""
QPushButton {{
border: none;
background-color: transparent;
padding: {dp(4)}px {dp(10)}px;
font-size: {self._scaled_font_size}pt;
font-weight: normal;
color: #757575;
font-family: 'Segoe UI';
}}
QPushButton:hover {{
background-color: #F0F0F0;
}}
"""
# Active: bold black, NO border
active_style = f"""
QPushButton {{
color: #333333;
font-weight: bold;
border: none;
}}
"""
s1 = style_base
if self._current_index == 0: s1 += active_style
s2 = style_base
if self._current_index == 1: s2 += active_style
self.btn1.setStyleSheet(s1)
self.btn2.setStyleSheet(s2)
class StatusToggleButton(QPushButton):
"""A button that supports an 'active' state with a blue border and no background."""
def __init__(self, text, active_color="#4CAF50", parent=None):
super().__init__(text, parent)
self.active_color = active_color
self._is_active = False
self._dp_func = parent.dp if parent and hasattr(parent, 'dp') else lambda x: x
self._scaled_font_size = parent.scaled_font_size if parent and hasattr(parent, 'scaled_font_size') else 14
self.setCursor(Qt.PointingHandCursor)
self.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
# Consistent icon scaling (base 20px)
fs = self._dp_func(20)
self.setIconSize(QSize(fs, fs))
self.setFont(QFont('Segoe UI', parent.scaled_font_size, QFont.Weight.Bold))
self.update_appearance()
def set_active(self, active):
self._is_active = active
self.update_appearance()
def update_appearance(self):
dp = self._dp_func
style = f"""
QPushButton {{
border: none;
background-color: transparent;
padding: {dp(4)}px {dp(10)}px;
font-size: {self._scaled_font_size}pt;
font-weight: normal;
color: #757575;
font-family: 'Segoe UI';
}}
QPushButton:hover {{
background-color: #F0F0F0;
}}
"""
if self._is_active:
style += f"""
QPushButton {{
color: #333333;
font-weight: bold;
}}
"""
self.setStyleSheet(style)
# ------------------------------------------------------------------------
class HelpButton(QPushButton):
"""Przycisk z ikoną pomocy, który po kliknięciu otwiera podręcznik użytkownika we wskazanym miejscu."""
def __init__(self, anchor="", icon_name="info", parent=None, tooltip_key=None):
super().__init__(parent)
self.anchor = anchor
self.icon_name = icon_name
self.tooltip_key = tooltip_key
# Pobieranie funkcji skalowania dp() od rodzica (MainWindowV4)
self.dp = parent.dp if parent and hasattr(parent, "dp") else lambda x: x
self.setFixedSize(self.dp(28), self.dp(28))
self.setIconSize(QSize(self.dp(24), self.dp(24)))
self.setCursor(Qt.PointingHandCursor)
self.update_tooltip()
# Load icon safely
try:
import nuitka_compat
import os
base_dir = nuitka_compat.get_base_dir()
if self.icon_name.endswith('.svg'):
icon_path = os.path.join(base_dir, "assets", self.icon_name)
else:
icon_path = os.path.join(base_dir, "assets", f"{self.icon_name}_flat.svg")
if os.path.exists(icon_path):
self.setIcon(QIcon(icon_path))
else:
self.setText("ℹ")
except Exception:
self.setText("ℹ")
self.setStyleSheet("""
QPushButton {
background-color: transparent;
border: none;
font-size: 16px;
border-radius: 4px;
color: #1565C0;
}
QPushButton:hover {
background-color: #e5e7eb;
}
QPushButton:pressed {
background-color: #d1d5db;
}
""")
self.clicked.connect(self.open_manual)
def update_tooltip(self):
mw = self.window()
if mw and hasattr(mw, "translator") and mw.translator:
lng = mw.translator.ui_lang
if self.tooltip_key:
self.setToolTip(lng.get_label(self.tooltip_key))
elif self.icon_name in ["idea", "lightbulb"]:
self.setToolTip(lng.get_label('tooltip_help_idea', 'Read in-depth guide'))
else:
self.setToolTip(lng.get_label('tooltip_help_info', 'View in user manual'))
else:
if self.tooltip_key:
self.setToolTip("Info") # Simple fallback
elif self.icon_name in ["idea", "lightbulb"]:
self.setToolTip("Read in-depth guide")
else:
self.setToolTip("View in user manual")
def open_manual(self):
import os
import nuitka_compat
base_dir = nuitka_compat.get_base_dir()
manual_path = os.path.join(base_dir, "docs", "user-manual.html")
if os.path.exists(manual_path):
url_str = f"file:///{manual_path.replace(os.sep, '/')}"
if self.anchor:
url_str += f"#{self.anchor}"
QDesktopServices.openUrl(QUrl(url_str))
else:
print(f"Manual not found at: {manual_path}")
class ScreenshotToast(QLabel):
"""Transient notification widget for screenshot confirmation."""
def __init__(self, message):
super().__init__(None)
self.setText(message)
self.setAlignment(Qt.AlignCenter)
self.setStyleSheet("""
QLabel {
background-color: rgba(30, 30, 30, 220);
color: #00FFCC;
border: 1px solid #00FFCC;
border-radius: 12px;
padding: 14px 20px;
font-weight: bold;
font-size: 13px;
}
""")
self.setWindowFlags(Qt.ToolTip | Qt.FramelessWindowHint | Qt.WindowStaysOnTopHint)
self.setAttribute(Qt.WA_ShowWithoutActivating)
self.setAttribute(Qt.WA_DeleteOnClose) # prevent memory leak on repeated screenshots
def show_and_fade(self):
screen = QApplication.primaryScreen().availableGeometry() # excludes taskbar
self.adjustSize()
self.move(screen.right() - self.width() - 20, screen.bottom() - self.height() - 20)
self.show()
QTimer.singleShot(2500, self.close)
class MainWindowV4(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("Game-Changing Translator v4")
self.translator = None
self.source_overlay = None
self.target_overlay = None
self._pending_colors = {}
self._is_loading = True
self._is_toggling_visibility = False
# Set Application Icon
icon_path = os.path.join(nuitka_compat.get_base_dir(), "assets", "app_icon_shadow.ico")
if os.path.exists(icon_path):
self.setWindowIcon(QIcon(icon_path))
self.init_dpi_scaling()
self.init_ui()
self.bind_auto_save()
def get_system_fonts(self):
db = QFontDatabase()
all_fonts = sorted(db.families())
preferred_fonts = ['Arial', 'Times New Roman', 'Calibri', 'Cambria', 'Segoe UI']
final_fonts = []
for font in preferred_fonts:
if font in all_fonts:
final_fonts.append(font); all_fonts.remove(font)
final_fonts.extend(all_fonts)
return final_fonts
def synchronize_combo_widths(self):
"""Ensure all model and context combos have the same width based on the widest one."""
combos = [self.translation_model_combo, self.ocr_model_combo,
self.gemini_context_combo, self.deepl_context_combo]
# Reset to allow natural size hint calculation
for c in combos:
c.setMinimumWidth(0)
# Force a layout update to ensure size hints are fresh
QApplication.processEvents()
# Find maximum width required
max_w = 0
for c in combos:
max_w = max(max_w, c.sizeHint().width())
# Apply the uniform width
if max_w > 0:
for c in combos:
c.setMinimumWidth(max_w)
def synchronize_language_combo_widths(self):
"""Ensure Source and Target language combos have the same width based on the widest content."""
combos = [self.source_lang_combo, self.target_lang_combo]
# Reset to allow natural size hint calculation
for c in combos:
c.setMinimumWidth(0)
c.updateGeometry()
# Force layout updates to ensure size hints are fresh
QApplication.processEvents()
QApplication.sendPostedEvents()
# Find maximum width required
max_w = 0
for c in combos:
hint_w = c.sizeHint().width()
max_w = max(max_w, hint_w)
# Apply the uniform width
if max_w > 0:
for c in combos:
c.setMinimumWidth(max_w)
def retranslate_ui(self):
if not self.translator: return
self.setWindowTitle(self.translator.ui_lang.get_label('app_title', 'Game-Changing Translator v4'))
already_loading = getattr(self, '_is_loading', False)
self._is_loading = True
lng = self.translator.ui_lang
# Actions/Buttons
# Update Segmented Toggles and Settings Button with SVG icons
self.config_mode_btn.set_labels(
lng.get_label('config_mode_simple', 'Simple'),
lng.get_label('config_mode_advanced', 'Custom')
)
self.config_mode_btn.set_icons(
QIcon("assets/mode_simple.svg"),
QIcon("assets/mode_custom.svg")
)
self.settings_visibility_btn.setText(lng.get_label('settings_tab_title', 'Settings'))
self.settings_visibility_btn.setIcon(QIcon("assets/settings.svg"))
# Update standard toolbar actions with SVG icons
self.action_source.setText(lng.get_label('select_source_btn', 'Select Source Area (OCR)'))
self.action_source.setIcon(QIcon("assets/source.svg"))
self.action_target.setText(lng.get_label('select_target_btn', 'Select Target Area (Translation)'))
self.action_target.setIcon(QIcon("assets/target.svg"))
self.show_gemini_key_btn.setText(lng.get_label('ui_visibility_show', 'Show'))
self.show_deepl_key_btn.setText(lng.get_label('ui_visibility_show', 'Show'))
self.lbl_gemini_key.setText(lng.get_label('gemini_api_key_label', 'Gemini API Key:'))
self.lbl_deepl_key.setText(lng.get_label('deepl_api_key_label', 'DeepL API Key:'))
# Status & Button state
self.update_status_display()
self.update_licence_display()
self.update_about_text()
self.save_settings_btn.setText(" " + lng.get_label('save_settings_btn', 'Save Settings'))
save_icon_path = os.path.join(nuitka_compat.get_base_dir(), "assets", "floppy_disk_flat.svg")
if os.path.exists(save_icon_path):
self.save_settings_btn.setIcon(QIcon(save_icon_path))
self.save_settings_btn.setIconSize(QSize(self.dp(20), self.dp(20)))
else:
self.save_settings_btn.setIcon(QIcon())
# Main Tab labels
self.lbl_source_lang.setText(lng.get_label('source_lang_label', 'Source Language:'))
self.lbl_target_lang.setText(lng.get_label('target_lang_label', 'Target Language:'))
self.lbl_gemini_key.setText(lng.get_label('gemini_api_key_label', 'Gemini API Key:'))
self.lbl_deepl_key.setText(lng.get_label('deepl_api_key_label', 'DeepL API Key:'))
# Tab Titles
# Tab Titles - New Order: Settings, Costs, Shortcuts, About
self.tab_widget.setTabText(0, lng.get_label('settings_tab_title', 'Settings'))
self.tab_widget.setTabText(1, lng.get_label('custom_prompt_tab_title', 'Custom Prompt'))
self.tab_widget.setTabText(2, lng.get_label('api_usage_tab_title', 'API Usage'))
self.tab_widget.setTabText(3, lng.get_label('shortcuts_tab_title', 'Shortcuts'))
self.tab_widget.setTabText(4, lng.get_label('about_tab_title', 'About'))
# Custom Prompt Tab
if hasattr(self, 'grp_custom_trans'):
self.grp_custom_trans.setTitle(lng.get_label('custom_prompt_translation_title', 'Translation Prompt'))
self.grp_custom_ocr.setTitle(lng.get_label('custom_prompt_ocr_title', 'OCR Prompt'))
self.lbl_cp_trans_info.setText(lng.get_label('custom_prompt_info', 'This text will be added...'))
self.lbl_cp_ocr_info.setText(f"<sup style='color: gray; font-style: normal;'>PRO</sup> {lng.get_label('custom_prompt_ocr_info', 'This text will be added...')}")
self.save_cp_btn.setText(lng.get_label('save_btn', 'Save'))
self.reload_cp_btn.setText(lng.get_label('reload_btn', 'Reload'))
self.save_ocr_cp_btn.setText(lng.get_label('save_btn', 'Save'))
self.reload_ocr_cp_btn.setText(lng.get_label('reload_btn', 'Reload'))
enable_lbl = lng.get_label('custom_prompt_enabled_label', 'Enabled')
self.custom_prompt_trans_enabled_check.setText(enable_lbl)
self.custom_prompt_ocr_enabled_check.setText(enable_lbl)
# API Key Toggle Buttons
show_lbl = lng.get_label('show_btn', 'Show')
hide_lbl = lng.get_label('hide_btn', 'Hide')
for btn, entry in [(self.show_gemini_key_btn, self.gemini_api_key_entry),
(self.show_deepl_key_btn, self.deepl_api_key_entry)]:
is_hidden = (entry.echoMode() == QLineEdit.Password)
btn.setText(show_lbl if is_hidden else hide_lbl)
# API Key Placeholders
self.gemini_api_key_entry.setPlaceholderText(lng.get_label('gemini_api_key_placeholder', 'Mandatory field'))
self.deepl_api_key_entry.setPlaceholderText(lng.get_label('deepl_api_key_placeholder', 'Optional field'))
# Settings Groups & Elements
self.grp_models.setTitle(lng.get_label('models_and_context_section_label', 'Models and Context'))
self.lbl_translation_model.setText(lng.get_label('translation_model_label', 'Translation Model:'))
self.lbl_ocr_model.setText(lng.get_label('ocr_model_label', 'OCR Model:'))
self.lbl_gemini_context.setText(lng.get_label('gemini_context_window_label', 'Context Window:'))
current_g = self.gemini_context_combo.currentData()
self.gemini_context_combo.clear()
for i in range(6):
self.gemini_context_combo.addItem(lng.get_label(f'gemini_context_window_{i}', str(i)), i)
if current_g is not None: self.gemini_context_combo.setCurrentIndex(self.gemini_context_combo.findData(current_g))
current_d = self.deepl_context_combo.currentData()
self.deepl_context_combo.clear()
for i in range(4):
lbl = lng.get_label(f'deepl_context_window_{i}', lng.get_label(f'gemini_context_window_{i}', str(i)))
self.deepl_context_combo.addItem(lbl, i)
if current_d is not None: self.deepl_context_combo.setCurrentIndex(self.deepl_context_combo.findData(current_d))
self.lbl_deepl_context.setText(lng.get_label('deepl_context_window_label', 'Context Window:'))
self.grp_behavior.setTitle(lng.get_label('behavior_frame_title', 'App Behaviour'))
self.update_auto_detect_label()
self.update_capture_padding_label()
self.update_target_on_source_label()
self.update_debug_log_label()
self.update_info_tooltips()
self.keep_linebreaks_check.setText(lng.get_label('keep_linebreaks_label', 'Keep Linebreaks'))
self.lbl_scan_interval.setText(lng.get_label('scan_interval_label', 'Scan Interval (ms):'))
self.lbl_clear_timeout.setText(lng.get_label('clear_timeout_label', 'Clear Translation Timeout (s):'))
self.lbl_discovery_time.setText(lng.get_label('discovery_timeout_label', 'Time:'))
self.lbl_discovery_unit.setText(lng.get_label('discovery_timeout_unit', 'seconds'))
self.grp_appearance.setTitle(lng.get_label('appearance_frame_title', 'Appearance & Formatting'))
is_simple = getattr(self.translator, 'config_mode', '') == 'Simple'
self.lbl_source_color.setText(f"{lng.get_label('source_color_label', 'Source Area Colour:')} <sup style='color: gray;'>PRO</sup>")
self.lbl_target_color.setText(f"{lng.get_label('target_color_label', 'Target Area Colour:')} <sup style='color: gray;'>PRO</sup>")
self.lbl_target_text_color.setText(f"{lng.get_label('target_text_color_label', 'Target Text Colour:')} <sup style='color: gray;'>PRO</sup>")
self.source_color_btn.setText(lng.get_label('choose_color_btn', 'Choose Colour'))
self.target_color_btn.setText(lng.get_label('choose_color_btn', 'Choose Colour'))
self.target_text_color_btn.setText(lng.get_label('choose_color_btn', 'Choose Colour'))
self.lbl_font_size.setText(lng.get_label('font_size_label', 'Target Window Font Size:'))
self.lbl_font_type.setText(lng.get_label('font_type_label', 'Target Window Font Type:'))
self.lbl_opacity_bg.setText(lng.get_label('opacity_background_label', 'Opacity Background:'))
self.lbl_opacity_text.setText(lng.get_label('opacity_text_label', 'Opacity Text:'))
self.grp_performance.setTitle(lng.get_label('performance_frame_title', 'Performance & Cache'))
self.lbl_file_cache_desc.setText(lng.get_label('file_cache_description', 'File caching saves translations to disk...'))
self.gemini_cache_check.setText(lng.get_label('gemini_file_cache_checkbox', 'Enable Gemini file cache...'))
self.deepl_cache_check.setText(lng.get_label('deepl_file_cache_checkbox', 'Enable DeepL file cache...'))
self.clear_caches_btn.setText(lng.get_label('clear_caches_btn', 'Clear File Caches'))
self.clear_cache_btn.setText(lng.get_label('clear_cache_btn', 'Clear Translation Cache'))
self.clear_debug_log_btn.setText(lng.get_label('clear_debug_log_btn', 'Clear Debug Log'))
if hasattr(self, 'grp_lang'):
self.grp_lang.setTitle(lng.get_label('gui_language_label', 'Interface Language'))
self.lbl_gui_lang.setText(lng.get_label('gui_language_dropdown_label', 'Language:'))
# Shortcuts Tab
if hasattr(self, 'grp_shortcuts'):
sc_title = lng.get_label('keyboard_shortcuts_title', 'Keyboard Shortcuts')
self.grp_shortcuts.setTitle(f"{sc_title}")
self.lbl_sc_start.setText(f"~ : {lng.get_label('shortcut_start_stop', 'Start/Stop Translation')}")
self.lbl_sc_src.setText(f"Alt+1 : {lng.get_label('shortcut_toggle_source', 'Toggle Source Window Visibility')}")
self.lbl_sc_tgt.setText(f"Alt+2 : {lng.get_label('shortcut_toggle_target', 'Toggle Translation Window Visibility')}")
self.lbl_sc_save.setText(f"Alt+S : {lng.get_label('shortcut_save_settings', 'Save Settings')}")
self.lbl_sc_file.setText(f"Alt+F : {lng.get_label('shortcut_clear_file_caches', 'Clear File Caches')}")
self.lbl_sc_cache.setText(f"Alt+T : {lng.get_label('shortcut_clear_cache', 'Clear Translation Cache')}")
self.lbl_sc_log.setText(f"Alt+D : {lng.get_label('shortcut_clear_log', 'Clear Debug Log')}")
self.lbl_sc_reset.setText(f"Alt+R : {lng.get_label('shortcut_reset_window', 'Reset App Window')}")
self.lbl_sc_screenshot.setText(f"Alt+L : {lng.get_label('shortcut_screenshot', 'Take Screenshot')}")
if hasattr(self, 'status_label'):
self.update_status_display()
# Costs Tab
if hasattr(self, 'refresh_stats_btn'):
self.refresh_stats_btn.setText(lng.get_label("api_usage_refresh_btn", 'Refresh Statistics'))
self.export_csv_btn.setText(lng.get_label("api_usage_export_csv_btn", 'Export (CSV)'))
self.export_text_btn.setText(lng.get_label("api_usage_export_text_btn", 'Export (Text)'))
self.copy_stats_btn.setText(lng.get_label("api_usage_copy_btn", 'Copy'))
# Retranslate section titles and row labels
for attr in ["gui_gemini_translation_labels", "gui_gemini_ocr_labels", "gui_gemini_combined_labels"]:
if hasattr(self, f"{attr}_group"):
group = getattr(self, f"{attr}_group")
key = getattr(self, f"{attr}_group_key")
fallback = getattr(self, f"{attr}_group_fallback")
group.setTitle(lng.get_label(key, fallback))
if hasattr(self, f"{attr}_metadata"):
metadata = getattr(self, f"{attr}_metadata")
for row_label, lang_key, fallback in metadata:
row_label.setText(lng.get_label(lang_key, fallback))
if hasattr(self, 'grp_deepl_stats'):
self.grp_deepl_stats.setTitle(lng.get_label("api_usage_section_deepl", "📈 DeepL Usage Tracker"))
if hasattr(self, 'lbl_deepl_usage_title'):
self.lbl_deepl_usage_title.setText(lng.get_label("deepl_usage_label", "DeepL Usage:"))
if hasattr(self, 'lbl_api_usage_note'):
self.lbl_api_usage_note.setText(lng.get_label("api_usage_info_note",
"Note: Statistics are based on the short log files (e.g., Gemini_OCR_Short_Log.txt). Data will be reset if these files are deleted or cleared."))
self.refresh_stats()
# About Tab
if hasattr(self, 'grp_about'):
from constants import APP_VERSION, APP_RELEASE_DATE, APP_RELEASE_DATE_POLISH
rel_date = APP_RELEASE_DATE_POLISH if lng.current_lang == 'pol' else APP_RELEASE_DATE
clean_version = APP_VERSION.lstrip('v')
self.grp_about.setTitle(f"Game-Changing Translator v{clean_version}")
self.lbl_about_release.setText(f"{lng.get_label('released_label', 'Released')} {rel_date}")
self.lbl_about_copyright.setText(lng.get_label('copyright_label', 'Copyright © 2025-2026 Tomasz Kamiński'))
self.lbl_about_app_desc.setText(lng.get_label('about_app_description', 'Game-Changing Translator is a desktop application...'))
self.lbl_about_models_desc.setText(lng.get_label('about_description', 'This application was developed...'))
self.lbl_about_manual.setText(lng.get_label('about_info_manual', 'For more information, see the user manual.'))
self.lbl_about_tool_header.setText(lng.get_label('about_other_tool_header', 'Check my other tool:'))
ohlc_link = f"<a href='https://github.com/tomkam1702/OHLC-Forge' style='color: #2196F3; text-decoration: underline;'>OHLC Forge</a>"
ohlc_desc = lng.get_label('about_other_tool_desc', 'OHLC Forge – specialist tool...')
if ohlc_desc.startswith("OHLC Forge"):
if " – " in ohlc_desc: ohlc_desc = ohlc_desc.split(" – ", 1)[1]
elif " - " in ohlc_desc: ohlc_desc = ohlc_desc.split(" - ", 1)[1]
self.lbl_about_tool_desc.setText(f"{ohlc_link} - {ohlc_desc}")
self.check_updates_btn.setText(lng.get_label('check_for_updates_btn', 'Check for Updates'))
self.grp_pro.setTitle(f"Open-Source Edition")
# Status Label
if not self.translator.is_running:
self.status_label.setText(lng.get_label('status_ready', 'Status: Ready'))
else:
self.status_label.setText(lng.get_label('status_running', 'Running (Press ~ to Stop)'))
self.refresh_language_lists()
self.synchronize_combo_widths()
self.update_visibility_btns()
if not already_loading:
self._is_loading = False
def toggle_key_visibility(self, entry, btn):
if not self.translator: return
lng = self.translator.ui_lang
if entry.echoMode() == QLineEdit.Password:
entry.setEchoMode(QLineEdit.Normal)
btn.setText(lng.get_label('hide_btn', 'Hide'))
else:
entry.setEchoMode(QLineEdit.Password)
btn.setText(lng.get_label('show_btn', 'Show'))
def update_auto_detect_label(self, checked=None):
if not self.translator: return
lbl = self.translator.ui_lang.get_label('auto_detect_label', 'Find Subtitles')
self.lbl_auto_detect_text.setText(f'{lbl} <sup style="color: gray;">PRO</sup>')
is_on = self.auto_detect_check.isChecked()
if hasattr(self, 'discovery_timeout_spin'):
self.lbl_discovery_time.setVisible(is_on)
self.discovery_timeout_container.setVisible(is_on)
def update_capture_padding_label(self, checked=None):
if not self.translator: return
lbl = self.translator.ui_lang.get_label('capture_padding_label', 'Scan Wider')
self.lbl_capture_padding_text.setText(f'{lbl} <sup style="color: gray;">PRO</sup>')
is_on = self.capture_padding_check.isChecked()
if hasattr(self, 'capture_padding_container'):
self.capture_padding_container.setVisible(is_on)
if is_on:
suffix = self.translator.ui_lang.get_label('capture_padding_suffix', '%')
self.capture_padding_value_label.setText(suffix)
def update_target_on_source_label(self, checked=None):
if not self.translator: return
lbl = self.translator.ui_lang.get_label('target_on_source_label', 'Target Area on Source Area')
self.lbl_target_on_source_text.setText(f'{lbl} <sup style="color: gray;">PRO</sup>')
def update_info_tooltips(self):
if not self.translator: return
lng = self.translator.ui_lang
# All HelpButton tooltips are updated via the loop below
for btn in self.findChildren(HelpButton):
btn.update_tooltip()
def update_debug_log_label(self, checked=None):
if not self.translator: return
lbl_enable = self.translator.ui_lang.get_label('toggle_debug_log_enable_btn', 'Enable Debug Log')
self.debug_log_check.setText(lbl_enable)
def bind_auto_save(self):
self._auto_save_timer = QTimer(self)
self._auto_save_timer.setSingleShot(True)
self._auto_save_timer.timeout.connect(self.save_all_settings)
combos = [
self.translation_model_combo, self.ocr_model_combo, self.gemini_context_combo,
self.deepl_context_combo, self.source_lang_combo,
self.target_lang_combo, self.font_type_combo
]
for c in combos: c.currentIndexChanged.connect(self._on_setting_changed)
checks = [
self.auto_detect_check, self.target_on_source_check, self.keep_linebreaks_check,
self.deepl_cache_check, self.gemini_cache_check, self.debug_log_check,
self.custom_prompt_trans_enabled_check, self.custom_prompt_ocr_enabled_check,
self.capture_padding_check
]
for c in checks: c.toggled.connect(self._on_setting_changed)
spins = [
self.scan_interval_spin, self.clear_timeout_spin, self.discovery_timeout_spin,
self.font_size_spin, self.target_opacity_spin, self.target_text_opacity_spin,
self.capture_padding_spin
]
for s in spins: s.valueChanged.connect(self._on_setting_changed)
entries = [self.gemini_api_key_entry, self.deepl_api_key_entry]
for e in entries: e.editingFinished.connect(self._on_setting_changed)
# Immediate backend sync for language combos (no 500ms delay)
self.source_lang_combo.currentIndexChanged.connect(self._on_language_combo_changed)
self.target_lang_combo.currentIndexChanged.connect(self._on_language_combo_changed)
def _on_setting_changed(self, *args):
if getattr(self, '_is_loading', False): return
self._auto_save_timer.start(500) # 500ms debounce before automatic save
def _on_capture_padding_changed(self, value):
"""Update the displayed percentage label when capture padding spin changes."""
if self.translator:
suffix = self.translator.ui_lang.get_label('capture_padding_suffix', '%')
self.capture_padding_value_label.setText(suffix)
def _on_language_combo_changed(self):
"""Immediately sync language combo selections to backend and save to .ini."""
if getattr(self, '_is_loading', False) or not self.translator:
return
t = self.translator
is_deepl = (t.translation_model == 'deepl_api')
source_code = self.source_lang_combo.currentData()
target_code = self.target_lang_combo.currentData()
log_debug(f"_on_language_combo_changed: source_code={source_code!r}, target_code={target_code!r}, "
f"source_text={self.source_lang_combo.currentText()!r}, target_text={self.target_lang_combo.currentText()!r}, "
f"source_count={self.source_lang_combo.count()}, target_count={self.target_lang_combo.count()}, "
f"is_deepl={is_deepl}")
if source_code:
t.source_lang = source_code
if is_deepl:
t.deepl_source_lang = source_code
else:
t.gemini_source_lang = source_code
if target_code:
t.target_lang = target_code
if is_deepl:
t.deepl_target_lang = target_code
else:
t.gemini_target_lang = target_code
log_debug(f"_on_language_combo_changed: AFTER UPDATE -> gemini_source={t.gemini_source_lang!r}, gemini_target={t.gemini_target_lang!r}")
# Cancel pending debounce timer and save everything immediately
self._auto_save_timer.stop()
self.save_all_settings()
def set_translator(self, translator):
self.translator = translator
self.translator.gui = self
log_debug("Stage III: Backend connected to MainWindowV4")
self.font_type_combo.addItems(self.get_system_fonts())
if self.translator.GEMINI_API_AVAILABLE:
self.ocr_model_combo.clear()
self.ocr_model_combo.addItems(self.translator.gemini_models_manager.get_ocr_model_names())
self.translation_model_combo.clear()
if self.translator:
model_names = self.translator.gemini_models_manager.get_translation_model_names()
if "DeepL" not in model_names:
model_names.append("DeepL")
self.translation_model_combo.addItems(model_names)
else:
self.translation_model_combo.addItems(["Gemini 2.5 Flash-Lite", "DeepL"])
self.refresh_language_lists()
# Populate GUI language combo
self.gui_lang_combo.clear()
self.gui_lang_combo.addItems(self.translator.ui_lang.get_language_list())
self.retranslate_ui()
self.load_settings_to_ui()
self._is_loading = False # End of initialisation
def refresh_language_lists(self):
if not self.translator: return
already_loading = getattr(self, '_is_loading', False)
self._is_loading = True
lm = self.translator.language_manager
ui_lang_for_lookup = 'polish' if self.translator.ui_lang.current_lang == 'pol' else 'english'
current_text = self.translation_model_combo.currentText()
active_model = 'deepl' if current_text == 'DeepL' else 'gemini'
# Helper for sorting language pairs
def sort_pairs(pairs, ui_lang):
auto_pair = [p for p in pairs if p[1] == 'auto']
others = [p for p in pairs if p[1] != 'auto']
if ui_lang == 'polish':
others.sort(key=lambda x: lm._polish_sort_key(x[0]))
else:
others.sort(key=lambda x: x[0])
return auto_pair + others
# Source Languages
source_pairs = []
detect_lbl = self.translator.ui_lang.get_label('detect_language', '< Detect language >')
if active_model == 'deepl':
source_pairs = [(detect_lbl if code == 'auto' else lm.get_localized_language_name(code, 'deepl', ui_lang_for_lookup), code)
for _, code in lm.deepl_source_languages]
elif active_model == 'gemini':
source_pairs = [(detect_lbl if code == 'auto' else lm.get_localized_language_name(code, 'gemini', ui_lang_for_lookup), code)
for _, code in lm.gemini_source_languages]
source_pairs = sort_pairs(source_pairs, ui_lang_for_lookup)
self.source_lang_combo.clear()
for name, code in source_pairs:
self.source_lang_combo.addItem(name, code)
# Target Languages
target_pairs = []
if active_model == 'deepl':
target_pairs = [(lm.get_localized_language_name(code, 'deepl', ui_lang_for_lookup), code)
for _, code in lm.deepl_target_languages]
elif active_model == 'gemini':
target_pairs = [(lm.get_localized_language_name(code, 'gemini', ui_lang_for_lookup), code)
for _, code in lm.gemini_target_languages]
target_pairs = sort_pairs(target_pairs, ui_lang_for_lookup)
self.target_lang_combo.clear()
for name, code in target_pairs:
self.target_lang_combo.addItem(name, code)
self.synchronize_language_combo_widths()
if not already_loading:
self._is_loading = False
def on_translation_model_changed(self):
if not self.translator: return
already_loading = getattr(self, '_is_loading', False)
self._is_loading = True
current_text = self.translation_model_combo.currentText()
is_gemini = (current_text != 'DeepL')
self.refresh_language_lists()
ui_lang_lookup = 'polish' if self.translator.ui_lang.current_lang == 'pol' else 'english'
provider = 'gemini' if is_gemini else 'deepl'
saved_source_code = self.translator.gemini_source_lang if is_gemini else self.translator.deepl_source_lang
saved_target_code = self.translator.gemini_target_lang if is_gemini else self.translator.deepl_target_lang
idx_src = self.source_lang_combo.findData(saved_source_code)
if idx_src >= 0: self.source_lang_combo.setCurrentIndex(idx_src)
idx_tgt = self.target_lang_combo.findData(saved_target_code)
if idx_tgt >= 0: self.target_lang_combo.setCurrentIndex(idx_tgt)
if hasattr(self, 'models_form_layout'):
self.models_form_layout.setRowVisible(2, is_gemini) # Gemini Context
self.models_form_layout.setRowVisible(3, not is_gemini) # DeepL Context
self.synchronize_language_combo_widths()
if not already_loading:
self._is_loading = False
self._on_setting_changed()
def on_gui_language_changed(self):
if not self.translator or getattr(self, '_is_loading', False): return
new_lang_name = self.gui_lang_combo.currentText()
if not new_lang_name: return
lang_code = self.translator.ui_lang.get_language_code_from_name(new_lang_name)
if lang_code:
self._is_loading = True
try:
# Important: Update the backend setting BEFORE retranslation/reloading
self.translator.gui_language = new_lang_name
self.translator.ui_lang.load_language(lang_code)
self.retranslate_ui()
self.load_settings_to_ui() # Restore all selections from backend
self.translator.save_settings()
self.show_status(f"Language changed to {new_lang_name}", 3000)
finally:
self._is_loading = False
def on_config_mode_changed(self, index=0):
"""Handle Simple / Advanced mode toggle."""
if not self.translator or getattr(self, '_is_loading', False):
return
new_mode = 'Simple' if index == 0 else 'Advanced'
old_mode = self.translator.config_mode
if new_mode == old_mode:
return
self.translator.config_mode = new_mode
log_debug(f"Config mode changed: {old_mode} -> {new_mode}")
# Automatic transition: Show -> Hide when user manually switches Advanced -> Simple
if new_mode == 'Simple' and old_mode == 'Advanced' and self.translator.ui_visibility_mode == 'Show':
self.on_settings_btn_clicked() # Trigger visibility toggle to Hide
self._is_loading = True
try:
if new_mode == 'Simple':
self.translator.apply_simple_overrides()
else:
self.translator.reload_from_ini()
# Clear any pending color choices from the previous mode
self._pending_colors.clear()
self.load_settings_to_ui()
self.update_simple_mode_sensitivity()
# Sync live overlays to new mode's colors/opacity
t = self.translator
if t.source_overlay:
t.source_overlay.update_color(t.source_colour, 0.7)
if t.target_overlay:
t.target_overlay.update_color(t.target_colour, t.target_opacity)
t.target_overlay.update_text_color(t.target_text_colour)
# Save only the mode change (save_settings will skip locked keys)
self.translator.save_settings()
mode_label = self.translator.ui_lang.get_label(
'config_mode_simple' if new_mode == 'Simple' else 'config_mode_advanced',
new_mode
)
mode_prefix = self.translator.ui_lang.get_label('status_mode_prefix', 'Mode')
self.show_status(f"{mode_prefix}: {mode_label}", 2000)
finally:
self._is_loading = False
def on_top_visibility_btn_clicked(self):
"""Toggle Show / Hide mode for the top configuration area."""
if not self.translator or getattr(self, '_is_loading', False):
return
old_mode = getattr(self.translator, 'top_visibility_mode', 'Show')
new_mode = 'Hide' if old_mode == 'Show' else 'Show'
self.translator.top_visibility_mode = new_mode
log_debug(f"Top Visibility toggled: {old_mode} -> {new_mode}")
self.apply_top_visibility_settings(new_mode)
self.translator.save_settings()
def apply_top_visibility_settings(self, mode):
"""Apply Show/Hide logic to the top config widget."""
import os
import nuitka_compat