-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy patheverything.py
More file actions
6324 lines (5477 loc) · 253 KB
/
Copy patheverything.py
File metadata and controls
6324 lines (5477 loc) · 253 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
# Copyright 2025 Apple Dragon
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import os
import stat
import json
import subprocess
import time
import csv
import shutil
import zipfile
import traceback
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from pathlib import Path
from PyQt6.QtWidgets import (
QApplication, QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, QLabel, QLineEdit,
QCheckBox, QPushButton, QTreeWidget, QTreeWidgetItem, QProgressBar, QMenu,
QFileDialog, QMessageBox, QGroupBox, QInputDialog, QPlainTextEdit, QSplitter, QStackedWidget, QCompleter,
QSlider, QToolButton, QStyle, QGraphicsDropShadowEffect, QTabWidget, QDialog, QRadioButton, QButtonGroup,
QProgressDialog, QStyledItemDelegate
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer, QUrl, QMimeData, QPropertyAnimation, QEasingCurve, QMargins
from PyQt6.QtGui import QActionGroup, QBrush
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
from PyQt6.QtMultimediaWidgets import QVideoWidget
from PyQt6.QtGui import QPixmap, QMovie, QPainter, QFont, QColor, QPen, QLinearGradient, QGradient
from PyQt6.QtCore import QRectF, QEvent
from PyQt6.QtSvg import QSvgRenderer
from PyQt6.QtCharts import (
QChart,
QChartView,
QBarSet,
QHorizontalBarSeries,
QBarCategoryAxis,
QValueAxis,
)
CONFIG_PATH = os.path.expanduser("~/.everythingByMdfind.json")
DEBOUNCE_DELAY = 800
def read_config():
if not os.path.isfile(CONFIG_PATH):
return {}
try:
with open(CONFIG_PATH, "r", encoding="utf-8") as f:
return json.load(f)
except (OSError, ValueError) as exc:
# ValueError covers json.JSONDecodeError (corrupt file); fall back to
# defaults rather than crashing, but make the reason visible.
print(f"Failed to read config: {exc}")
return {}
def write_config(data):
# Write to a temp file and atomically replace the target so an interrupted
# write can never leave a half-written / corrupt config behind.
tmp_path = CONFIG_PATH + ".tmp"
try:
with open(tmp_path, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
f.flush()
os.fsync(f.fileno())
os.replace(tmp_path, CONFIG_PATH)
except (OSError, ValueError) as exc:
print(f"Failed to write config: {exc}")
try:
if os.path.exists(tmp_path):
os.remove(tmp_path)
except OSError:
pass
def get_dialog_stylesheet(dark_mode=False, include_radio=False, button_padding="10px 16px"):
"""Generate consistent dialog stylesheet for dark/light mode.
Args:
dark_mode: True for dark theme, False for light theme
include_radio: True to include QRadioButton styles
button_padding: CSS padding for QPushButton
"""
if dark_mode:
base = """
QDialog { background-color: #2d2d30; color: #d4d4d4; }
QLabel { color: #e1e4e8; font-size: 14px; }
QPushButton {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #0e4775, stop: 1 #0a3d66);
border: 1px solid #1177bb; border-radius: 6px; padding: %s;
color: white; font-weight: 600; min-width: 80px;
}
QPushButton:hover {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #1177bb, stop: 1 #0e639c);
}
""" % button_padding
radio = """
QRadioButton { color: #d4d4d4; font-size: 13px; padding: 8px; }
QRadioButton::indicator { width: 16px; height: 16px; }
QRadioButton::indicator:unchecked { border: 2px solid #404040; border-radius: 9px; background: #252526; }
QRadioButton::indicator:checked { border: 2px solid #007fd4; border-radius: 9px; background: #007fd4; }
"""
else:
base = """
QDialog { background-color: #ffffff; color: #24292f; }
QLabel { color: #24292f; font-size: 14px; }
QPushButton {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2ea043, stop: 1 #238636);
border: 1px solid #1a7f37; border-radius: 6px; padding: %s;
color: white; font-weight: 600; min-width: 80px;
}
QPushButton:hover {
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #2c974b, stop: 1 #1f883d);
}
""" % button_padding
radio = """
QRadioButton { color: #24292f; font-size: 13px; padding: 8px; }
QRadioButton::indicator { width: 16px; height: 16px; }
QRadioButton::indicator:unchecked { border: 2px solid #d1d9e0; border-radius: 9px; background: #ffffff; }
QRadioButton::indicator:checked { border: 2px solid #0969da; border-radius: 9px; background: #0969da; }
"""
return base + radio if include_radio else base
# Beautiful ToolTip class for showing confirmation messages
class BeautifulToolTip(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowFlags(Qt.WindowType.ToolTip | Qt.WindowType.FramelessWindowHint)
self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
self.setFixedSize(280, 80)
# Create layout
layout = QVBoxLayout(self)
layout.setContentsMargins(25, 20, 25, 20)
# Create label
self.label = QLabel()
self.label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.label.setWordWrap(True)
font = QFont()
font.setPointSize(16)
font.setBold(True)
font.setWeight(QFont.Weight.ExtraBold)
self.label.setFont(font)
# Add text shadow effect to label
label_shadow = QGraphicsDropShadowEffect()
label_shadow.setBlurRadius(8)
label_shadow.setOffset(2, 2)
label_shadow.setColor(QColor(0, 0, 0, 180))
self.label.setGraphicsEffect(label_shadow)
layout.addWidget(self.label)
# Set up style
self.setup_style()
# Add shadow effect
shadow = QGraphicsDropShadowEffect()
shadow.setBlurRadius(30)
shadow.setOffset(0, 6)
shadow.setColor(QColor(0, 0, 0, 200))
self.setGraphicsEffect(shadow)
# Animation
self.opacity_animation = QPropertyAnimation(self, b"windowOpacity")
self.opacity_animation.setDuration(200)
self.opacity_animation.setEasingCurve(QEasingCurve.Type.OutQuad)
# Auto-hide timer
self.hide_timer = QTimer()
self.hide_timer.setSingleShot(True)
self.hide_timer.timeout.connect(self.fade_out)
def setup_style(self, dark=False):
"""Setup tooltip style. dark=True for dark mode blue style."""
if dark:
colors = ("rgba(33, 150, 243, 180)", "rgba(25, 118, 210, 180)", "150")
else:
colors = ("rgba(76, 175, 80, 200)", "rgba(56, 142, 60, 200)", "120")
self.setStyleSheet(f"""
BeautifulToolTip {{
background: qlineargradient(x1: 0, y1: 0, x2: 0, y2: 1,
stop: 0 {colors[0]},
stop: 1 {colors[1]});
border-radius: 15px;
border: 3px solid rgba(255, 255, 255, {colors[2]});
}}
QLabel {{
color: white;
font-weight: bold;
font-size: 16px;
background: transparent;
border: none;
padding: 2px;
}}
""")
def setup_dark_style(self):
"""Convenience method for dark style."""
self.setup_style(dark=True)
def show_message(self, message, parent_widget, duration=2000):
# Stop any existing animations and timers first
self.hide_timer.stop()
self.opacity_animation.stop()
# Safely disconnect any existing signal connections to prevent conflicts
try:
self.opacity_animation.finished.disconnect()
except TypeError:
# No connections exist, which is fine
pass
self.label.setText(message)
# Position relative to parent widget
if parent_widget:
parent_rect = parent_widget.geometry()
parent_center = parent_widget.mapToGlobal(parent_rect.center())
# Position tooltip above the center of parent widget
tooltip_x = parent_center.x() - self.width() // 2
tooltip_y = parent_center.y() - parent_rect.height() // 2 - self.height() - 20
# Ensure tooltip stays within screen bounds
screen = QApplication.primaryScreen().geometry()
if tooltip_x < 10:
tooltip_x = 10
elif tooltip_x + self.width() > screen.width() - 10:
tooltip_x = screen.width() - self.width() - 10
if tooltip_y < 10:
tooltip_y = parent_center.y() + parent_rect.height() // 2 + 20
self.move(tooltip_x, tooltip_y)
# Show with fade-in animation
self.setWindowOpacity(0.0)
self.show()
self.raise_()
self.opacity_animation.setStartValue(0.0)
self.opacity_animation.setEndValue(1.0)
self.opacity_animation.start()
# Auto-hide after duration
self.hide_timer.start(duration)
def fade_out(self):
# Stop the hide timer to prevent conflicts
self.hide_timer.stop()
self.opacity_animation.setStartValue(1.0)
self.opacity_animation.setEndValue(0.0)
# Connect the finished signal only when we need it
self.opacity_animation.finished.connect(self.hide_and_cleanup)
self.opacity_animation.start()
def hide_and_cleanup(self):
"""Hide the tooltip and clean up signal connections"""
# Safely disconnect all signals to prevent conflicts
try:
self.opacity_animation.finished.disconnect()
except TypeError:
# No connections exist, which is fine
pass
self.hide()
# Reset opacity for next time
self.setWindowOpacity(1.0)
# Export Format Selection Dialog
class ExportFormatDialog(QDialog):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("🚀 Export Format Selection")
self.setModal(True)
self.setFixedSize(520, 480) # increase size to prevent text truncation
# Apply current theme styling
is_dark = hasattr(parent, 'dark_mode') and parent.dark_mode
self.setStyleSheet(get_dialog_stylesheet(dark_mode=is_dark, include_radio=True, button_padding="10px 20px"))
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 25, 20, 20) # increase top margin to ensure title is fully visible
layout.setSpacing(8) # set appropriate spacing
# Title
title = QLabel("📤 Choose Export Format")
title.setStyleSheet("""
font-size: 18px;
font-weight: bold;
margin-bottom: 15px;
padding: 8px 5px;
min-height: 35px;
max-height: 50px;
""")
title.setAlignment(Qt.AlignmentFlag.AlignCenter)
title.setWordWrap(True)
layout.addWidget(title)
# Format options - use list to avoid repetition
self.format_group = QButtonGroup(self)
format_options = [
("📄 JSON - Modern structured data", "Export as JSON with metadata and structured information",
" → Best for data processing, APIs, and modern applications"),
("📊 Excel - Spreadsheet with styling", "Export as Excel file with formatting and multiple columns",
" → Perfect for data analysis, charts, and business reports"),
("🌐 HTML - Interactive web page", "Export as styled HTML page with search and filtering",
" → Great for sharing, presentations, and web viewing"),
("📝 Markdown - Documentation format", "Export as Markdown for GitHub, documentation sites",
" → Ideal for GitHub, wikis, and documentation"),
("📋 CSV - Legacy spreadsheet format", "Export as simple CSV for basic compatibility",
" → Simple format for basic spreadsheet applications"),
]
desc_style = "color: #6c757d; font-size: 12px; margin-left: 20px; padding: 2px 0px;"
for idx, (label, tooltip, description) in enumerate(format_options):
radio = QRadioButton(label)
radio.setToolTip(tooltip)
self.format_group.addButton(radio, idx)
layout.addWidget(radio)
desc = QLabel(description)
desc.setStyleSheet(desc_style)
desc.setWordWrap(True)
layout.addWidget(desc)
if idx < len(format_options) - 1:
layout.addSpacing(5)
if idx == 0:
radio.setChecked(True) # Set JSON as default
layout.addStretch()
# Buttons
button_layout = QHBoxLayout()
button_layout.addStretch()
cancel_btn = QPushButton("Cancel")
cancel_btn.clicked.connect(self.reject)
button_layout.addWidget(cancel_btn)
export_btn = QPushButton("📤 Export")
export_btn.clicked.connect(self.accept)
export_btn.setDefault(True)
button_layout.addWidget(export_btn)
layout.addLayout(button_layout)
def get_selected_format(self):
"""Return the selected export format"""
formats = ["json", "excel", "html", "markdown", "csv"]
return formats[self.format_group.checkedId()]
# Export Success Dialog with multiple actions
class ExportSuccessDialog(QDialog):
def __init__(self, parent=None, file_path="", export_format=""):
super().__init__(parent)
self.file_path = file_path
self.export_format = export_format
self.setWindowTitle("✅ Export Successful")
self.setModal(True)
self.setFixedSize(420, 200)
# Apply current theme styling
is_dark = hasattr(parent, 'dark_mode') and parent.dark_mode
self.setStyleSheet(get_dialog_stylesheet(dark_mode=is_dark))
layout = QVBoxLayout(self)
layout.setContentsMargins(20, 20, 20, 20)
layout.setSpacing(15)
# Success message
success_label = QLabel(f"✅ Successfully exported {export_format.upper()} file!")
success_label.setStyleSheet("font-size: 16px; font-weight: bold; color: #28a745; margin-bottom: 10px;")
layout.addWidget(success_label)
# File path
path_label = QLabel(f"📁 Location: {file_path}")
path_label.setStyleSheet("font-size: 12px; word-wrap: true; margin-bottom: 10px;")
path_label.setWordWrap(True)
layout.addWidget(path_label)
layout.addStretch()
# Buttons
button_layout = QHBoxLayout()
# OK button
ok_btn = QPushButton("OK")
ok_btn.clicked.connect(self.accept)
ok_btn.setDefault(True)
button_layout.addWidget(ok_btn)
# Open file button
open_btn = QPushButton("📄 Open File")
open_btn.clicked.connect(self.open_file)
button_layout.addWidget(open_btn)
# Open in Finder button
finder_btn = QPushButton("🔍 Open in Finder")
finder_btn.clicked.connect(self.open_in_finder)
button_layout.addWidget(finder_btn)
layout.addLayout(button_layout)
def open_file(self):
"""Open the exported file with default application"""
try:
subprocess.run(["open", self.file_path], check=True)
except Exception as e:
QMessageBox.warning(self, "Error", f"Could not open file: {str(e)}")
def open_in_finder(self):
"""Open the file location in Finder"""
try:
subprocess.run(["open", "-R", self.file_path], check=True)
except Exception as e:
QMessageBox.warning(self, "Error", f"Could not open Finder: {str(e)}")
# Custom Slider that responds to direct clicks
class ClickableSlider(QSlider):
def __init__(self, orientation):
super().__init__(orientation)
def mousePressEvent(self, event):
# Calculate the relative position of the click and convert to value
value = self.minimum() + (self.maximum() - self.minimum()) * event.position().x() / self.width()
self.setValue(int(value))
# Emit the sliderMoved signal to update video position
self.sliderMoved.emit(int(value))
# Pass the event to the parent class
super().mousePressEvent(event)
# Custom ChartView that handles clicks on entire chart area including axis labels
class ClickableChartView(QChartView):
"""Custom QChartView that allows clicking anywhere on a chart row to select it"""
def __init__(self, chart, parent=None):
super().__init__(chart, parent)
self.main_window = None
self.click_timer = QTimer()
self.click_timer.setSingleShot(True)
self.click_timer.timeout.connect(self._handle_single_click)
self.click_count = 0
self.last_click_index = -1
def mousePressEvent(self, event):
if event.button() == Qt.MouseButton.LeftButton:
# Get the position relative to the chart
pos = event.position() if hasattr(event, 'position') else event.pos()
# Try to find which bar/category was clicked
chart = self.chart()
if not chart:
super().mousePressEvent(event)
return
# Get the chart's plot area
plot_area = chart.plotArea()
# Check if click is within the chart area (including axis labels on the left)
if pos.y() >= plot_area.top() and pos.y() <= plot_area.bottom():
# Calculate which bar index based on Y position
if hasattr(self, 'main_window') and self.main_window:
categories = getattr(self.main_window, 'scan_chart_categories', [])
if categories:
bar_height = plot_area.height() / len(categories)
# QtCharts displays horizontal bars from bottom to top
# So we need to reverse the index calculation
y_from_top = pos.y() - plot_area.top()
index = len(categories) - 1 - int(y_from_top / bar_height)
if 0 <= index < len(categories):
# Handle click/double-click detection
if self.click_count == 0:
self.click_count = 1
self.last_click_index = index
self.click_timer.start(300) # 300ms for double-click detection
elif self.click_count == 1 and self.last_click_index == index:
# Double-click detected
self.click_timer.stop()
self.click_count = 0
self.last_click_index = -1
if self.main_window:
self.main_window.on_scan_chart_bar_double_clicked(index, None)
return
super().mousePressEvent(event)
def _handle_single_click(self):
"""Handle single click after timer expires (no double-click detected)"""
if self.click_count == 1 and self.last_click_index >= 0:
if self.main_window:
self.main_window.on_scan_chart_bar_clicked(self.last_click_index, None)
self.click_count = 0
self.last_click_index = -1
# Custom QTreeWidget to support drag and drop of files to external applications
class DraggableTreeWidget(QTreeWidget):
"""Custom QTreeWidget to support drag and drop of files to external applications"""
def __init__(self, parent=None):
super().__init__(parent)
self.setDragEnabled(True)
def mimeTypes(self):
return ['text/uri-list']
def mimeData(self, items):
mime_data = QMimeData()
urls = []
for item in items:
path = item.text(3) # column 3 is the full path
urls.append(QUrl.fromLocalFile(path))
mime_data.setUrls(urls)
return mime_data
# Convert file size to a human-readable string
def format_size(size):
"""Convert file size to a human-readable string"""
for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
if size < 1024:
return f"{size:.2f} {unit}"
size /= 1024
return f"{size:.2f} TB"
def format_time_label(position_ms, duration_ms):
"""Format time in MM:SS / MM:SS format for media players."""
current_mins, current_secs = divmod(position_ms // 1000, 60)
total_mins, total_secs = divmod(duration_ms // 1000, 60)
return f"🕒 {current_mins:02d}:{current_secs:02d} / {total_mins:02d}:{total_secs:02d}"
# Item-data role that carries a row's share-of-total (0-100 float) for the
# "Share" column. Rows without it (normal search results) render nothing.
SHARE_ROLE = Qt.ItemDataRole.UserRole + 100
class PercentBarDelegate(QStyledItemDelegate):
"""Draws a horizontal proportion bar with a percentage label.
Used by the disk-analysis "Share" column to show each folder's fraction
of the scanned total. The value is read from SHARE_ROLE; the framework
still paints the row background/selection so highlighting stays uniform.
"""
def __init__(self, parent=None, dark_mode_getter=None):
super().__init__(parent)
self._dark_mode_getter = dark_mode_getter
def paint(self, painter, option, index):
# Let the style paint the background/selection first (this column's
# display text is empty, so nothing else is drawn over the bar).
super().paint(painter, option, index)
value = index.data(SHARE_ROLE)
if value is None:
return
try:
pct = float(value)
except (TypeError, ValueError):
return
pct = max(0.0, min(100.0, pct))
dark = bool(self._dark_mode_getter()) if self._dark_mode_getter else False
if dark:
track_color = QColor("#242536")
grad_start, grad_end = QColor("#3b6fd6"), QColor("#8ab4ff")
else:
track_color = QColor("#eaeef5")
grad_start, grad_end = QColor("#2f6fed"), QColor("#7fb0ff")
rect = QRectF(option.rect).adjusted(6, 5, -6, -5)
if rect.width() <= 0 or rect.height() <= 0:
return
radius = rect.height() / 2.0 # pill-shaped
painter.save()
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
# Track
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(track_color)
painter.drawRoundedRect(rect, radius, radius)
# Filled portion with a left→right accent gradient
if pct > 0:
fill_width = max(rect.height(), rect.width() * pct / 100.0)
fill_rect = QRectF(rect.x(), rect.y(), fill_width, rect.height())
gradient = QLinearGradient(fill_rect.topLeft(), fill_rect.topRight())
gradient.setColorAt(0.0, grad_start)
gradient.setColorAt(1.0, grad_end)
painter.setBrush(QBrush(gradient))
painter.drawRoundedRect(fill_rect, radius, radius)
# Percentage label centred on the bar; white over the fill reads well
# in both themes.
painter.setPen(QPen(QColor("#ffffff") if pct >= 45 else (
QColor("#c8d3f5") if dark else QColor("#33415c"))))
font = painter.font()
font.setPointSizeF(max(8.0, font.pointSizeF() - 0.5))
font.setBold(True)
painter.setFont(font)
painter.drawText(rect, int(Qt.AlignmentFlag.AlignCenter), f"{pct:.1f}%")
painter.restore()
class LoadingOverlay(QWidget):
"""Lightweight, asset-free loading overlay.
Draws a translucent scrim over its parent plus a centered rounded card
with an animated spinner and a message — a much cleaner replacement for a
modal QProgressDialog. Clicking anywhere cancels (if a callback is set).
"""
def __init__(self, parent, dark_mode=True):
super().__init__(parent)
self._angle = 0
self._message = "Scanning…"
self._dark = dark_mode
self._cancel_callback = None
self._timer = QTimer(self)
self._timer.timeout.connect(self._advance)
self.setCursor(Qt.CursorShape.ArrowCursor)
self.hide()
def _advance(self):
self._angle = (self._angle + 12) % 360
self.update()
def start(self, message, dark_mode=None, cancel_callback=None):
if dark_mode is not None:
self._dark = dark_mode
self._message = message
self._cancel_callback = cancel_callback
parent = self.parentWidget()
if parent:
self.setGeometry(parent.rect())
parent.installEventFilter(self)
self.raise_()
self.show()
if not self._timer.isActive():
self._timer.start(40) # ~25 fps
def stop(self):
self._timer.stop()
parent = self.parentWidget()
if parent:
parent.removeEventFilter(self)
self.hide()
def eventFilter(self, obj, event):
if obj is self.parentWidget() and event.type() == QEvent.Type.Resize:
self.setGeometry(self.parentWidget().rect())
return super().eventFilter(obj, event)
def mousePressEvent(self, event):
if self._cancel_callback:
self._cancel_callback()
def paintEvent(self, event):
painter = QPainter(self)
painter.setRenderHint(QPainter.RenderHint.Antialiasing, True)
# Scrim dimming the chart behind the overlay
scrim = QColor(15, 16, 30, 165) if self._dark else QColor(245, 247, 251, 190)
painter.fillRect(self.rect(), scrim)
# Centered card
cw, ch = 220, 130
cx = (self.width() - cw) // 2
cy = (self.height() - ch) // 2
card = QRectF(cx, cy, cw, ch)
painter.setPen(Qt.PenStyle.NoPen)
painter.setBrush(QColor("#1f2233") if self._dark else QColor("#ffffff"))
painter.drawRoundedRect(card, 16, 16)
# Spinner: faint full ring + a rotating accent arc
accent = QColor("#8ab4ff") if self._dark else QColor("#2f6fed")
track = QColor(255, 255, 255, 45) if self._dark else QColor(0, 0, 0, 30)
radius = 20
sx = cx + cw / 2
sy = cy + 42
spinner_rect = QRectF(sx - radius, sy - radius, 2 * radius, 2 * radius)
painter.setBrush(Qt.BrushStyle.NoBrush)
ring_pen = QPen(track, 4)
ring_pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(ring_pen)
painter.drawArc(spinner_rect, 0, 360 * 16)
arc_pen = QPen(accent, 4)
arc_pen.setCapStyle(Qt.PenCapStyle.RoundCap)
painter.setPen(arc_pen)
painter.drawArc(spinner_rect, -self._angle * 16, 100 * 16)
# Message + subtle cancel hint
painter.setPen(QPen(QColor("#c8d3f5") if self._dark else QColor("#33415c")))
font = painter.font()
font.setPointSize(11)
font.setBold(True)
painter.setFont(font)
painter.drawText(QRectF(cx, cy + 74, cw, 22),
int(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop),
self._message)
if self._cancel_callback:
painter.setPen(QPen(QColor(200, 211, 245, 140) if self._dark else QColor(90, 100, 120, 160)))
hint_font = painter.font()
hint_font.setPointSize(9)
hint_font.setBold(False)
painter.setFont(hint_font)
painter.drawText(QRectF(cx, cy + 98, cw, 18),
int(Qt.AlignmentFlag.AlignHCenter | Qt.AlignmentFlag.AlignTop),
"Click to cancel")
# Class to manage individual search tabs
class SearchTab:
"""Manages the data and widgets for a single search tab"""
def __init__(self, query="", directory="", file_name_search=True, match_case=False, full_match=False, min_size="", max_size="", extensions="", is_pinned=False, tab_title="", extra_clause=None, is_bookmark=False, is_scan_tab=False):
self.query = query
self.directory = directory
self.file_name_search = file_name_search
self.match_case = match_case
self.full_match = full_match
self.min_size = min_size
self.max_size = max_size
self.extensions = extensions
# Pin state
self.is_pinned = is_pinned
self.tab_title = tab_title # Store original tab title
self.is_scan_tab = is_scan_tab
# Bookmark search fields
self.extra_clause = extra_clause
self.is_bookmark = is_bookmark
# Search results data
self.all_file_data = []
self.file_data = []
self.current_loaded = 0
self.items_found_count = 0 # Store the number of items found for this tab
self.scan_chart_data = [] # Usage scan visualization cache
self.scan_chart_title = ""
# Create the tree widget for this tab
self.tree = DraggableTreeWidget()
# Column 4 ("Share") shows a proportion bar for disk-analysis tabs and
# stays hidden for ordinary search results. Path remains column 3 so
# existing column references are unaffected.
self.tree.setColumnCount(5)
self.tree.setHeaderLabels(["Name", "Size", "Date Modified", "Path", "Share"])
self.tree.setSelectionMode(QTreeWidget.SelectionMode.ExtendedSelection)
self.tree.setSelectionBehavior(QTreeWidget.SelectionBehavior.SelectRows)
self.tree.setSortingEnabled(False)
self.tree.setColumnWidth(0, 200)
self.tree.setColumnWidth(1, 80)
self.tree.setColumnWidth(2, 130)
self.tree.setColumnWidth(3, 350)
self.tree.setColumnWidth(4, 150)
self.tree.setColumnHidden(4, True)
# Show the "Share" bar right after "Size" (visual position 2) while
# keeping its logical index 4, so it is immediately visible instead of
# hidden past the wide "Path" column. Logical indices are unchanged.
self.tree.header().moveSection(self.tree.header().visualIndex(4), 2)
# Sort settings
self.sort_column = -1
self.sort_order = Qt.SortOrder.AscendingOrder
# Search worker thread
self.search_worker = None
# Thread class to run mdfind in the background.
# Reads results line by line based on search parameters and sends them to the main thread.
class SearchWorker(QThread):
"""Thread class to run mdfind in the background.
Reads results line by line based on search parameters and sends them to the main thread."""
progress_signal = pyqtSignal(int)
result_signal = pyqtSignal(list)
error_signal = pyqtSignal(str)
def __init__(self, query, directory, search_by_file_name, match_case, full_match, extra_clause=None, is_bookmark=False):
super().__init__()
self.query = query
self.directory = directory
self.search_by_file_name = search_by_file_name
self.match_case = match_case
self.full_match = full_match
self.extra_clause = extra_clause
self.is_bookmark = is_bookmark
self._is_running = True
self.process = None
def run(self):
files_info = []
idx = 0
cmd = ["mdfind"]
# If it's a bookmark search, use only the extra clause
if self.is_bookmark and self.extra_clause is not None:
query_str = self.extra_clause
else:
# Normal search behavior as before
full_match_str = "" if self.full_match else "*"
case_modifier = "" if self.match_case else "cd"
if self.search_by_file_name:
query_str = f'kMDItemFSName == "{full_match_str}{self.query}{full_match_str}"{case_modifier}'
if self.extra_clause is not None:
query_str += f" && {self.extra_clause}"
else:
if self.query != "":
query_str = f'kMDItemTextContent == "{full_match_str}{self.query}{full_match_str}"{case_modifier}'
if self.extra_clause is not None:
query_str += f" && {self.extra_clause}"
else:
if self.extra_clause is not None:
query_str = self.extra_clause
else:
return
cmd.append(query_str)
if self.directory:
dir_expanded = os.path.expanduser(self.directory)
cmd.extend(["-onlyin", dir_expanded])
# print(f"Running mdfind with query: {cmd}")
try:
self.process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
except Exception as e:
self.error_signal.emit(str(e))
return
try:
while self._is_running:
line = self.process.stdout.readline()
if not line:
break
idx += 1
path = line.strip()
if path:
try:
# Use single os.stat() call instead of multiple os.path calls
stat_result = os.stat(path)
is_dir = stat.S_ISDIR(stat_result.st_mode)
size_ = 0 if is_dir else stat_result.st_size
mtime = stat_result.st_mtime
files_info.append((os.path.basename(path), size_, mtime, path))
except (OSError, IOError):
# File may have been deleted or is inaccessible
continue
if idx % 10 == 0:
self.progress_signal.emit(min(100, idx % 100))
self.process.wait()
self.result_signal.emit(files_info)
except Exception as e:
self.error_signal.emit(str(e))
self.stop()
finally:
self.progress_signal.emit(0)
def stop(self):
self._is_running = False
if self.process is not None:
try:
self.process.terminate()
except Exception:
pass
class DirectoryScanWorker(QThread):
"""Scan top-level directories under a root path and report sizes"""
progress_signal = pyqtSignal(int, int, str) # processed, total, current dir name
result_signal = pyqtSignal(list)
error_signal = pyqtSignal(str)
cancelled_signal = pyqtSignal()
# Cap parallel `du` processes so we speed up wall-clock time on many
# folders without thrashing the disk with unbounded concurrency.
MAX_WORKERS = 8
def __init__(self, root_path, entries=None):
super().__init__()
self.root_path = Path(root_path)
self.entries = entries
self._is_running = True
self._procs = set()
self._procs_lock = threading.Lock()
def run(self):
try:
entries = self.entries if self.entries is not None else [entry for entry in self.root_path.iterdir() if entry.is_dir()]
except Exception as exc:
self.error_signal.emit(f"Failed to list '{self.root_path}': {exc}")
return
total = len(entries)
if total == 0:
self.result_signal.emit([])
return
# Scan folders concurrently: `du` is largely I/O-bound, so overlapping
# several folders shrinks total scan time dramatically versus running
# them one after another.
results = []
processed = 0
max_workers = min(self.MAX_WORKERS, total)
with ThreadPoolExecutor(max_workers=max_workers) as executor:
future_to_entry = {
executor.submit(self._get_directory_size, entry): entry
for entry in entries
}
for future in as_completed(future_to_entry):
if not self._is_running:
# Cancel anything still queued; running processes are
# terminated via stop().
executor.shutdown(wait=False, cancel_futures=True)
self.cancelled_signal.emit()
return
entry = future_to_entry[future]
try:
size_bytes = future.result()
except Exception:
size_bytes = 0
results.append((entry.name, size_bytes))
processed += 1
self.progress_signal.emit(processed, total, entry.name)
if not self._is_running:
self.cancelled_signal.emit()
return
self.result_signal.emit(results)
def _get_directory_size(self, entry):
if not self._is_running:
return 0
try:
proc = subprocess.Popen(
["du", "-skxP", str(entry)],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
except (OSError, ValueError):
return 0
with self._procs_lock:
self._procs.add(proc)
try:
stdout, _ = proc.communicate()
except Exception:
return 0
finally:
with self._procs_lock:
self._procs.discard(proc)
try:
text = stdout.decode(errors="ignore").strip()
if text:
last_line = text.splitlines()[-1]
first_token = last_line.split()[0]
return int(first_token) * 1024
except (ValueError, IndexError):
return 0
return 0
def stop(self):
self._is_running = False
# Terminate in-flight `du` processes so cancellation is responsive
# instead of waiting for large folders to finish.
with self._procs_lock:
for proc in list(self._procs):
try:
proc.terminate()
except Exception:
pass
class SubdirScanWorker(QThread):