-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathui.py
More file actions
2412 lines (2184 loc) · 105 KB
/
Copy pathui.py
File metadata and controls
2412 lines (2184 loc) · 105 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
from PyQt6.QtWidgets import QMainWindow, QWidget, QVBoxLayout, QMenuBar, QFileDialog, QAbstractItemView, QMessageBox, QDialog, QHBoxLayout, QLabel, QLineEdit, QPushButton, QCheckBox, QGridLayout, QListWidget, QListWidgetItem, QTextEdit, QSplitter, QComboBox, QStyledItemDelegate, QInputDialog, QTreeWidget, QTreeWidgetItem, QTabWidget, QAbstractItemDelegate, QSpinBox, QDoubleSpinBox, QDateEdit, QTimeEdit, QDateTimeEdit, QApplication, QTableView, QColorDialog
from PyQt6.QtGui import QAction, QStandardItemModel, QStandardItem, QKeySequence, QColor, QBrush
from PyQt6.QtCore import Qt, QItemSelection, QByteArray, QEvent, QPersistentModelIndex
from file_parser import open_txt_file, detect_file_type, auto_detect_encoding, save_txt_file, check_for_working_version
import pandas as pd
from custom_widgets import CleanTableView
from column_letters import index_to_column_letters
from column_descriptions import get_description
from file_bindings import get_binding_manager, DataFileBinding
import copy
import os
import shutil
from datetime import datetime
import json
import re
import logging
from workspace_manager import WorkspaceManager
# Editor widget types for caching and performance optimization
EDITOR_WIDGET_TYPES = (QComboBox, QLineEdit, QSpinBox, QDoubleSpinBox, QDateEdit, QTimeEdit, QDateTimeEdit)
class ComboBoxDelegate(QStyledItemDelegate):
def __init__(self, parent=None, items=None):
super().__init__(parent)
self.items = items or []
def createEditor(self, parent, option, index):
# Parent the editor to the view's viewport to satisfy QAbstractItemView ownership checks
v = self.parent()
try:
parent_to_use = v.viewport() if (v is not None and hasattr(v, 'viewport')) else parent
except Exception as e:
logging.exception("Failed to set parent_to_use in ComboBoxDelegate.createEditor")
parent_to_use = parent
editor = QComboBox(parent_to_use)
editor.addItems(self.items)
editor.setEditable(True)
# Tag with persistent index for reliable manual commit
try:
editor.setProperty("_d2te_index", QPersistentModelIndex(index))
except Exception as e:
logging.exception("Failed to set _d2te_index property on editor in ComboBoxDelegate.createEditor")
# Debug info: name the editor for easier tracing
try:
# Get view ID if available for better tracking
view_id = getattr(v, '_view_id', 'unknown') if v else 'noview'
editor.setObjectName(f"ComboEditor_{view_id}_r{index.row()}_c{index.column()}")
cfg = getattr(v, 'config_manager', None)
debug_on = False
try:
debug_on = cfg.get_setting("debug_mode_enabled", False)
except Exception:
debug_on = False
if debug_on:
pname = parent_to_use.__class__.__name__
vname = getattr(v, 'objectName', lambda: '')() or repr(v)
# Also log the immediate parent chain for verification
chain = []
p = editor.parent()
steps = 0
while p is not None and steps < 6:
chain.append(p.__class__.__name__)
p = p.parent()
steps += 1
print(f"[DEBUG] createEditor -> {editor.objectName()} for view {vname} (parent widget={pname}); parent_chain={' > '.join(chain) if chain else 'None'}")
except Exception:
pass
return editor
def setEditorData(self, editor, index):
value = index.model().data(index, Qt.ItemDataRole.EditRole)
editor.setCurrentText(str(value))
def setModelData(self, editor, model, index):
value = editor.currentText()
model.setData(index, value, Qt.ItemDataRole.EditRole)
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
class UndoCommand:
"""Represents a single undoable action"""
def __init__(self, row, col, old_value, new_value):
self.row = row
self.col = col
self.old_value = old_value
self.new_value = new_value
class UndoStack:
"""Manages undo/redo operations with a maximum stack size"""
def __init__(self, max_size=10):
self.max_size = max_size
self.undo_stack = []
self.redo_stack = []
def push(self, command):
"""Add a new command to the undo stack"""
self.undo_stack.append(command)
self.redo_stack.clear()
if len(self.undo_stack) > self.max_size:
self.undo_stack.pop(0)
def can_undo(self):
return len(self.undo_stack) > 0
def can_redo(self):
return len(self.redo_stack) > 0
def undo(self):
"""Return the last command for undoing"""
if self.can_undo():
command = self.undo_stack.pop()
self.redo_stack.append(command)
return command
return None
def redo(self):
"""Return the last undone command for redoing"""
if self.can_redo():
command = self.redo_stack.pop()
self.undo_stack.append(command)
return command
return None
def clear(self):
"""Clear both stacks"""
self.undo_stack.clear()
self.redo_stack.clear()
class SearchReplaceDialog(QDialog):
"""Dialog for search and replace functionality"""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Search and Replace")
self.setModal(True)
self.resize(400, 150)
layout = QGridLayout()
layout.addWidget(QLabel("Search for:"), 0, 0)
self.search_input = QLineEdit()
layout.addWidget(self.search_input, 0, 1)
layout.addWidget(QLabel("Replace with:"), 1, 0)
self.replace_input = QLineEdit()
layout.addWidget(self.replace_input, 1, 1)
self.case_sensitive = QCheckBox("Case sensitive")
layout.addWidget(self.case_sensitive, 2, 0, 1, 2)
button_layout = QHBoxLayout()
self.find_next_btn = QPushButton("Find Next")
self.find_next_btn.clicked.connect(self.find_next)
button_layout.addWidget(self.find_next_btn)
self.replace_btn = QPushButton("Replace")
self.replace_btn.clicked.connect(self.replace_current)
button_layout.addWidget(self.replace_btn)
self.replace_all_btn = QPushButton("Replace All")
self.replace_all_btn.clicked.connect(self.replace_all)
button_layout.addWidget(self.replace_all_btn)
self.close_btn = QPushButton("Close")
self.close_btn.clicked.connect(self.close)
button_layout.addWidget(self.close_btn)
layout.addLayout(button_layout, 3, 0, 1, 2)
self.setLayout(layout)
self.parent_editor = parent
self.current_row = 0
self.current_col = 0
self.found_positions = []
self.current_find_index = -1
def find_next(self):
"""Find the next occurrence of the search term"""
search_term = self.search_input.text()
if not search_term:
return
case_sensitive = self.case_sensitive.isChecked()
model = self.parent_editor.tableView.model()
if not model:
return
start_row = self.current_row
start_col = self.current_col
found = False
for row in range(start_row, model.rowCount()):
start_column = start_col if row == start_row else 0
for col in range(start_column, model.columnCount()):
item = model.item(row, col)
if item:
cell_text = item.text()
if not case_sensitive:
cell_text = cell_text.lower()
search_term_check = search_term.lower()
else:
search_term_check = search_term
if search_term_check in cell_text:
self.current_row = row
self.current_col = col
index = model.index(row, col)
self.parent_editor.tableView.setCurrentIndex(index)
self.parent_editor.tableView.scrollTo(index)
self.current_col += 1
if self.current_col >= model.columnCount():
self.current_col = 0
self.current_row += 1
found = True
return
if start_row > 0 or start_col > 0:
self.current_row = 0
self.current_col = 0
self.find_next()
else:
QMessageBox.information(self, "Search", f"'{search_term}' not found.")
def replace_current(self):
"""Replace the currently selected cell if it contains the search term"""
search_term = self.search_input.text()
replace_term = self.replace_input.text()
if not search_term:
return
model = self.parent_editor.tableView.model()
current_index = self.parent_editor.tableView.currentIndex()
if current_index.isValid():
item = model.item(current_index.row(), current_index.column())
if item:
cell_text = item.text()
case_sensitive = self.case_sensitive.isChecked()
if not case_sensitive:
if search_term.lower() in cell_text.lower():
import re
new_text = re.sub(re.escape(search_term), replace_term, cell_text, flags=re.IGNORECASE)
item.setText(new_text)
else:
if search_term in cell_text:
new_text = cell_text.replace(search_term, replace_term)
item.setText(new_text)
def replace_all(self):
"""Replace all occurrences of the search term"""
search_term = self.search_input.text()
replace_term = self.replace_input.text()
if not search_term:
return
model = self.parent_editor.tableView.model()
if not model:
return
case_sensitive = self.case_sensitive.isChecked()
replace_count = 0
for row in range(model.rowCount()):
for col in range(model.columnCount()):
item = model.item(row, col)
if item:
cell_text = item.text()
original_text = cell_text
if not case_sensitive:
if search_term.lower() in cell_text.lower():
import re
cell_text = re.sub(re.escape(search_term), replace_term, cell_text, flags=re.IGNORECASE)
else:
if search_term in cell_text:
cell_text = cell_text.replace(search_term, replace_term)
if cell_text != original_text:
item.setText(cell_text)
replace_count += 1
if replace_count > 0:
QMessageBox.information(self, "Replace All", f"Replaced {replace_count} occurrence(s).")
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName("MainWindow")
self.centralWidget = QWidget(MainWindow)
self.centralWidget.setObjectName("centralWidget")
self.verticalLayout = QVBoxLayout(self.centralWidget)
self.verticalLayout.setObjectName("verticalLayout")
# Workspace splitter: left tree, right editor table
self.workspaceSplitter = QSplitter(Qt.Orientation.Horizontal, self.centralWidget)
self.workspaceSplitter.setObjectName("workspaceSplitter")
self.workspaceSplitter.setChildrenCollapsible(True)
self.workspaceTree = QTreeWidget(self.workspaceSplitter)
self.workspaceTree.setObjectName("workspaceTree")
self.workspaceTree.setHeaderLabel("Workspace")
self.workspaceTree.setRootIsDecorated(False)
self.workspaceTree.setAcceptDrops(True)
self.workspaceTree.viewport().setAcceptDrops(True)
self.workspaceTree.setDropIndicatorShown(True)
self.workspaceTree.setDragDropMode(QAbstractItemView.DragDropMode.DropOnly)
# Right side: tabbed editor area
self.editorTabs = QTabWidget(self.workspaceSplitter)
self.editorTabs.setObjectName("editorTabs")
self.editorTabs.setTabsClosable(True)
self.editorTabs.setMovable(True)
# Make editor stretch and set initial sizes
self.workspaceSplitter.setStretchFactor(0, 0)
self.workspaceSplitter.setStretchFactor(1, 1)
self.workspaceSplitter.setSizes([220, 780])
self.verticalLayout.addWidget(self.workspaceSplitter)
MainWindow.setCentralWidget(self.centralWidget)
self.menubar = QMenuBar(MainWindow)
self.menubar.setObjectName("menubar")
MainWindow.setMenuBar(self.menubar)
class BoundFileDialog(QDialog):
"""Dialog for selecting bound data files with metadata display."""
def __init__(self, parent=None):
super().__init__(parent)
self.selected_binding = None
self.init_ui()
self.populate_files()
def init_ui(self):
"""Initialize the dialog UI."""
self.setWindowTitle("Select Diablo II Data File")
self.setGeometry(200, 200, 800, 600)
layout = QVBoxLayout()
splitter = QSplitter(Qt.Orientation.Horizontal)
file_widget = QWidget()
file_layout = QVBoxLayout(file_widget)
file_label = QLabel("Available Data Files:")
file_layout.addWidget(file_label)
self.file_list = QListWidget()
self.file_list.currentItemChanged.connect(self.on_file_selected)
file_layout.addWidget(self.file_list)
metadata_widget = QWidget()
metadata_layout = QVBoxLayout(metadata_widget)
metadata_label = QLabel("File Information:")
metadata_layout.addWidget(metadata_label)
self.metadata_display = QTextEdit()
self.metadata_display.setReadOnly(True)
metadata_layout.addWidget(self.metadata_display)
splitter.addWidget(file_widget)
splitter.addWidget(metadata_widget)
splitter.setSizes([300, 500])
layout.addWidget(splitter)
button_layout = QHBoxLayout()
self.open_button = QPushButton("Open File")
self.open_button.clicked.connect(self.accept)
self.open_button.setEnabled(False)
cancel_button = QPushButton("Cancel")
cancel_button.clicked.connect(self.reject)
button_layout.addStretch()
button_layout.addWidget(self.open_button)
button_layout.addWidget(cancel_button)
layout.addLayout(button_layout)
self.setLayout(layout)
def populate_files(self):
"""Populate the file list with available bound files."""
binding_manager = get_binding_manager()
bindings = binding_manager.get_all_bindings()
for key, binding in sorted(bindings.items()):
display_name = f"{binding.base_name} ({os.path.basename(binding.txt_path)})"
item = QListWidgetItem(display_name)
item.setData(Qt.ItemDataRole.UserRole, binding)
self.file_list.addItem(item)
def on_file_selected(self, current, previous):
"""Handle file selection change."""
if current:
self.selected_binding = current.data(Qt.ItemDataRole.UserRole)
self.open_button.setEnabled(True)
self.update_metadata_display()
else:
self.selected_binding = None
self.open_button.setEnabled(False)
self.metadata_display.clear()
def update_metadata_display(self):
"""Update the metadata display with information about the selected file."""
if not self.selected_binding:
return
binding = self.selected_binding
metadata = binding.metadata
display_text = f"<h3>{binding.base_name}</h3>"
display_text += f"<p><strong>Data File:</strong> {os.path.basename(binding.txt_path)}</p>"
display_text += f"<p><strong>Metadata File:</strong> {os.path.basename(binding.json_path)}</p>"
description = binding.get_description()
if description and description != "No description available":
display_text += f"<p><strong>Description:</strong><br>{description}</p>"
column_descriptions = binding.get_column_descriptions()
if column_descriptions:
display_text += f"<p><strong>Columns ({len(column_descriptions)}):</strong></p>"
display_text += "<ul>"
for col_name, col_desc in list(column_descriptions.items())[:10]:
display_text += f"<li><strong>{col_name}:</strong> {col_desc}</li>"
if len(column_descriptions) > 10:
display_text += f"<li><em>... and {len(column_descriptions) - 10} more columns</em></li>"
display_text += "</ul>"
self.metadata_display.setHtml(display_text)
from config_manager import ConfigManager
class SettingsDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Settings")
self.setModal(True)
self.config_manager = ConfigManager()
layout = QVBoxLayout()
self.multi_column_selection_checkbox = QCheckBox("Enable multi-column selection")
self.multi_column_selection_checkbox.setChecked(self.config_manager.get_setting("multi_column_selection_enabled", False))
layout.addWidget(self.multi_column_selection_checkbox)
self.ignore_empty_cells_checkbox = QCheckBox("Ignore empty cells on column select")
self.ignore_empty_cells_checkbox.setChecked(self.config_manager.get_setting("ignore_empty_cells_on_column_select", False))
layout.addWidget(self.ignore_empty_cells_checkbox)
self.multi_column_select_all_checkbox = QCheckBox("Enable multi-column select all (Ctrl+R)")
self.multi_column_select_all_checkbox.setChecked(self.config_manager.get_setting("multi_column_select_all_enabled", False))
layout.addWidget(self.multi_column_select_all_checkbox)
self.show_row_numbers_checkbox = QCheckBox("Show row numbers on frozen column")
self.show_row_numbers_checkbox.setChecked(self.config_manager.get_setting("show_row_numbers_on_frozen_column", False))
layout.addWidget(self.show_row_numbers_checkbox)
# Add the new checkbox for freezing the first row
# self.freeze_first_row_checkbox = QCheckBox("Enable freezing the first row")
# self.freeze_first_row_checkbox.setChecked(self.config_manager.get_setting("freeze_first_row_enabled", False))
# layout.addWidget(self.freeze_first_row_checkbox)
self.debug_mode_checkbox = QCheckBox("Enable Debug Mode")
self.debug_mode_checkbox.setChecked(self.config_manager.get_setting("debug_mode_enabled", False))
layout.addWidget(self.debug_mode_checkbox)
# Crosshair guides settings
self.crosshair_enabled_checkbox = QCheckBox("Enable crosshair guides (row/column lines)")
self.crosshair_enabled_checkbox.setChecked(self.config_manager.get_setting("crosshair_enabled", True))
layout.addWidget(self.crosshair_enabled_checkbox)
self.crosshair_hover_checkbox = QCheckBox("Crosshair follows mouse hover")
self.crosshair_hover_checkbox.setChecked(self.config_manager.get_setting("crosshair_hover_enabled", True))
layout.addWidget(self.crosshair_hover_checkbox)
crosshair_row = QHBoxLayout()
crosshair_row.addWidget(QLabel("Crosshair thickness (px):"))
self.crosshair_thickness_input = QLineEdit(str(self.config_manager.get_setting("crosshair_thickness", 1)))
self.crosshair_thickness_input.setPlaceholderText("e.g. 1-6")
self.crosshair_thickness_input.setMaximumWidth(80)
crosshair_row.addWidget(self.crosshair_thickness_input)
crosshair_row.addStretch(1)
layout.addLayout(crosshair_row)
# Column letters option
self.show_column_letters_checkbox = QCheckBox("Show column letters (A, B, C)")
self.show_column_letters_checkbox.setChecked(self.config_manager.get_setting("show_column_letters_enabled", True))
layout.addWidget(self.show_column_letters_checkbox)
# Header minimum width setting
header_min_row = QHBoxLayout()
header_min_row.addWidget(QLabel("Header minimum width (px):"))
try:
header_min = int(self.config_manager.get_setting("header_min_section_size", 40) or 40)
except Exception:
header_min = 40
self.header_min_width_input = QLineEdit(str(max(10, min(1000, header_min))))
self.header_min_width_input.setPlaceholderText("e.g. 20-1000")
self.header_min_width_input.setMaximumWidth(100)
header_min_row.addWidget(self.header_min_width_input)
header_min_row.addStretch(1)
layout.addLayout(header_min_row)
# Column colors feature controls
layout.addWidget(QLabel("Column colors"))
self.enable_column_colors_checkbox = QCheckBox("Enable column colors (global by column name)")
try:
self.enable_column_colors_checkbox.setChecked(bool(self.config_manager.get_setting("enable_column_colors", True)))
except Exception:
self.enable_column_colors_checkbox.setChecked(True)
layout.addWidget(self.enable_column_colors_checkbox)
# High contrast text option for colored columns
self.high_contrast_text_checkbox = QCheckBox("High-contrast text on colored columns")
try:
self.high_contrast_text_checkbox.setChecked(bool(self.config_manager.get_setting("high_contrast_column_text_enabled", True)))
except Exception:
self.high_contrast_text_checkbox.setChecked(True)
layout.addWidget(self.high_contrast_text_checkbox)
# Custom palette manager (MRU list of hex colors)
palette_row = QVBoxLayout()
palette_row.addWidget(QLabel("Custom palette (most recently used):"))
self.palette_list = QListWidget()
try:
self._palette = list(self.config_manager.get_setting("custom_column_color_palette", []) or [])
except Exception:
self._palette = []
self._update_palette_list()
palette_row.addWidget(self.palette_list)
palette_buttons = QHBoxLayout()
self.palette_add_btn = QPushButton("Add…")
self.palette_add_btn.clicked.connect(self._palette_add_clicked)
palette_buttons.addWidget(self.palette_add_btn)
self.palette_remove_btn = QPushButton("Remove")
self.palette_remove_btn.clicked.connect(self._palette_remove_clicked)
palette_buttons.addWidget(self.palette_remove_btn)
self.palette_reset_btn = QPushButton("Reset")
self.palette_reset_btn.clicked.connect(self._palette_reset_clicked)
palette_buttons.addWidget(self.palette_reset_btn)
palette_buttons.addStretch(1)
palette_row.addLayout(palette_buttons)
layout.addLayout(palette_row)
button_layout = QHBoxLayout()
self.save_button = QPushButton("Save")
self.save_button.clicked.connect(self.save_settings)
button_layout.addWidget(self.save_button)
self.cancel_button = QPushButton("Cancel")
self.cancel_button.clicked.connect(self.reject)
button_layout.addWidget(self.cancel_button)
layout.addLayout(button_layout)
self.setLayout(layout)
def save_settings(self):
self.config_manager.set_setting("multi_column_selection_enabled", self.multi_column_selection_checkbox.isChecked())
self.config_manager.set_setting("ignore_empty_cells_on_column_select", self.ignore_empty_cells_checkbox.isChecked())
self.config_manager.set_setting("multi_column_select_all_enabled", self.multi_column_select_all_checkbox.isChecked())
self.config_manager.set_setting("show_row_numbers_on_frozen_column", self.show_row_numbers_checkbox.isChecked())
# Save the new setting
#self.config_manager.set_setting("freeze_first_row_enabled", self.freeze_first_row_checkbox.isChecked())
self.config_manager.set_setting("debug_mode_enabled", self.debug_mode_checkbox.isChecked())
# Crosshair settings
self.config_manager.set_setting("crosshair_enabled", self.crosshair_enabled_checkbox.isChecked())
self.config_manager.set_setting("crosshair_hover_enabled", self.crosshair_hover_checkbox.isChecked())
try:
thickness = int(self.crosshair_thickness_input.text())
except Exception:
thickness = 1
thickness = max(1, min(6, thickness))
self.config_manager.set_setting("crosshair_thickness", thickness)
# Column letters
self.config_manager.set_setting("show_column_letters_enabled", self.show_column_letters_checkbox.isChecked())
# Header min width
try:
header_min = int(self.header_min_width_input.text())
except Exception:
header_min = 40
header_min = max(10, min(1000, header_min))
try:
self.config_manager.set_setting("header_min_section_size", header_min)
except Exception:
pass
try:
self.config_manager.set_setting("enable_column_colors", bool(self.enable_column_colors_checkbox.isChecked()))
except Exception:
pass
try:
self.config_manager.set_setting("high_contrast_column_text_enabled", bool(self.high_contrast_text_checkbox.isChecked()))
except Exception:
pass
try:
# Persist MRU palette order
self.config_manager.set_setting("custom_column_color_palette", list(self._palette))
except Exception:
pass
# Apply to current view immediately if available
try:
parent = self.parent()
tv = getattr(parent, 'tableView', None)
if tv:
# Rebuild colors/text
if hasattr(tv, 'rebuild_column_color_map_from_config'):
tv.rebuild_column_color_map_from_config()
# Apply header min width to all relevant headers
try:
hh = tv.horizontalHeader()
if hh:
hh.setMinimumSectionSize(int(header_min))
except Exception:
pass
try:
fhh = getattr(tv.frozen_row_view, 'horizontalHeader', None)
if callable(fhh):
fhh().setMinimumSectionSize(int(header_min))
except Exception:
pass
except Exception:
pass
self.accept()
def _best_foreground_for_hex(self, hex_color: str) -> QColor:
try:
c = QColor(hex_color)
if not c.isValid():
return QColor("#000000")
# Perceived luminance
r, g, b = c.red(), c.green(), c.blue()
lum = 0.299 * r + 0.587 * g + 0.114 * b
return QColor("#000000") if lum > 186 else QColor("#ffffff")
except Exception:
return QColor("#000000")
def _update_palette_list(self):
try:
self.palette_list.clear()
for hexc in self._palette:
item = QListWidgetItem(str(hexc))
try:
bg = QBrush(QColor(hexc))
fg = QBrush(self._best_foreground_for_hex(hexc))
item.setBackground(bg)
item.setForeground(fg)
except Exception:
pass
self.palette_list.addItem(item)
except Exception:
pass
def _palette_add_clicked(self):
try:
chosen = QColorDialog.getColor(QColor("#ffffff"), self, "Add Custom Color")
if chosen.isValid():
hexc = chosen.name()
# MRU insert
self._palette = [c for c in self._palette if str(c).lower() != hexc.lower()]
self._palette.insert(0, hexc)
# Cap list length
if len(self._palette) > 12:
self._palette = self._palette[:12]
self._update_palette_list()
except Exception:
pass
def _palette_remove_clicked(self):
try:
rows = sorted({i.row() for i in self.palette_list.selectedIndexes()}, reverse=True)
if not rows:
return
for r in rows:
if 0 <= r < len(self._palette):
del self._palette[r]
self._update_palette_list()
except Exception:
pass
def _palette_reset_clicked(self):
try:
self._palette = []
self._update_palette_list()
except Exception:
pass
class EditorWindow(QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(EditorWindow, self).__init__(parent)
self.setupUi(self)
self.data_frame = None
self.current_file_path = None
self.current_binding = None
self.undo_stack = UndoStack()
self._tracking_changes = True
self.config_manager = ConfigManager()
self.unique_column_values = {}
# Persisted workspace file list
try:
self.workspace_files = list(self.config_manager.get_setting("workspace_files", []))
except Exception:
self.workspace_files = []
# Open files tracking: map file path -> DataFileBinding
self.open_files = {}
# Optional in-memory cache of dataframes to avoid re-reading from disk
self._file_data_cache = {}
self.load_unique_column_values()
self.create_menus()
self.apply_initial_settings()
self.update_window_title()
self.workspace_manager = WorkspaceManager()
# Tab management
self._tabs = {} # path -> CleanTableView
self._current_tab_index = -1
# View caching for performance optimization
self._all_views_cache = []
self.editorTabs.currentChanged.connect(self.on_tab_changed)
self.editorTabs.tabCloseRequested.connect(self.on_tab_close)
try:
self.editorTabs.tabBar().tabBarClicked.connect(self.on_tab_bar_clicked)
except Exception:
pass
# Populate workspace panel and hook activation
try:
self.populate_workspace_tree()
self.workspaceTree.itemActivated.connect(self.load_workspace_item)
self.workspaceTree.installEventFilter(self)
except Exception:
pass
# Honour configurable undo depth
try:
self.undo_stack.max_size = int(self.config_manager.get_setting("undo_stack_max_size", 10) or 10)
except Exception:
self.undo_stack.max_size = 10
# Enable drag-and-drop opening of .txt files
self.setAcceptDrops(True)
def debug_print(self, *args):
try:
if self.config_manager.get_setting("debug_mode_enabled", False):
print("[DEBUG]", *args)
except Exception:
pass
def create_menus(self):
# File Menu
file_menu = self.menubar.addMenu("&File")
open_action = QAction("&Open...", self)
open_action.setShortcut(QKeySequence.StandardKey.Open)
open_action.triggered.connect(self.open_file)
file_menu.addAction(open_action)
open_bound_action = QAction("Open &Bound File...", self)
open_bound_action.setShortcut(QKeySequence("Ctrl+B"))
open_bound_action.triggered.connect(self.open_bound_file)
file_menu.addAction(open_bound_action)
save_action = QAction("&Save", self)
save_action.setShortcut(QKeySequence.StandardKey.Save)
save_action.triggered.connect(self.save_file)
file_menu.addAction(save_action)
save_as_action = QAction("Save &As...", self)
save_as_action.setShortcut(QKeySequence.StandardKey.SaveAs)
save_as_action.triggered.connect(self.save_file_as)
file_menu.addAction(save_as_action)
# Edit Menu
edit_menu = self.menubar.addMenu("&Edit")
undo_action = QAction("&Undo", self)
undo_action.setShortcut(QKeySequence.StandardKey.Undo)
undo_action.triggered.connect(self.undo)
edit_menu.addAction(undo_action)
redo_action = QAction("&Redo", self)
redo_action.setShortcut(QKeySequence.StandardKey.Redo)
redo_action.triggered.connect(self.redo)
edit_menu.addAction(redo_action)
edit_menu.addSeparator()
find_replace_action = QAction("&Find && Replace...", self)
find_replace_action.setShortcut(QKeySequence.StandardKey.Find)
find_replace_action.triggered.connect(self.show_search_replace)
edit_menu.addAction(find_replace_action)
edit_menu.addSeparator()
copy_action = QAction("&Copy", self)
copy_action.setShortcut(QKeySequence.StandardKey.Copy)
copy_action.triggered.connect(self.copy_selection)
edit_menu.addAction(copy_action)
cut_action = QAction("Cu&t", self)
cut_action.setShortcut(QKeySequence.StandardKey.Cut)
cut_action.triggered.connect(self.cut_selection)
edit_menu.addAction(cut_action)
paste_action = QAction("&Paste", self)
paste_action.setShortcut(QKeySequence.StandardKey.Paste)
paste_action.triggered.connect(self.paste_selection)
edit_menu.addAction(paste_action)
edit_menu.addSeparator()
clear_action = QAction("&Clear Contents", self)
clear_action.setShortcut(QKeySequence.StandardKey.Delete)
clear_action.triggered.connect(self.clear_selection)
edit_menu.addAction(clear_action)
select_all_action = QAction("Select &All", self)
select_all_action.setShortcut(QKeySequence.StandardKey.SelectAll)
select_all_action.triggered.connect(self.select_all)
edit_menu.addAction(select_all_action)
# View Menu
view_menu = self.menubar.addMenu("&View")
self.freeze_col_action = QAction("Freeze First Column", self, checkable=True)
self.freeze_col_action.triggered.connect(self.toggle_freeze_first_column)
view_menu.addAction(self.freeze_col_action)
# Show column letters toggle
self.show_letters_action = QAction("Show Column Letters (A, B, C)", self, checkable=True)
try:
self.show_letters_action.setChecked(bool(self.config_manager.get_setting("show_column_letters_enabled", True)))
except Exception:
self.show_letters_action.setChecked(True)
self.show_letters_action.triggered.connect(self.toggle_show_column_letters)
view_menu.addAction(self.show_letters_action)
#self.freeze_row_action = QAction("Freeze First Row", self, checkable=True)
#self.freeze_row_action.triggered.connect(self.toggle_freeze_first_row)
#view_menu.addAction(self.freeze_row_action)
# Settings Menu
settings_menu = self.menubar.addMenu("&Settings")
settings_action = QAction("&Settings...", self)
settings_action.triggered.connect(self.show_settings)
settings_menu.addAction(settings_action)
# Workspace Menu
workspace_menu = self.menubar.addMenu("&Workspace")
ws_save_action = QAction("&Save Workspace...", self)
ws_save_action.setShortcut(QKeySequence("Ctrl+Shift+S"))
ws_save_action.triggered.connect(self.action_save_workspace)
workspace_menu.addAction(ws_save_action)
ws_load_action = QAction("&Load Workspace...", self)
ws_load_action.setShortcut(QKeySequence("Ctrl+Shift+O"))
ws_load_action.triggered.connect(self.action_load_workspace)
workspace_menu.addAction(ws_load_action)
ws_delete_action = QAction("&Delete Workspace...", self)
ws_delete_action.triggered.connect(self.action_delete_workspace)
workspace_menu.addAction(ws_delete_action)
workspace_menu.addSeparator()
ws_add_file_action = QAction("&Add File to Panel...", self)
ws_add_file_action.setShortcut(QKeySequence("Ctrl+Shift+A"))
ws_add_file_action.triggered.connect(self.add_file_to_workspace_panel)
workspace_menu.addAction(ws_add_file_action)
ws_remove_file_action = QAction("&Remove Selected from Panel", self)
ws_remove_file_action.setShortcut(QKeySequence("Del"))
ws_remove_file_action.triggered.connect(self.remove_selected_from_workspace_panel)
workspace_menu.addAction(ws_remove_file_action)
def apply_initial_settings(self):
"""Loads and applies settings from the config manager on startup."""
if not hasattr(self, 'tableView') or self.tableView is None:
return
# Freeze Column Setting
freeze_col = self.config_manager.get_setting("freeze_first_column_enabled", False)
self.freeze_col_action.setChecked(freeze_col)
self.tableView.set_first_column_frozen(freeze_col)
# Freeze Row Setting
# freeze_row = self.config_manager.get_setting("freeze_first_row_enabled", False)
#self.freeze_row_action.setChecked(freeze_row)
#self.tableView.set_first_row_frozen(freeze_row)
# Crosshair guides
crosshair_enabled = self.config_manager.get_setting("crosshair_enabled", True)
self.tableView.setCrosshairGuidesEnabled(bool(crosshair_enabled))
crosshair_hover = self.config_manager.get_setting("crosshair_hover_enabled", True)
try:
self.tableView.setCrosshairHoverEnabled(bool(crosshair_hover))
except Exception:
pass
try:
crosshair_width = int(self.config_manager.get_setting("crosshair_thickness", 1) or 1)
except Exception:
crosshair_width = 1
self.tableView.setCrosshairWidth(max(1, min(6, crosshair_width)))
# Also sync header outline thickness on custom headers
try:
hh = self.tableView.horizontalHeader()
vh = self.tableView.verticalHeader()
if hasattr(hh, 'setCrosshairStyle'):
hh.setCrosshairStyle(border_width=max(1, min(6, crosshair_width)))
if hasattr(vh, 'setCrosshairStyle'):
vh.setCrosshairStyle(border_width=max(1, min(6, crosshair_width)))
except Exception:
pass
# Column letters: trigger header repaint to reflect setting
try:
if hasattr(self, 'show_letters_action'):
self.show_letters_action.setChecked(bool(self.config_manager.get_setting("show_column_letters_enabled", True)))
# Current view header
self.tableView.horizontalHeader().viewport().update()
# Frozen column header if visible
fhh = getattr(self.tableView.frozen_column_view, 'horizontalHeader', None)
if callable(fhh):
fhh().viewport().update()
except Exception:
pass
# Header minimum width
try:
header_min = int(self.config_manager.get_setting("header_min_section_size", 40) or 40)
except Exception:
header_min = 40
header_min = max(10, min(1000, header_min))
try:
hh = self.tableView.horizontalHeader()
if hh:
hh.setMinimumSectionSize(int(header_min))
except Exception:
pass
try:
fhh2 = getattr(self.tableView.frozen_row_view, 'horizontalHeader', None)
if callable(fhh2):
fhh2().setMinimumSectionSize(int(header_min))
except Exception:
pass
def toggle_freeze_first_column(self, frozen):
"""Handles the 'Freeze First Column' menu action."""
if self.data_frame is None or self.data_frame.shape[1] == 0:
self.freeze_col_action.setChecked(False)
return
self.tableView.set_first_column_frozen(frozen)
self.config_manager.set_setting("freeze_first_column_enabled", frozen)
print(f"Freeze first column {'enabled' if frozen else 'disabled'}.")
def toggle_freeze_first_row(self, frozen):
return
# """Handles the 'Freeze First Row' menu action."""
# if self.data_frame is None or self.data_frame.shape[0] == 0:
# self.freeze_row_action.setChecked(False)
# return
#self.tableView.set_first_row_frozen(frozen)
#self.config_manager.set_setting("freeze_first_row_enabled", frozen)
#print(f"Freeze first row {'enabled' if frozen else 'disabled'}.")
def toggle_show_column_letters(self, enabled: bool):
try:
self.config_manager.set_setting("show_column_letters_enabled", bool(enabled))
except Exception:
pass
# Force header repaint on current view
try:
if hasattr(self, 'tableView') and self.tableView is not None:
self.tableView.horizontalHeader().viewport().update()
fhh = getattr(self.tableView.frozen_column_view, 'horizontalHeader', None)
if callable(fhh):
fhh().viewport().update()
except Exception:
pass
# --- Workspace helpers ---
def _capture_table_state(self):
tv = getattr(self, 'tableView', None)
if not tv:
return {}
# Column widths - use compact representation when possible
try:
header = tv.horizontalHeader()
col_count = tv.model().columnCount() if tv.model() else 0
# First, collect all widths
raw_widths = []
for i in range(col_count):
raw_widths.append(header.sectionSize(i))
# Check if we can use a compact representation
if len(raw_widths) > 3:
# Group by width for compression
width_groups = {}
for i, width in enumerate(raw_widths):
if width not in width_groups:
width_groups[width] = []
width_groups[width].append(i)
# If we have large groups of the same width, use compact format
if len(width_groups) <= len(raw_widths) // 3:
compact_widths = []
for width, indices in width_groups.items():
# Sort indices to identify consecutive ranges