-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInktyping.py
More file actions
5649 lines (4313 loc) · 237 KB
/
Inktyping.py
File metadata and controls
5649 lines (4313 loc) · 237 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
# OS
import os
import sys
import argparse
import subprocess
import random
import shutil
import json
import datetime
import time
from send2trash import send2trash
from pathlib import Path
# Text stuff
import re
import inflect
from ebooklib import epub, ITEM_DOCUMENT
from bs4 import BeautifulSoup
import PyPDF2
import time
from html import escape
# PyQT
from PyQt5 import QtGui
from PyQt5.QtTest import QTest
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt, QEvent, QItemSelectionModel
from PyQt5.QtGui import QFont, QColor
from PyQt5 import QtCore, QtWidgets
import sip
# App
from main_window import Ui_MainWindow
from session_display import Ui_session_display
import resources_config_rc
class MainApp(QtWidgets.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None, show_main_window=False):
super().__init__(parent)
self.setupUi(self)
self.setWindowTitle('Sentence practice - Inktyping')
self.session_schedule = {}
# Install event filter
self.installEventFilter(self)
self.plural = inflect.engine()
# Disable tab focus for all widgets
for widget in self.findChildren(QtWidgets.QWidget):
widget.setFocusPolicy(QtCore.Qt.ClickFocus)
# Initialize label dictionaries
self.labels_color_dictionary = {"Default": "#00000000"}
self.preset_labels_dictionary = {}
# Define default shortcuts
self.default_shortcuts = {
"main_window": {
"start": "Return",
"close": "Escape",
"cycle_label": "\u00b2"
},
"session_window": {
"toggle_highlight": "G",
"toggle_text_field": "T",
"color_window": "F1",
"always_on_top": "A",
"prev_sentence": "Left",
"pause_timer": "Space",
"close": "Escape",
"next_sentence": "Right",
"open_folder": "O",
"copy_plain_text": "C",
"copy_plain_text_metadata": "Ctrl+Shift+C",
"copy_highlighted_text": "Ctrl+C",
"copy_highlighted_text_metadata": "Shift+C",
"toggle_autocopy": "F3",
"toggle_metadata": "F2",
"delete_sentence": "Ctrl+D",
"zoom_in": "Q",
"zoom_out": "D",
"zoom_in_numpad": "+",
"zoom_out_numpad": "-",
"show_main_window": "Tab",
"add_30_seconds": "Up",
"add_60_seconds": "Ctrl+Up",
"restart_timer": "Ctrl+Shift+Up"
}
}
# Use the executable's directory for absolute paths
if getattr(sys, 'frozen', False): # Check if the application is frozen (compiled as an EXE)
self.base_dir = os.path.dirname(sys.executable)
self.app_path = sys.executable
self.temp_dir = sys._MEIPASS
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.app_path = os.path.abspath(__file__)
self.temp_dir = None
self.presets_dir = os.path.join(self.base_dir, 'writing_presets')
self.text_presets_dir = os.path.join(self.presets_dir, 'text_presets')
self.session_presets_dir = os.path.join(self.presets_dir, 'session_presets')
self.theme_presets_dir = os.path.join(self.presets_dir, 'theme_presets') # New directory for themes
self.default_themes_dir = os.path.join(self.base_dir,'default_themes') # Default themes directory
self.rainmeter_presets_dir = os.path.join(self.presets_dir,'rainmeter_presets')
self.rainmeter_files_dir = os.path.join(self.base_dir,'rainmeter_files')
self.rainmeter_deleted_files_dir = os.path.join(self.rainmeter_presets_dir,'Deleted Files')
self.default_themes = ['default_theme.txt','dark_theme.txt', 'light_theme.txt']
self.current_theme = "default_theme.txt"
print('------------------')
print(' Base Directory:', self.base_dir)
print(' Temporary Directory:', self.temp_dir)
print(' Default Themes Directory:', self.default_themes_dir)
print(' Theme Presets Directory:', self.theme_presets_dir)
print(' Rainmeter Presets Directory:', self.rainmeter_presets_dir)
print(' Rainmeter Files Directory:', self.rainmeter_files_dir)
print(' Rainmeter Deleted Files Directory:', self.rainmeter_deleted_files_dir)
print('------------------')
self.create_directories()
self.ensure_default_themes()
# Initialize the randomize_settings variable or False depending on your default
self.randomize_settings = True
self.autocopy_settings = False
self.auto_start_settings = False
# Initialize cache variables
self.sentence_names_cache = []
self.session_names_cache = []
self.sentence_selection_cache = -1
self.session_selection_cache = -1
# Init color settings
self.color_settings = {}
# Load session settings at startup
self.load_session_settings()
self.init_buttons()
self.apply_shortcuts_main_window()
self.table_sentences_selection.setItem(0, 0, QTableWidgetItem('112'))
# Enable sorting on table headers
self.table_sentences_selection.setSortingEnabled(True)
self.table_session_selection.setSortingEnabled(True)
# Alternative method (ensures interactivity)
self.table_sentences_selection.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Interactive)
self.table_session_selection.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Interactive)
self.load_session_settings()
self.schedule = []
self.total_time = 0
self.selection = {'folders': [], 'files': []}
self.KEYWORDS_TYPES = {}
# Hide the main window initially
#self.setWindowFlags(QtCore.Qt.Window | QtCore.Qt.FramelessWindowHint)
self.display = None # Initialize with None
# Automatically start the session if auto_start is True
if self.auto_start_settings and show_main_window :
self.start_session_from_files()
# Show the main window if show_main_window is True
elif show_main_window == True:
self.show()
# Initialize position for dragging
self.oldPos = self.pos()
self.init_styles()
self.load_presets()
def init_message_boxes(self):
"""Initialize custom message box settings."""
self.message_box = QtWidgets.QMessageBox(self)
self.message_box.setIcon(QtWidgets.QMessageBox.NoIcon) # Set to no icon by default
def show_info_message(self, title, message):
"""Show an information message box without an icon."""
self.message_box.setWindowTitle(title)
self.message_box.setText(message)
self.message_box.exec_()
def ensure_default_themes(self):
"""Ensure default theme files are present in theme_presets_dir and replace any missing or corrupted files."""
self.current_theme = 'default_theme.txt'
# Determine the base directory based on whether the app is running as a PyInstaller bundle
if getattr(sys, 'frozen', False):
temp_dir = sys._MEIPASS
self.base_dir = os.path.dirname(sys.executable)
self.default_themes_dir = os.path.join(temp_dir, 'default_themes')
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.default_themes_dir = os.path.join(self.base_dir, 'default_themes')
# Ensure the theme presets directory exists
os.makedirs(self.theme_presets_dir, exist_ok=True)
for theme_file in self.default_themes:
source_file = os.path.join(self.default_themes_dir, theme_file)
destination_file = os.path.join(self.theme_presets_dir, theme_file)
# If the destination file does not exist, or it's corrupted, replace it with the default theme
if not os.path.exists(destination_file):
self.copy_theme_file(source_file, destination_file)
else:
try:
# Check if the existing file is readable and not corrupted
with open(destination_file, 'r') as dst:
content = dst.read()
if not content.strip():
print(f"{theme_file} is empty or corrupted. Replacing with default.")
self.copy_theme_file(source_file, destination_file)
except Exception as e:
print(f"Error reading {theme_file}: {e}. Replacing with default.")
self.copy_theme_file(source_file, destination_file)
def copy_theme_file(self, source_file, destination_file):
"""Copy a theme file from source to destination."""
if os.path.exists(source_file):
try:
with open(source_file, 'r') as src:
content = src.read()
with open(destination_file, 'w') as dst:
dst.write(content)
print(f"Copied {source_file} to {destination_file}")
except Exception as e:
print(f"Error copying {source_file} to {destination_file}: {e}")
else:
print(f"Source theme file {source_file} does not exist.")
def reset_default_themes(self):
"""Replace corrupted or missing theme files in theme_presets_dir with default ones."""
self.current_theme = 'default_theme.txt'
# Determine the base directory based on whether the app is running as a PyInstaller bundle
if getattr(sys, 'frozen', False):
temp_dir = sys._MEIPASS
self.base_dir = self.base_dir = os.path.dirname(sys.executable)
self.default_themes_dir = os.path.join(temp_dir, 'default_themes')
else:
self.base_dir = os.path.dirname(os.path.abspath(__file__))
self.default_themes_dir = os.path.join(self.base_dir, 'default_themes')
for theme_file in self.default_themes:
source_file = os.path.join(self.default_themes_dir, theme_file)
destination_file = os.path.join(self.theme_presets_dir, theme_file)
# Remove the existing file if it exists
if os.path.exists(destination_file):
os.remove(destination_file)
# Read from the source file and write to the destination file
if os.path.exists(source_file):
try:
with open(source_file, 'r') as src:
content = src.read()
with open(destination_file, 'w') as dst:
dst.write(content)
print(f"THEME RESTAURED : Replaced {theme_file} in {self.theme_presets_dir}")
self.init_styles()
except Exception as e:
print(f"Error copying {theme_file}: {e}")
else:
print(f"Source theme file {source_file} does not exist.")
self.show_info_message( 'Invalid theme', f'Invalid theme file, theme restaured to default.')
def showEvent(self, event):
"""Override showEvent to control window visibility."""
if not self.isVisible():
event.ignore() # Ignore the event to keep the window hidden
else:
super().showEvent(event) # Otherwise, handle normally
def init_buttons(self):
# Buttons for selection
self.add_folders_button.clicked.connect(self.create_preset)
self.delete_sentences_preset.clicked.connect(self.delete_sentences_files)
# Buttons for preset
self.save_session_presets_button.clicked.connect(self.save_session_presets)
self.delete_session_preset.clicked.connect(self.delete_presets_files)
self.open_preset_button.clicked.connect(self.open_preset)
# Buttons for rainmeter
self.rainmeter_preset_button.clicked.connect(self.create_rainmeter_preset)
# Start session button with tooltip
self.start_session_button.clicked.connect(self.start_session_launcher)
self.start_session_button.setToolTip(f"[{self.shortcut_settings['main_window']['start']}] Start the session.")
# Close window button with tooltip
self.close_window_button.clicked.connect(self.save_session_settings)
self.close_window_button.clicked.connect(self.close)
self.close_window_button.setToolTip(f"[{self.shortcut_settings['main_window']['close']}] Close the setting window.")
# Toggles
self.randomize_toggle.stateChanged.connect(self.update_randomize_settings)
self.autocopy_toggle.stateChanged.connect(self.update_autocopy_settings)
self.auto_start_toggle.stateChanged.connect(self.update_auto_start_settings)
# Table selection handlers
#self.table_sentences_selection.itemChanged.connect(self.rename_presets)
#self.table_session_selection.itemChanged.connect(self.rename_presets)
self.table_sentences_selection.itemChanged.connect(self.handle_preset_rename)
self.table_session_selection.itemChanged.connect(self.handle_preset_rename)
# Track editing state to prevent duplicate signals
self.currently_editing = False
self.current_edited_item = None
# Connect itemDoubleClicked to start tracking edits
self.table_sentences_selection.itemDoubleClicked.connect(self.start_edit_tracking)
self.table_session_selection.itemDoubleClicked.connect(self.start_edit_tracking)
# Install event filters to catch Return/Enter key
self.table_sentences_selection.installEventFilter(self)
self.table_session_selection.installEventFilter(self)
# Assuming these are your QTableWidget instances
self.table_sentences_selection.selectionModel().selectionChanged.connect(self.update_selection_cache)
self.table_session_selection.selectionModel().selectionChanged.connect(self.update_selection_cache)
# Theme selector button
self.theme_options_button.clicked.connect(self.open_theme_selector)
# Preset search
self.search_preset.textChanged.connect(self.filter_presets)
# Connect label options button
self.labels_options_button.clicked.connect(self.open_label_manager)
# Add context menu to table_sentences_selection
self.table_sentences_selection.setContextMenuPolicy(Qt.CustomContextMenu)
self.table_sentences_selection.customContextMenuRequested.connect(self.show_sentence_context_menu)
def show_sentence_context_menu(self, position):
"""Show context menu for the sentence table with direct label assignment options."""
selected_row = self.table_sentences_selection.currentRow()
if selected_row < 0:
return
file_item = self.table_sentences_selection.item(selected_row, 1) # Name column
if not file_item:
return
filename = file_item.text() + ".txt"
context_menu = QMenu(self)
# Add label options directly to the context menu
for label_name, color in sorted(self.labels_color_dictionary.items()):
action = context_menu.addAction(label_name)
pixmap = QtGui.QPixmap(16, 16)
pixmap.fill(QColor(color))
action.setIcon(QtGui.QIcon(pixmap))
# Check the current label
current_label = self.preset_labels_dictionary.get(filename, "Default")
if label_name == current_label:
action.setCheckable(True)
action.setChecked(True)
# Connect the action
action.triggered.connect(lambda checked, ln=label_name: self.assign_label(filename, ln))
# Show the menu
context_menu.exec_(self.table_sentences_selection.viewport().mapToGlobal(position))
def assign_label(self, filename, label_name):
"""Assign a label to a preset file."""
self.preset_labels_dictionary[filename] = label_name
self.save_session_settings()
# Update the UI
selected_row = self.table_sentences_selection.currentRow()
if selected_row >= 0:
color_item = self.table_sentences_selection.item(selected_row, 0)
if color_item:
color = self.labels_color_dictionary.get(label_name, "#00000000")
color_item.setBackground(QColor(color))
color_item.setToolTip(label_name)
def start_edit_tracking(self, item):
"""Called when double-clicking to edit an item"""
self.currently_editing = True
self.current_edited_item = item
self.original_text = item.text() # Store original value
def eventFilter(self, source, event):
"""Handle Return/Enter key press during editing"""
if (event.type() == QtCore.QEvent.KeyPress and
event.key() in (QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter) and
source.state() == QtWidgets.QAbstractItemView.EditingState):
# Force close the editor
source.closePersistentEditor(source.currentItem())
return True # Event handled
return super().eventFilter(source, event)
def handle_preset_rename(self, item):
"""Handle the actual renaming after edit completes"""
if not self.currently_editing or item != self.current_edited_item:
return
# Store these values before potentially modifying state
original_text = self.original_text
# Reset editing state BEFORE making changes
self.currently_editing = False
self.current_edited_item = None
# Only proceed if text actually changed
if item.text() != original_text:
if self.sender() == self.table_sentences_selection or self.sender() == self.table_session_selection:
# Pass success/failure back from rename_presets
success = self.rename_presets(item)
if not success:
# Set the text back to original without triggering events
self.blockSignals(True)
item.setText(original_text)
self.blockSignals(False)
def init_styles(self, dialog=None, dialog_color=None, session=None):
"""
Initialize custom styles for various UI elements including buttons, spin boxes,
table widgets, checkboxes, dialogs, and the main window. Optionally apply styles
to a specific dialog or session window.
"""
# Load the selected theme file
selected_theme_path = os.path.join(self.theme_presets_dir, self.current_theme)
print('NOW LOADING THEME : ',selected_theme_path)
if selected_theme_path:
try:
with open(selected_theme_path, 'r') as f:
theme_styles = f.read()
except FileNotFoundError:
print("No theme selected or theme file not found. Applying default styles.")
self.ensure_default_themes()
return
try:
# Parse theme styles as JSON
styles_dict = json.loads(theme_styles)
# Apply styles to each element based on the keys in the theme file
for element_group, element_styles in styles_dict.items():
# Split group of elements (comma-separated)
element_names = [name.strip() for name in element_group.split(',')]
for element_name in element_names:
if hasattr(self, element_name):
element = getattr(self, element_name)
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
element.setStyleSheet(style_sheet)
elif element_name == "MainWindow":
# Apply style directly to the MainWindow
style_sheet = ""
for selector, style in element_styles.items():
if selector == "window_icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
print(file_path)
self.setWindowIcon(QtGui.QIcon(file_path))
elif selector == "icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
self.label.setText(f"<html><head/><body><p><img src=\"{file_path}\"/></p></body></html>")
else:
style_sheet += f"{selector} {{{style}}}\n"
self.setStyleSheet(style_sheet)
self.init_message_boxes()
elif dialog and element_name == "dialog_styles":
# Apply styles to the dialog if it matches the name in the theme file
style_sheet = ""
style_sheet_header = ""
for selector, style in element_styles.items():
if selector == "QHeaderView::section":
style_sheet_header += f"{selector} {{{style}}}\n"
else:
style_sheet += f"{selector} {{{style}}}\n"
dialog.setStyleSheet(style_sheet)
if isinstance(dialog, LabelManagerDialog):
dialog.label_list.horizontalHeader().setStyleSheet(style_sheet_header)
elif "dictionary_controls" in styles_dict and dialog and isinstance(dialog, MultiFolderSelector):
style_dict = styles_dict["dictionary_controls"]
# Apply styles to checkboxes
if "checkbox" in style_dict:
style_sheet = ""
for selector, style in style_dict["checkbox"].items():
style_sheet += f"{selector} {{{style}}}\n"
for i in range(10): # 0-9 (including the ignored keywords)
checkbox = dialog.findChild(QtWidgets.QCheckBox, f"dictionary_checkbox_{i}")
if checkbox:
checkbox.setStyleSheet(style_sheet)
# Apply styles to labels
if "label" in style_dict:
style_sheet = ""
for selector, style in style_dict["label"].items():
style_sheet += f"{selector} {{{style}}}\n"
for i in range(10):
label = dialog.findChild(QtWidgets.QLabel, f"dictionary_label_{i}")
if label:
label.setStyleSheet(style_sheet)
# Apply styles to path edits
if "path_edit" in style_dict:
style_sheet = ""
for selector, style in style_dict["path_edit"].items():
style_sheet += f"{selector} {{{style}}}\n"
for i in range(10):
path_edit = dialog.findChild(QtWidgets.QLineEdit, f"dictionary_path_edit_{i}")
if path_edit:
path_edit.setStyleSheet(style_sheet)
# Apply styles to browse buttons
if "browse_button" in style_dict:
style_sheet = ""
for selector, style in style_dict["browse_button"].items():
style_sheet += f"{selector} {{{style}}}\n"
for i in range(10):
browse_button = dialog.findChild(QtWidgets.QPushButton, f"dictionary_browse_button_{i}")
if browse_button:
browse_button.setStyleSheet(style_sheet)
if "dictionary_container" in styles_dict and dialog and isinstance(dialog, MultiFolderSelector):
style_sheet = ""
for selector, style in styles_dict["dictionary_container"].items():
style_sheet += f"{selector} {{{style}}}\n"
dialog.dictionary_container.setStyleSheet(style_sheet)
# And for the content widget
if hasattr(dialog, 'dictionary_content'):
dialog.dictionary_content.setStyleSheet(style_sheet)
elif dialog_color and element_name == "ColorPickerDialog":
print(element_styles.items())
# Apply styles specifically to ColorPickerDialog
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
dialog_color.setStyleSheet(style_sheet)
elif session and element_name == "session_display":
# Apply style to session_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "window_icon":
if self.temp_dir :
file_path = os.path.join(self.temp_dir, style)
else:
file_path = os.path.join(self.base_dir, style)
session.setWindowIcon(QtGui.QIcon(file_path))
style_sheet += f"{style}\n"
session.setStyleSheet(style_sheet)
if "background:" not in session.styleSheet():
print('No background color')
session.setStyleSheet("background: rgb(0,0,0)")
elif element_name == "text_display":
if session:
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "text_color":
session.color_settings[selector]=style
elif "highlight_color_" in selector:
session.color_settings[selector] = style
elif selector == "always_on_top_border":
session.color_settings["always_on_top_border"]=style
elif "metadata_" in selector:
session.color_settings[selector]=style
else:
style_sheet += f"{selector} {{{style}}}\n"
if hasattr(session, 'text_display'):
session.text_display.setStyleSheet(style_sheet)
else:
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
if selector == "text_color":
self.color_settings[selector]=style
elif "highlight_color_" in selector:
self.color_settings[selector] = style
elif session and element_name == "lineEdit":
# Apply style to text_display if it matches the name in the theme file
style_sheet = ""
for selector, style in element_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
if hasattr(session, 'lineEdit'):
session.lineEdit.setStyleSheet(style_sheet)
elif session and element_name == "session_display_labels":
session_display_label_styles = styles_dict["session_display_labels"]
for label_name in ["session_info", "timer_display"]:
if hasattr(session, label_name):
label = getattr(session, label_name)
style_sheet = ""
for selector, style in session_display_label_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
label.setStyleSheet(style_sheet)
# Apply font settings to session labels only if specified
if session and "label_fonts" in styles_dict:
font_settings = styles_dict["label_fonts"]
font = QtGui.QFont()
font.setFamily(font_settings.get("family", "Arial"))
font.setPointSize(font_settings.get("size", 10))
font.setBold(font_settings.get("bold", False))
font.setItalic(font_settings.get("italic", False))
font.setWeight(font_settings.get("weight", 50))
# Apply font only to session labels
for label_name in ["session_info", "timer_display"]:
if hasattr(session, label_name):
label = getattr(session, label_name)
label.setFont(font)
# Apply common button styles to QPushButton widgets
if "common_button_styles" in styles_dict:
button_styles = styles_dict["common_button_styles"]
for button_name in ["theme_options_button","labels_options_button", "add_folders_button", "delete_sentences_preset", "open_preset_button","rainmeter_preset_button",
"delete_session_preset", "save_session_presets_button", "start_session_button", "close_window_button"]:
if hasattr(self, button_name):
button = getattr(self, button_name)
style_sheet = ""
for selector, style in button_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
button.setStyleSheet(style_sheet)
# Apply styles to other elements if needed
if "labels" in styles_dict:
label_styles = styles_dict["labels"]
for label_name in ["select_images", "label_7", "image_amount_label","sentence_amount_label", "duration_label", "label_5", "label_6"]:
if hasattr(self, label_name):
label = getattr(self, label_name)
style_sheet = ""
for selector, style in label_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
label.setStyleSheet(style_sheet)
if "common_spinbox_styles" in styles_dict:
spinbox_styles = styles_dict["common_spinbox_styles"]
for spinbox_name in ["set_seconds", "set_number_of_sentences", "set_minutes"]:
if hasattr(self, spinbox_name):
spinbox = getattr(self, spinbox_name)
style_sheet = ""
for selector, style in spinbox_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
spinbox.setStyleSheet(style_sheet)
if "common_checkbox_styles" in styles_dict:
checkbox_styles = styles_dict["common_checkbox_styles"]
style_sheet = ""
for selector, style in checkbox_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
# Assuming self has checkboxes that need styling
for checkbox_name in ["auto_start_toggle", "randomize_toggle","autocopy_toggle"]:
if hasattr(self, checkbox_name):
checkbox = getattr(self, checkbox_name)
checkbox.setStyleSheet(style_sheet)
if session and "session_buttons" in styles_dict:
button_styles = styles_dict["session_buttons"]
button_names = [
"grid_button", "toggle_highlight_button","color_text_button", "toggle_text_button",
"flip_horizontal_button", "flip_vertical_button",
"previous_sentence", "pause_timer", "stop_session",
"next_sentence", "copy_sentence_button", "clipboard_button","metadata_button",
"open_folder_button", "delete_sentence_button", "show_main_window_button"
]
for button_name in button_names:
if hasattr(session, button_name):
button = getattr(session, button_name)
style_sheet = ""
for selector, style in button_styles.items():
style_sheet += f"{selector} {{{style}}}\n"
button.setStyleSheet(style_sheet)
except json.JSONDecodeError:
print("Error parsing theme file. Applying default styles.")
self.reset_default_themes()
else:
print("No theme selected or theme file not found. Applying default styles.")
self.reset_default_themes()
def update_selection_cache(self):
"""Update the selected filename cache based on current table selections."""
# Only proceed if signals aren't blocked
if not self.table_sentences_selection.signalsBlocked() and not self.table_session_selection.signalsBlocked():
# print("-- updating cache --")
# Track sentence selection by filename
selected_row = self.table_sentences_selection.currentRow()
if selected_row >= 0:
name_item = self.table_sentences_selection.item(selected_row, 1) # Name column
if name_item:
# Store both filename and row number
self.selected_sentence_filename = name_item.text() + ".txt"
self.selected_sentence_row = selected_row
# Track session selection by filename
selected_row = self.table_session_selection.currentRow()
if selected_row >= 0:
name_item = self.table_session_selection.item(selected_row, 0) # Name column
if name_item:
# Store both filename and row number
self.selected_session_filename = name_item.text() + ".txt"
self.selected_session_row = selected_row
def filter_presets(self):
"""Filter table_sentences_selection based on search_preset input."""
search_text = self.search_preset.text().strip().lower()
for row in range(self.table_sentences_selection.rowCount()):
item = self.table_sentences_selection.item(row, 1) # Assuming filenames are in column 0
if item:
filename = item.text().lower()
self.table_sentences_selection.setRowHidden(row, search_text not in filename)
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Tab:
# Custom Tab key handling
if self.search_preset.hasFocus():
# Clear focus from all widgets
focused_widget = QtWidgets.QApplication.focusWidget()
if focused_widget:
focused_widget.clearFocus()
# Explicitly clear focus for the entire window
self.clearFocus()
else:
# Set focus to search_preset
self.search_preset.setFocus()
self.search_preset.selectAll()
# Prevent default Tab behavior
event.accept()
return
# Call the parent class's keyPressEvent for other key events
super().keyPressEvent(event)
def eventFilter(self, obj, event):
# Optionally keep your existing event filter logic
return super().eventFilter(obj, event)
########################################## TEXT PARSING ##########################################
########################################## TEXT PARSING ##########################################
########################################## TEXT PARSING ##########################################
def sanitize_filename(self, name):
"""Remove or replace characters invalid in Windows filenames."""
invalid_chars = '<>:"/\\|?*'
for ch in invalid_chars:
name = name.replace(ch, '_')
# Remove trailing dots and spaces
name = name.rstrip(' .')
return name.strip()
def create_preset(self, selected_files=None, keyword_profiles=None, preset_name=None, highlight_keywords=True,
output_option="Single output", max_length=200, metadata_settings=True, output_folder=None, is_gui=True, metadata_prefix=";;"):
"""
Opens a dialog for folder selection, collects keyword profiles, and processes all EPUB, PDF, and TXT files
within the selected folders using the chosen profiles. Combines results from all folders.
"""
# Start timer
self.load_presets()
if is_gui:
dialog = MultiFolderSelector(self, preset_name, text_presets_dir=self.text_presets_dir)
self.init_styles(dialog=dialog)
for child in dialog.findChildren(QtWidgets.QWidget):
child.style().unpolish(child)
child.style().polish(child)
if dialog.exec_() == QtWidgets.QDialog.Accepted:
selected_files = dialog.selected_files
highlight_keywords = dialog.highlight_keywords_checkbox.isChecked()
output_option = dialog.output_option_dropdown.currentText()
metadata_settings = dialog.extract_metadata_checkbox.isChecked()
append_mode = dialog.get_append_mode()
if preset_name == None:
if append_mode:
preset_name = dialog.selected_preset_name
else:
preset_name = dialog.preset_name_edit.text()
max_length = int(dialog.max_length_edit.text()) if dialog.max_length_edit.text().isdigit() else 200
keyword_profiles = dialog.get_all_keyword_profiles()
#print("keyword_profiles : ", keyword_profiles)
if not selected_files:
self.show_info_message('No Selection', 'No files were selected.')
return
else:
return
# Ensure we have directories to process
if not selected_files:
if is_gui:
self.show_info_message('No Selection', 'No folders were selected.')
return
# Dictionary to store all results
all_results = {}
total_sentences = 0 # Counter for total unique sentences
# Start timer
start_time = time.time()
folder_results = self.process_text_files(
file_paths=selected_files,
keyword_profiles=keyword_profiles,
highlight_keywords=highlight_keywords,
output_option=output_option,
preset_name=preset_name,
max_length=max_length,
metadata_settings=metadata_settings
)
# Merge results
for keyword, sentences in folder_results.items():
if keyword not in all_results:
all_results[keyword] = []
all_results[keyword].extend(sentences)
# Determine the output folder
target_folder = output_folder if output_folder else self.text_presets_dir
os.makedirs(target_folder, exist_ok=True)
# Create the combined output file and count unique sentences
combined_output_path = os.path.join(target_folder, f"{preset_name}.txt")
preset_name = self.sanitize_filename(preset_name)
combined_output_path = os.path.join(target_folder, f"{preset_name}.txt")
seen_sentences = set()
#Load existing sentences if in append mode
if is_gui and dialog.get_append_mode() and os.path.exists(combined_output_path):
try:
with open(combined_output_path, 'r', encoding='utf-8') as existing_file:
content = existing_file.read()
# Parse existing sentences to avoid duplicates
# Handle both metadata and non-metadata formats
blocks = content.split('\n\n')
for block in blocks:
block = block.strip()
if block:
try:
# Try parsing as metadata format first
entry = eval(block)
if isinstance(entry, list) and len(entry) == 2:
seen_sentences.add((entry[0].strip(), '')) # Add without filepath for comparison
except:
# Plain text format
seen_sentences.add((block, ''))
except Exception as e:
print(f"Error reading existing preset: {e}")
# Change 'w' to 'a' when in append mode