-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheverything.py
2208 lines (1900 loc) · 86.8 KB
/
everything.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import json
import subprocess
import time
import csv
import shutil
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
)
from PyQt6.QtCore import Qt, QThread, pyqtSignal, QTimer, QUrl, QMimeData
from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput
from PyQt6.QtMultimediaWidgets import QVideoWidget
from PyQt6.QtGui import QPixmap, QMovie, QPainter, QFont
from PyQt6.QtSvg import QSvgRenderer
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:
return {}
def write_config(data):
try:
with open(CONFIG_PATH, "w", encoding="utf-8") as f:
json.dump(data, f, indent=2)
except:
pass
# 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 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"
# 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 and os.path.isfile(path):
try:
size_ = os.path.getsize(path)
mtime = os.path.getmtime(path)
files_info.append((os.path.basename(path), size_, mtime, path))
except Exception as e:
print(f"Error processing file {path}: {e}")
elif path and os.path.isdir(path):
# If the path is a directory, add it to the list with size 0
mtime = os.path.getmtime(path)
files_info.append((os.path.basename(path), 0, mtime, path))
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 MediaPlayerManager:
"""Manages media playback functionality shared between embedded and standalone players"""
def __init__(self, parent=None):
self.parent = parent
self.audio_output = QAudioOutput()
self.media_player = QMediaPlayer()
self.audio_output.setVolume(0.7) # Default 70%
self.video_extensions = set()
self.audio_extensions = set()
self.current_media_path = None
self.slider_dragging = False
self.was_playing = False
def setup_extensions(self, video_ext, audio_ext):
"""Set up the video and audio extensions"""
self.video_extensions = video_ext
self.audio_extensions = audio_ext
def set_video_output(self, video_widget):
"""Set the video output widget"""
self.media_player.setVideoOutput(video_widget)
self.media_player.setAudioOutput(self.audio_output)
def play_media(self, path, is_audio=False):
"""Play a media file"""
self.current_media_path = path
self.media_player.setSource(QUrl.fromLocalFile(path))
self.media_player.play()
return True
def stop(self):
"""Stop media playback"""
self.media_player.stop()
self.current_media_path = None
def pause(self):
"""Pause media playback"""
self.media_player.pause()
def toggle_play_pause(self):
"""Toggle between play and pause states"""
if self.media_player.playbackState() == QMediaPlayer.PlaybackState.PlayingState:
self.media_player.pause()
return False
else:
self.media_player.play()
return True
def set_position(self, position):
"""Set the playback position"""
self.media_player.setPosition(position)
def get_position(self):
"""Get the current playback position"""
return self.media_player.position()
def get_duration(self):
"""Get the media duration"""
return self.media_player.duration()
def set_volume(self, volume_percent):
"""Set volume as a percentage (0-100)"""
self.audio_output.setVolume(volume_percent / 100.0)
def toggle_mute(self):
"""Toggle audio mute state"""
current_mute = self.audio_output.isMuted()
self.audio_output.setMuted(not current_mute)
return not current_mute
def is_muted(self):
"""Check if audio is muted"""
return self.audio_output.isMuted()
def get_volume(self):
"""Get current volume as percentage (0-100)"""
return int(self.audio_output.volume() * 100)
def on_slider_pressed(self):
"""Handle slider press event"""
self.slider_dragging = True
self.was_playing = self.media_player.playbackState() == QMediaPlayer.PlaybackState.PlayingState
if self.was_playing:
self.media_player.pause()
def on_slider_released(self):
"""Handle slider release event"""
self.slider_dragging = False
if self.was_playing:
self.media_player.play()
def is_audio_file(self, path):
"""Check if file is an audio file based on extension"""
_, ext = os.path.splitext(path)
return ext.lower() in self.audio_extensions
def is_video_file(self, path):
"""Check if file is a video file based on extension"""
_, ext = os.path.splitext(path)
return ext.lower() in self.video_extensions
def is_media_file(self, path):
"""Check if file is either audio or video"""
return self.is_audio_file(path) or self.is_video_file(path)
def connect_signals(self, position_callback, duration_callback, state_callback):
"""Connect signal handlers for the media player"""
self.media_player.positionChanged.connect(position_callback)
self.media_player.durationChanged.connect(duration_callback)
self.media_player.playbackStateChanged.connect(state_callback)
# Update StandalonePlayerWindow to use MediaPlayerManager
class StandalonePlayerWindow(QMainWindow):
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Media Player")
self.resize(800, 600) # Default size, user can resize
# Main widget and layout
central_widget = QWidget()
main_layout = QVBoxLayout(central_widget)
# Video widget
self.video_widget = QVideoWidget()
if getattr(QVideoWidget, "setAspectRatioMode", None) is not None:
self.video_widget.setAspectRatioMode(Qt.AspectRatioMode.KeepAspectRatio)
self.video_widget.installEventFilter(self)
# Audio label for audio files
self.audio_label = QLabel()
self.audio_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.audio_label.setWordWrap(True)
font = QFont()
font.setPointSize(16)
font.setBold(True)
self.audio_label.setFont(font)
self.audio_label.setVisible(False)
self.audio_label.installEventFilter(self)
# Media container to hold both video widget and audio label
media_container = QWidget()
media_layout = QVBoxLayout(media_container)
media_layout.setContentsMargins(0, 0, 0, 0)
media_layout.addWidget(self.video_widget)
media_layout.addWidget(self.audio_label)
main_layout.addWidget(media_container, 1)
# Controls layout
controls_layout = QHBoxLayout()
# Play/Pause button
self.play_button = QToolButton()
self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
controls_layout.addWidget(self.play_button)
# Time label
self.time_label = QLabel("00:00 / 00:00")
self.time_label.setMinimumWidth(100)
controls_layout.addWidget(self.time_label)
# Seek slider
self.seek_slider = ClickableSlider(Qt.Orientation.Horizontal)
self.seek_slider.setRange(0, 0)
controls_layout.addWidget(self.seek_slider, 4)
# Volume button
self.volume_button = QToolButton()
self.volume_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolume))
controls_layout.addWidget(self.volume_button)
# Volume slider
self.volume_slider = QSlider(Qt.Orientation.Horizontal)
self.volume_slider.setRange(0, 100)
self.volume_slider.setValue(70) # Default volume
self.volume_slider.setMaximumWidth(100)
controls_layout.addWidget(self.volume_slider)
main_layout.addLayout(controls_layout)
# Create the media player manager
self.player_manager = MediaPlayerManager(self)
self.player_manager.set_video_output(self.video_widget)
# Connect signals
self.play_button.clicked.connect(self.toggle_play_pause)
self.seek_slider.sliderMoved.connect(self.player_manager.set_position)
self.seek_slider.sliderPressed.connect(self.player_manager.on_slider_pressed)
self.seek_slider.sliderReleased.connect(self.player_manager.on_slider_released)
self.volume_button.clicked.connect(self.toggle_mute)
self.volume_slider.valueChanged.connect(self.player_manager.set_volume)
# Connect media player signals
self.player_manager.connect_signals(
self.update_position,
self.update_duration,
self.on_playback_state_changed
)
self.setCentralWidget(central_widget)
self.continuous_playback = False
self.dark_mode = False
self.current_media_path = None
def setup_extensions(self, video_ext, audio_ext):
"""Set up the video and audio extensions from the parent app"""
self.player_manager.setup_extensions(video_ext, audio_ext)
def set_continuous_playback(self, enabled):
"""Set whether continuous playback is enabled"""
self.continuous_playback = enabled
def set_dark_mode(self, enabled):
"""Set dark mode for the player"""
self.dark_mode = enabled
filename = os.path.basename(self.current_media_path) if self.current_media_path else ""
if filename:
self.audio_label.setText(f"<div style='padding: 20px; border-radius: 10px;'>"
f"<div style='font-size: 24pt; color: {'white' if enabled else 'black'};'>"
f"{filename}</div></div>")
def play_media(self, path, is_video=True):
"""Play a media file"""
self.current_media_path = path
# Update UI based on media type
if is_video:
self.video_widget.setVisible(True)
self.audio_label.setVisible(False)
else:
self.video_widget.setVisible(False)
self.audio_label.setVisible(True)
filename = os.path.basename(path)
self.audio_label.setText(f"<div style='padding: 20px; border-radius: 10px;'>"
f"<div style='font-size: 24pt; color: {'white' if self.dark_mode else 'black'};'>"
f"{filename}</div></div>")
# Use the player manager to play the media
self.player_manager.play_media(path)
self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
def toggle_play_pause(self):
is_playing = self.player_manager.toggle_play_pause()
icon = QStyle.StandardPixmap.SP_MediaPause if is_playing else QStyle.StandardPixmap.SP_MediaPlay
self.play_button.setIcon(self.style().standardIcon(icon))
def update_position(self, position):
try:
if not self.player_manager.slider_dragging:
self.seek_slider.setValue(position)
total_duration = self.player_manager.get_duration()
current_mins = position // 60000
current_secs = (position % 60000) // 1000
total_mins = total_duration // 60000
total_secs = (total_duration % 60000) // 1000
self.time_label.setText(f"{current_mins:02d}:{current_secs:02d} / {total_mins:02d}:{total_secs:02d}")
except Exception:
pass
def update_duration(self, duration):
self.seek_slider.setRange(0, duration)
if duration > 0:
self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause))
def toggle_mute(self):
is_muted = self.player_manager.toggle_mute()
icon = QStyle.StandardPixmap.SP_MediaVolumeMuted if is_muted else QStyle.StandardPixmap.SP_MediaVolume
self.volume_button.setIcon(self.style().standardIcon(icon))
if not is_muted:
self.volume_slider.setValue(self.player_manager.get_volume())
def on_playback_state_changed(self, state):
if state == QMediaPlayer.PlaybackState.StoppedState:
if self.continuous_playback and self.player_manager.get_position() > 0:
# Signal to the main app that we need to play the next media
self.parent().play_next_in_standalone()
def closeEvent(self, event):
# Signal the parent to restore the embedded player
self.parent().restore_embedded_player()
event.accept()
def get_current_position(self):
"""Get the current position of the media player"""
return self.player_manager.get_position()
def get_playback_state(self):
"""Get the current playback state (playing/paused)"""
return self.player_manager.media_player.playbackState()
def eventFilter(self, obj, event):
if event.type() == event.Type.MouseButtonPress and (obj == self.video_widget or obj == self.audio_label):
if event.button() == Qt.MouseButton.LeftButton:
self.toggle_play_pause()
return True
return super().eventFilter(obj, event)
class MdfindApp(QMainWindow):
def __init__(self):
super().__init__()
# Load dark mode and history settings from config
config = read_config()
self.dark_mode = config.get("dark_mode", False)
self.history_enabled = config.get("history_enabled", True)
self.preview_enabled = config.get("preview_enabled", False)
self.continuous_playback = config.get("continuous_playback", False)
self.slider_dragging = False # Initialize slider_dragging attribute
self.setWindowTitle("Everything by mdfind")
size = config.get("window_size", {"width": 1920, "height": 1080})
self.resize(size["width"], size["height"])
# Define recognizable extensions before initializing extension emoji map
self.image_extensions = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp",".heic"}
self.video_extensions = {".mp4", ".mov", ".avi", ".mkv", ".mpg", ".mpeg"}
self.audio_extensions = {".mp3", ".wav", ".aac", ".ogg", ".flac", ".m4a", ".wma", ".caf",".aif",".m4r",".au"}
# ========== Menu Bar ==========
menubar = self.menuBar()
help_menu = menubar.addMenu('Help')
about_action = help_menu.addAction('About')
about_action.triggered.connect(self.show_about_dialog)
# Add a "History" menu
history_menu = menubar.addMenu('History')
clear_history_action = history_menu.addAction('Clear History')
clear_history_action.triggered.connect(self.clear_history)
enable_history_action = history_menu.addAction("Enable History")
enable_history_action.setCheckable(True)
enable_history_action.setChecked(self.history_enabled)
enable_history_action.triggered.connect(self.toggle_history)
# Add a "View" menu
view_menu = menubar.addMenu('View')
toggle_preview_action = view_menu.addAction('Toggle Preview')
toggle_preview_action.setCheckable(True)
toggle_preview_action.setChecked(self.preview_enabled) # Use the loaded setting instead of hardcoded False
toggle_preview_action.triggered.connect(self.toggle_preview)
# Store reference to the toggle_preview_action for later use
self.toggle_preview_action = toggle_preview_action
# Add continuous playback action
continuous_playback_action = view_menu.addAction('Continuous Playback')
continuous_playback_action.setCheckable(True)
continuous_playback_action.setChecked(self.continuous_playback)
continuous_playback_action.triggered.connect(self.toggle_continuous_playback)
self.continuous_playback_action = continuous_playback_action
# Added dark mode toggle action in the View menu
dark_mode_action = view_menu.addAction('Dark Mode')
dark_mode_action.setCheckable(True)
dark_mode_action.setChecked(self.dark_mode)
dark_mode_action.triggered.connect(self.toggle_dark_mode)
if self.dark_mode:
self.set_dark_mode()
else:
self.set_non_dark_mode()
# === Bookmarks Menu ===
bookmarks_menu = menubar.addMenu("Bookmarks")
bookmarks_menu.addAction("Large Files", self.bookmark_large_files)
bookmarks_menu.addAction("Video Files", self.bookmark_videos)
bookmarks_menu.addAction("Audio Files", self.bookmark_audio)
bookmarks_menu.addAction("Images", self.bookmark_images)
bookmarks_menu.addAction("Archives", self.bookmark_archives)
bookmarks_menu.addAction("Applications", self.bookmark_applications)
# Search thread variables
self.search_worker = None
self.all_file_data = []
self.file_data = []
self.initialize_extension_emoji_map()
# ======= Main layout: QSplitter, left for search/list and right for preview ===========
splitter = QSplitter(self)
splitter.setOrientation(Qt.Orientation.Horizontal)
self.setCentralWidget(splitter)
# ========== Left side ==========
left_container = QWidget()
left_layout = QVBoxLayout(left_container)
# First row: Search Query input and statistics
form_layout = QHBoxLayout()
lbl_query = QLabel("Search Query:")
self.edit_query = QLineEdit()
self.lbl_items_found = QLabel("0 items found")
form_layout.addWidget(lbl_query)
form_layout.addWidget(self.edit_query, 4)
form_layout.addWidget(self.lbl_items_found, 1)
left_layout.addLayout(form_layout)
# Second row: Directory selection (optional)
form_layout2 = QHBoxLayout()
lbl_dir = QLabel("Directory (optional):")
self.edit_dir = QLineEdit()
self.edit_dir.setPlaceholderText(" Leave empty to search everywhere")
btn_select_dir = QPushButton("Select Dir")
btn_select_dir.clicked.connect(self.select_directory)
form_layout2.addWidget(lbl_dir)
form_layout2.addWidget(self.edit_dir, 4)
form_layout2.addWidget(btn_select_dir, 1)
left_layout.addLayout(form_layout2)
# Advanced Filters group
group_advanced = QGroupBox("Advanced Filters")
adv_layout = QHBoxLayout()
lbl_min_size = QLabel("Min Size (bytes):")
self.edit_min_size = QLineEdit()
lbl_max_size = QLabel("Max Size (bytes):")
self.edit_max_size = QLineEdit()
lbl_extension = QLabel("File Extension:")
self.edit_extension = QLineEdit()
self.edit_extension.setPlaceholderText("pdf;docx;xls")
self.chk_file_name = QCheckBox("Search by File Name")
self.chk_file_name.setChecked(True)
self.chk_match_case = QCheckBox("Match Case")
self.chk_full_match = QCheckBox("Full Match")
adv_layout.addWidget(lbl_min_size, 2)
adv_layout.addWidget(self.edit_min_size, 5)
adv_layout.addWidget(lbl_max_size, 2)
adv_layout.addWidget(self.edit_max_size, 5)
adv_layout.addWidget(lbl_extension, 2)
adv_layout.addWidget(self.edit_extension, 5)
adv_layout.addWidget(self.chk_file_name, 2)
adv_layout.addWidget(self.chk_match_case, 2)
adv_layout.addWidget(self.chk_full_match, 2)
group_advanced.setLayout(adv_layout)
left_layout.addWidget(group_advanced)
# Search results list
self.tree = DraggableTreeWidget()
self.tree.setColumnCount(4)
self.tree.setHeaderLabels(["Name", "Size", "Date Modified", "Path"])
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.header().setSectionsClickable(True)
self.tree.header().setSortIndicatorShown(True)
self.tree.header().sectionClicked.connect(self.on_header_clicked)
left_layout.addWidget(self.tree, stretch=1)
# Progress bar and Export button
self.progress = QProgressBar()
self.progress.setMaximum(100)
left_layout.addWidget(self.progress)
btn_export = QPushButton("Export to CSV")
btn_export.clicked.connect(self.export_to_csv)
left_layout.addWidget(btn_export, alignment=Qt.AlignmentFlag.AlignRight)
splitter.addWidget(left_container)
# ========== Right side Preview ==========
self.preview_container = QWidget()
preview_layout = QVBoxLayout(self.preview_container)
# Header layout with Preview title and buttons
header_layout = QHBoxLayout()
preview_title = QLabel("<b>Preview</b>")
header_layout.addWidget(preview_title)
header_layout.addStretch()
# Add a pop-out button
popout_button = QPushButton("□") # Square symbol for pop-out
popout_button.setFixedSize(24, 24)
popout_button.setToolTip("Open in standalone player")
popout_button.clicked.connect(self.open_standalone_player)
popout_button.setObjectName("previewPopoutButton")
popout_button.setStyleSheet("""
#previewPopoutButton {
border: none;
border-radius: 12px;
font-size: 14px;
font-weight: bold;
background-color: transparent;
}
#previewPopoutButton:hover {
background-color: #4285f4;
color: white;
}
""")
# Add the popout button to the header
header_layout.addWidget(popout_button)
# Add a more stylish close button to the header
close_button = QPushButton("✕") # Using Unicode "Heavy Multiplication X" character
close_button.setFixedSize(24, 24) # Keep the square size
close_button.setToolTip("Close preview panel")
close_button.clicked.connect(self.close_preview)
# Apply special styling to the close button to make it more elegant
close_button.setObjectName("previewCloseButton") # Set object name for styling
close_button.setStyleSheet("""
#previewCloseButton {
border: none;
border-radius: 12px;
font-size: 14px;
font-weight: bold;
background-color: transparent;
}
#previewCloseButton:hover {
background-color: #d32f2f;
color: white;
}
""")
header_layout.addWidget(close_button)
preview_layout.addLayout(header_layout)
# Create vertical splitter for preview (top) and metadata (bottom)
self.preview_splitter = QSplitter(Qt.Orientation.Vertical)
preview_layout.addWidget(self.preview_splitter, stretch=1)
# Keep the existing QStackedWidget as top
self.preview_stack = QStackedWidget()
# 1) Text Preview
self.text_preview = QPlainTextEdit()
self.text_preview.setReadOnly(True)
# 2) Image Preview: Fixed size, scale manually if needed
self.image_label = QLabel()
self.image_label.setFixedSize(500, 400)
self.image_label.setScaledContents(False)
self.image_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
# Wrap image_label in a centered container
image_container = QWidget()
image_layout = QVBoxLayout(image_container)
image_layout.setContentsMargins(0, 0, 0, 0)
image_layout.addWidget(self.image_label, alignment=Qt.AlignmentFlag.AlignCenter)
# 3) Video/Audio Preview Container
media_container = QWidget()
media_layout = QVBoxLayout(media_container)
media_layout.setContentsMargins(0, 0, 0, 0)
# Video widget
self.video_widget = QVideoWidget()
self.video_widget.setFixedSize(500, 400)
if getattr(QVideoWidget, "setAspectRatioMode", None) is not None:
self.video_widget.setAspectRatioMode(Qt.AspectRatioMode.KeepAspectRatio)
self.video_widget.installEventFilter(self)
self.audio_label = QLabel()
self.audio_label.setFixedSize(500, 400)
self.audio_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
self.audio_label.setWordWrap(True)
font = QFont()
font.setPointSize(16)
font.setBold(True)
self.audio_label.setFont(font)
self.audio_label.setVisible(False)
self.audio_label.installEventFilter(self)
media_layout.addWidget(self.video_widget, alignment=Qt.AlignmentFlag.AlignCenter)
media_layout.addWidget(self.audio_label, alignment=Qt.AlignmentFlag.AlignCenter)
# Set up media player
self.audio_output = QAudioOutput()
self.media_player = QMediaPlayer()
self.media_player.setVideoOutput(self.video_widget)
self.media_player.setAudioOutput(self.audio_output)
self.media_player.positionChanged.connect(self.update_position)
self.media_player.durationChanged.connect(self.update_duration)
self.media_player.playbackStateChanged.connect(self.on_playback_state_changed)
# Create video controls
video_controls_layout = QHBoxLayout()
# Play/Pause button
self.play_button = QToolButton()
self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
self.play_button.clicked.connect(self.toggle_play_pause)
video_controls_layout.addWidget(self.play_button)
# Current time label
self.time_label = QLabel("00:00 / 00:00")
self.time_label.setMinimumWidth(100)
video_controls_layout.addWidget(self.time_label)
# Seekbar - replace standard QSlider with our ClickableSlider
self.seek_slider = ClickableSlider(Qt.Orientation.Horizontal)
self.seek_slider.setRange(0, 0)
self.seek_slider.sliderMoved.connect(self.set_position)
self.seek_slider.sliderPressed.connect(self.on_slider_pressed)
self.seek_slider.sliderReleased.connect(self.on_slider_released)
video_controls_layout.addWidget(self.seek_slider, 4) # Give seekbar more space
# Volume button and slider
self.volume_button = QToolButton()
self.volume_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaVolume))
self.volume_button.clicked.connect(self.toggle_mute)
video_controls_layout.addWidget(self.volume_button)
self.volume_slider = QSlider(Qt.Orientation.Horizontal)
self.volume_slider.setRange(0, 100)
self.volume_slider.setValue(70) # Default volume
self.volume_slider.setMaximumWidth(100)
self.volume_slider.valueChanged.connect(self.set_volume)
self.audio_output.setVolume(0.7) # Set initial volume to 70%
video_controls_layout.addWidget(self.volume_slider)
# Add all controls to the media layout
media_layout.addLayout(video_controls_layout)
# Add container to stack instead of self.video_widget directly.
self.preview_stack.addWidget(self.text_preview) # index 0
self.preview_stack.addWidget(image_container) # index 1
self.preview_stack.addWidget(media_container) # index 2
self.preview_splitter.addWidget(self.preview_stack)
# Bottom pane: metadata info
self.media_info = QPlainTextEdit()
self.media_info.setReadOnly(True)
self.preview_splitter.addWidget(self.media_info)
splitter.addWidget(self.preview_container)
splitter.setSizes([800, 400]) # Initial left-right ratio
# Make the preview panel invisible by default
self.preview_container.setVisible(self.preview_enabled) # Use the loaded setting instead of always hidden
# Load last sort settings from config
config = read_config()
self.sort_column = config.get("sort_column", -1)
self.sort_order = Qt.SortOrder(config.get("sort_order", 0)) # 0 = Ascending, 1 = Descending
# If there was a saved column, show it in the UI
if self.sort_column != -1:
self.tree.header().setSortIndicator(self.sort_column, self.sort_order)
self.query_history = config.get("query_history", [])
self.query_completer = QCompleter(self.query_history)
self.query_completer.setCaseSensitivity(Qt.CaseSensitivity.CaseInsensitive)
self.edit_query.setCompleter(self.query_completer)
# ========== Signal bindings ==========
self.search_timer = QTimer()
self.search_timer.setSingleShot(True)
self.search_timer.timeout.connect(self.start_search)
self.edit_query.textChanged.connect(self.on_query_changed)
# connect Enter key press
self.edit_query.returnPressed.connect(self.on_search_enter)
self.edit_dir.textChanged.connect(self.on_dir_changed)
self.chk_file_name.stateChanged.connect(lambda: self.search_timer.start(DEBOUNCE_DELAY))
self.chk_match_case.stateChanged.connect(lambda: self.search_timer.start(DEBOUNCE_DELAY))
self.chk_full_match.stateChanged.connect(lambda: self.search_timer.start(DEBOUNCE_DELAY))
self.edit_min_size.textChanged.connect(self.reapply_filter)
self.edit_max_size.textChanged.connect(self.reapply_filter)
self.edit_extension.textChanged.connect(self.reapply_filter)
self.tree.itemSelectionChanged.connect(self.on_tree_selection_changed)
self.tree.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self.show_context_menu)
self.tree.itemDoubleClicked.connect(self.open_with_default_app)
self.single_context_menu = QMenu(self)
self.single_context_menu.addAction("Open", self.open_with_default_app)
self.single_context_menu.addAction("Delete", self.delete_file)
self.single_context_menu.addAction("Copy to...", self.copy_file)
self.single_context_menu.addAction("Move to...", self.move_file)
self.single_context_menu.addAction("Rename", self.rename_file)
self.single_context_menu.addAction("Copy full path with file name", self.copy_full_path)
self.single_context_menu.addAction("Copy path without file name", self.copy_path_only)
self.single_context_menu.addAction("Copy file name only", self.copy_file_name_only)
self.single_context_menu.addAction("Open in Finder", self.open_in_finder)
self.single_context_menu.addAction("Export to CSV", self.export_to_csv)
self.multi_context_menu = QMenu(self)
self.multi_context_menu.addAction("Open", self.open_multiple_files)
self.multi_context_menu.addAction("Delete", self.delete_multiple_files)
self.multi_context_menu.addAction("Copy to...", self.copy_multiple_files)
self.multi_context_menu.addAction("Move to...", self.move_multiple_files)
self.multi_context_menu.addAction("Batch Rename", self.batch_rename_files)
self.batch_size = 100
self.current_loaded = 0
self.tree.verticalScrollBar().valueChanged.connect(self.check_scroll_position)
# Create the standalone player window but don't show it yet
self.standalone_player = StandalonePlayerWindow(self)
self.standalone_player_active = False
# Configure standalone player
self.standalone_player.setup_extensions(self.video_extensions, self.audio_extensions)
self.standalone_player.set_continuous_playback(self.continuous_playback)
self.standalone_player.set_dark_mode(self.dark_mode)
# Create the media player manager for embedded player
self.player_manager = MediaPlayerManager(self)
# Set up media player
self.audio_output = self.player_manager.audio_output
self.media_player = self.player_manager.media_player
self.player_manager.set_video_output(self.video_widget)
self.player_manager.connect_signals(
self.update_position,
self.update_duration,
self.on_playback_state_changed
)
# Set up recognized extensions in the player manager
self.player_manager.setup_extensions(self.video_extensions, self.audio_extensions)
# ========== Preview logic ==========
def on_tree_selection_changed(self):
# if preview is not visible, do nothing
if not self.preview_container.isVisible():
return
selected_items = self.tree.selectedItems()
if not selected_items or len(selected_items) != 1:
# For multiple or no selection: stop media playback and clear preview
self.player_manager.stop()
self.preview_stack.setCurrentIndex(0)
self.text_preview.setPlainText("")
self.media_info.setPlainText("") # Clear bottom pane
return
path = selected_items[0].text(3)
if not os.path.isfile(path):
self.player_manager.stop()
self.preview_stack.setCurrentIndex(0)
self.text_preview.setPlainText("No preview available.")
self.media_info.setPlainText("")
return
# Stop previous media playback
self.player_manager.stop()
# If standalone player is active, use it instead
if self.standalone_player_active:
self.show_in_standalone_player(path)
return
# Display basic file info in the bottom pane
self.display_file_info(path)
# Check file extension for preview type
_, ext = os.path.splitext(path)
ext = ext.lower()
if ext in self.image_extensions or ext == ".svg":
self.display_image_preview(path, ext)
elif ext in self.video_extensions:
self.display_video_preview(path)
elif ext in self.audio_extensions:
self.display_audio_preview(path)
else:
self.display_text_preview(path)
def display_file_info(self, path):
"""Display basic file information in the info pane"""
file_stat = os.stat(path)
size_kb = round(file_stat.st_size / 1024, 2)
self.media_info.setPlainText(
f"File: {path}\nSize: {size_kb} KB\nLast Modified: {time.ctime(file_stat.st_mtime)}"
)
def display_image_preview(self, path, ext):
"""Handle display of image files"""
if ext == ".gif":
movie = QMovie(path)
self.image_label.setMovie(movie)
movie.start()
# Show resolution info from the current frame if available
pix = movie.currentPixmap()
self.media_info.appendPlainText(
f"Resolution: {pix.width()} x {pix.height()}"
)
elif ext == ".svg":
renderer = QSvgRenderer(path)
default_size = renderer.defaultSize()
container_size = self.image_label.size()
ratio = min(container_size.width() / default_size.width(),
container_size.height() / default_size.height())
new_width = int(default_size.width() * ratio)
new_height = int(default_size.height() * ratio)
pixmap = QPixmap(new_width, new_height)
pixmap.fill(Qt.GlobalColor.transparent)
painter = QPainter(pixmap)
renderer.render(painter)
painter.end()
self.image_label.setPixmap(pixmap)
self.media_info.appendPlainText(
f"Resolution: {new_width} x {new_height}"
)
else:
pixmap = QPixmap(path)
# Scale down using KeepAspectRatio if pixmap is larger than image_label
if (pixmap.width() > self.image_label.width()) or (pixmap.height() > self.image_label.height()):
pixmap = pixmap.scaled(