-
Notifications
You must be signed in to change notification settings - Fork 94
/
Copy pathangrysearch.py
executable file
·1742 lines (1454 loc) · 65 KB
/
angrysearch.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
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
ANGRYsearch - file search, instant results as you typeself.
Attempt of making multiplatform version of Everything Search Engine
https://www.voidtools.com/
"""
# Hide docstring warnings
# Ignore imported but not used
# Hide warning function is too complex
# pylama:ignore=D100,D101,D102,D103,D105,W0611,C901
import base64
import locale
import mimetypes
import os
import platform
import re
import shlex
import shutil
import sqlite3
import subprocess
import sys
import time
from datetime import datetime
from itertools import permutations
from operator import itemgetter
from os.path import join as join_path
import PyQt5.QtCore as Qc
import PyQt5.QtGui as Qg
import PyQt5.QtWidgets as Qw
# THE DATABASE WAS BUILD USING FTS5 EXTENSION OF SQLITE3
FTS5_AVAILABLE = False
# CONFIG AND DATABASE PATHS
TEMP_PATH = Qc.QStandardPaths.standardLocations(
Qc.QStandardPaths.TempLocation)[0]
CACHE_PATH = Qc.QStandardPaths.standardLocations(
Qc.QStandardPaths.CacheLocation)[0]
CONFIG_PATH = Qc.QStandardPaths.standardLocations(
Qc.QStandardPaths.ConfigLocation)[0] + '/angrysearch/angrysearch.conf'
DATABASE_PATH = join_path(os.path.expanduser('~'),
CACHE_PATH,
'angrysearch',
'angry_database.db')
def run_query(query, parameters=()):
"""Run any query."""
query_result = con.execute(query, parameters)
return query_result
# THREAD FOR ASYNC SEARCHES IN THE DATABASE
# RETURNS FIRST 500(number_of_results) RESULTS MATCHING THE QUERY
# fts VALUE DECIDES IF USE FAST "MATCH" OR SLOWER BUT SUBSTRING AWARE "LIKE"
class ThreadDBQuery(Qc.QThread):
db_query_signal = Qc.pyqtSignal(str, list, list)
def __init__(self, db_query, setting_params, parent=None):
super().__init__()
self.words_quoted = None
self.number_of_results = setting_params['number_of_results']
self.fts = setting_params['fts']
self.regex_mode = setting_params['regex_mode']
self.db_query = db_query
def run(self):
"""Run user's search query"""
if self.regex_mode:
q = "SELECT * FROM angry_table WHERE path REGEXP ? LIMIT ?"
params = (self.db_query, self.number_of_results)
elif self.fts:
sql_query = self.match_query_adjustment(self.db_query)
q = "SELECT * FROM angry_table WHERE angry_table MATCH ? LIMIT ?"
params = (sql_query, self.number_of_results)
else:
sql_query = self.like_query_adjustment(self.db_query)
q = "SELECT * FROM angry_table WHERE path LIKE ? LIMIT ?"
params = (sql_query, self.number_of_results)
db_query_result = run_query(q, params).fetchall()
self.db_query_signal.emit(self.db_query,
db_query_result,
self.words_quoted)
# FTS CHECKBOX IS UNCHECKED, SO NO INDEXING
# PERMUTATION OF INPUT PHRASES IS USED SO THAT ORDER DOES NOT MATTER
def like_query_adjustment(self, input_text):
input_text = input_text.replace('"', '""')
o = []
p = permutations(input_text.strip().split())
for x in p:
o.append('"%{0}%"'.format('%'.join(x)))
return ' OR path LIKE '.join(o)
# FTS CHECKBOX IS CHECKED, FTS VIRTUAL TABLES ARE USED
def match_query_adjustment(self, input_text):
for x in {'\\', '?', '(', ')', '*'}:
if x in input_text:
input_text = input_text.replace(x, '')
query_words = input_text.strip().split()
if FTS5_AVAILABLE:
# MINUS SIGN MARKS PHRASES THAT MUST NOT APPEAR IN RESULTS
words_no_minus = []
excluded_words = []
for x in query_words:
if x.startswith('-'):
if len(x) > 1:
excluded_words.append(x[1:])
else:
words_no_minus.append(x)
if not words_no_minus:
words_no_minus.append('1')
# QUOTED PHRASES ARE SEARCHED WITHOUT WILD CARD * AT THE END
final_query = ''
words_quoted = []
for x in words_no_minus:
if '\"' in x:
if x.startswith('\"') and x.endswith('\"'):
x = x.replace('\"', '')
final_query += '"{}" '.format(x)
words_quoted.append(x)
continue
x = x.replace('\"', '')
if '\'' in x:
if x.startswith('\'') and x.endswith('\''):
x = x.replace('\'', '')
final_query += '"{}" '.format(x)
words_quoted.append(x)
continue
x = x.replace('\'', '')
final_query += '"{}"* '.format(x)
if len(excluded_words) > 0:
exclude_query_part = ''
for x in excluded_words:
x_is_quoted = False
if '\"' in x:
if x.startswith('\"') and x.endswith('\"'):
x_is_quoted = True
x = x.replace('\"', '')
if '\'' in x:
if x.startswith('\'') and x.endswith('\''):
x_is_quoted = True
x = x.replace('\'', '')
if x_is_quoted:
if len(x) > 1:
exclude_query_part += 'NOT {} '.format(x)
else:
exclude_query_part += 'NOT {}* '.format(x)
final_query = '{} {}'.format(final_query,
exclude_query_part)
self.words_quoted = words_quoted
return final_query
if not FTS5_AVAILABLE:
final_query = ''
words_quoted = []
for x in query_words:
if '\"' in x:
if x.startswith('\"') and x.endswith('\"'):
x = x.replace('\"', '')
final_query += '"{}" '.format(x)
words_quoted.append(x)
continue
x = x.replace('\"', '')
if '\'' in x:
if x.startswith('\'') and x.endswith('\''):
x = x.replace('\'', '')
final_query += '"{}" '.format(x)
words_quoted.append(x)
continue
x = x.replace('\'', '')
final_query += '{}* '.format(x)
self.words_quoted = words_quoted
return final_query
# THREAD FOR PREVENTING DATABASE QUERY BEING DONE ON EVERY SINGLE KEYPRESS
# SHORT WAIT TIME LETS USER FINISH TYPING, OFF BY DEFAULT
class ThreadDelayDBQuery(Qc.QThread):
delay_signal = Qc.pyqtSignal(str)
def __init__(self, input_text, parent=None):
super().__init__()
self.input_text = input_text
def run(self):
time.sleep(0.2)
self.delay_signal.emit(self.input_text)
# THREAD FOR UPDATING THE DATABASE
# PREVENTS LOCKING UP THE GUI AND ALLOWS TO SHOW PROGRESS
# NEW DATABASE IS CREATED IN /tmp AND REPLACES ONE IN /.cache/angrysearch
class ThreadDBUpdate(Qc.QThread):
db_update_signal = Qc.pyqtSignal(str, str)
crawl_signal = Qc.pyqtSignal(str)
def __init__(self, lite, dirs_excluded, parent=None):
super().__init__()
self.lite = lite
self.table = []
self.prep_excluded = []
self.crawl_time = ''
self.database_time = ''
for x in dirs_excluded:
y = [k.encode() for k in x.split('/') if k]
z = ''
# IF FULL PATH
if x.startswith('/'):
up = b'/' + b'/'.join(y[:-1])
z = {'case': 1, 'ign': y[-1], 'up': up}
# IF ONLY SINGLE DIRECTORY NAME
elif len(y) == 1:
z = {'case': 2, 'ign': y[-1], 'up': ''}
# IF PARENT/TARGET
elif len(y) == 2:
z = {'case': 3, 'ign': y[-1], 'up': y[-2]}
if z:
self.prep_excluded.append(z)
self.directories_timestamp = {}
def run(self):
self.db_update_signal.emit('label_1', '0')
self.crawling_drives()
self.db_update_signal.emit('label_2', self.crawl_time)
self.new_database()
self.db_update_signal.emit('label_3', self.database_time)
self.replace_old_db_with_new()
self.db_update_signal.emit('the_end_of_the_update', '0')
def crawling_drives(self):
def error(err):
print(err)
root_dir = b'/'
tstart = datetime.now()
dir_list = []
file_list = []
try:
# SCANDIR ALLOWS MUCH FASTER INDEXING OF THE FILE SYSTEM, OBVIOUS
# IN LITE MODE IS NOW PART OF PYTHON 3.5, FUNCTIONALLY
# REPLACING os.walk
import scandir
except ImportError:
scandir = os
for root, dirs, files in scandir.walk(root_dir, onerror=error):
dirs.sort()
files.sort()
if root == b'/' and b'proc' in dirs:
dirs.remove(b'proc')
# SLICING WITH [:] SO THAT THE LIST ID STAYS THE SAME
dirs[:] = self.remove_excluded_dirs(dirs, root, self.prep_excluded)
self.crawl_signal.emit(
root.decode(encoding='utf-8', errors='ignore'))
if self.lite:
for dname in dirs:
dir_list.append(('1', os.path.join(root, dname).decode(
encoding='UTF-8', errors='ignore')))
for fname in files:
file_list.append(('0', os.path.join(root, fname).decode(
encoding='UTF-8', errors='ignore')))
else:
for dname in dirs:
path = os.path.join(root, dname)
utf_path = path.decode(encoding='utf-8', errors='ignore')
try:
stats = os.lstat(path)
epoch_time = int(stats.st_mtime.__trunc__())
except:
print("Can't access: " + str(path))
epoch_time = 0
dir_list.append(('1', utf_path, '', epoch_time))
for fname in files:
path = os.path.join(root, fname)
utf_path = path.decode(encoding='utf-8', errors='ignore')
try:
stats = os.lstat(path)
size = stats.st_size
epoch_time = int(stats.st_mtime.__trunc__())
except:
print("Can't access: " + str(path))
size = 0
epoch_time = 0
file_list.append(('0', utf_path, size, epoch_time))
self.table = dir_list + file_list
self.crawl_time = self.time_difference(tstart)
def new_database(self):
global con
temp_db_path = TEMP_PATH + '/angry_database.db'
tstart = datetime.now()
if os.path.exists(temp_db_path):
if con:
con.close()
os.remove(temp_db_path)
con = sqlite3.connect(temp_db_path, check_same_thread=False)
cur = con.cursor()
if self.lite:
if self.fts5_pragma_check():
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts5(directory UNINDEXED, path)''')
cur.execute('''PRAGMA user_version = 4;''')
else:
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts4(directory, path,
notindexed=directory)''')
cur.execute('''PRAGMA user_version = 3;''')
cur.executemany('''INSERT INTO angry_table VALUES (?, ?)''',
self.table)
else:
if self.fts5_pragma_check():
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts5(directory UNINDEXED,
path,
size UNINDEXED, date UNINDEXED)''')
cur.execute('''PRAGMA user_version = 4;''')
else:
cur.execute('''CREATE VIRTUAL TABLE angry_table
USING fts4(directory, path, size, date,
notindexed=directory,
notindexed=size,
notindexed=date)''')
cur.execute('''PRAGMA user_version = 3;''')
cur.executemany('''INSERT INTO angry_table VALUES (?, ?, ?, ?)''',
self.table)
con.commit()
self.database_time = self.time_difference(tstart)
def replace_old_db_with_new(self):
global con
global DATABASE_PATH
temp_db_path = TEMP_PATH + '/angry_database.db'
dir_path = os.path.dirname(DATABASE_PATH)
if not os.path.exists(temp_db_path):
return
if not os.path.exists(dir_path):
os.makedirs(dir_path)
if con:
con.close()
shutil.move(temp_db_path, DATABASE_PATH)
con = sqlite3.connect(DATABASE_PATH, check_same_thread=False)
con.create_function("regexp", 2, regexp)
def time_difference(self, tstart):
time_diff = datetime.now() - tstart
mins, secs = divmod(time_diff.seconds, 60)
return '{:0>2d}:{:0>2d}'.format(mins, secs)
def remove_excluded_dirs(self, dirs, root, to_ignore):
after_exclusion = []
for x in dirs:
for z in to_ignore:
if x == z['ign']:
if z['case'] == 1:
if root == z['up']:
self.show_ignored(root, z['ign'])
break
elif z['case'] == 2:
self.show_ignored(root, z['ign'])
break
elif z['case'] == 3:
y = [k for k in root.split(b'/') if k]
if y[-1] == z['up']:
self.show_ignored(root, z['ign'])
break
else:
after_exclusion.append(x)
return after_exclusion
def show_ignored(self, root, item):
r = root.decode(encoding='utf-8', errors='ignore')
i = item.decode(encoding='utf-8', errors='ignore')
if r == '/':
print('Ignoring directory: /{}'.format(i))
else:
print('Ignoring directory: {}/{}'.format(r, i))
# FTS5 IS A NEW EXTENSION OF SQLITE
# SQLITE NEEDS TO BE COMPILED WITH FTS5 ENABLED
def fts5_pragma_check(self):
with sqlite3.connect(':memory:') as conn:
cur = conn.cursor()
cur.execute('pragma compile_options;')
available_pragmas = cur.fetchall()
return ('ENABLE_FTS5', ) in available_pragmas
# THREAD FOR GETTING MIMETYPE OF A FILE CURRENTLY SELECTED
class ThreadMimetype(Qc.QThread):
mime_signal = Qc.pyqtSignal(str, str)
def __init__(self, path, parent=None):
super().__init__()
self.path = path
def run(self):
if not os.path.exists(self.path):
mimetype = 'NOT FOUND'
else:
mime = subprocess.Popen(['xdg-mime',
'query',
'filetype',
self.path],
stdout=subprocess.PIPE)
mime.wait()
if mime.returncode == 0:
mimetype = str(mime.communicate()[0].decode('latin-1').strip())
elif mime.returncode == 5:
mimetype = 'NO PERMISSION'
else:
mimetype = 'NOPE'
self.mime_signal.emit(self.path, mimetype)
# CUSTOM TABLE MODEL TO HAVE FINE CONTROL OVER THE CONTENT AND PRESENTATION
class AngryTableModel(Qc.QAbstractTableModel):
sort_changed_signal = Qc.pyqtSignal(int, int)
def __init__(self, table_data=None, setting_params=None, parent=None):
super().__init__()
if table_data is None:
table_data = [[]]
self.table_data = table_data
if setting_params['angrysearch_lite']:
self.headers = ['Name', 'Path']
else:
self.headers = ['Name', 'Path', 'Size', 'Date Modified']
def rowCount(self, parent=None, *args, **kwargs):
return len(self.table_data)
def columnCount(self, parent=None, *args, **kwargs):
return len(self.headers)
def headerData(self, section, orientation, role=None):
if role == Qc.Qt.DisplayRole and orientation == Qc.Qt.Horizontal:
return self.headers[section]
def data(self, index, role=None):
if role == Qc.Qt.DisplayRole:
row = index.row()
column = index.column()
value = self.table_data[row][column]
if column == 3:
return value
return value.text()
if role == Qc.Qt.DecorationRole and index.column() == 0:
row = index.row()
column = index.column()
value = self.table_data[row][column]
return value.icon()
def sort(self, column, order=None):
self.sort_changed_signal.emit(column, order)
if column == 0:
self.layoutAboutToBeChanged.emit()
self.table_data.sort(key=lambda z: z[0]._name)
if order == Qc.Qt.DescendingOrder:
self.table_data.reverse()
self.table_data.sort(key=lambda z: z[0]._is_dir, reverse=True)
self.layoutChanged.emit()
elif column == 1:
self.layoutAboutToBeChanged.emit()
self.table_data.sort(key=lambda z: z[0]._parent_dir)
self.table_data.sort(key=lambda z: z[0]._is_dir, reverse=True)
self.layoutChanged.emit()
elif column == 2:
self.layoutAboutToBeChanged.emit()
self.table_data.sort(key=lambda z: z[2]._bytes)
if order == Qc.Qt.DescendingOrder:
self.table_data.reverse()
self.table_data.sort(key=lambda z: z[0]._is_dir, reverse=True)
self.layoutChanged.emit()
elif column == 3:
self.layoutAboutToBeChanged.emit()
self.table_data.sort(key=lambda z: z[3])
if order == Qc.Qt.DescendingOrder:
self.table_data.reverse()
self.table_data.sort(key=lambda z: z[0]._is_dir, reverse=True)
self.layoutChanged.emit()
def itemFromIndex(self, row, col):
return self.table_data[row][col]
# CUSTOM TABLE VIEW TO EASILY ADJUST ROW HEIGHT AND COLUMN WIDTH
class AngryTableView(Qw.QTableView):
def __init__(self, lite=True, row_height=0, parent=None):
super().__init__()
self.lite = lite
if row_height and row_height != 0:
self.verticalHeader().setDefaultSectionSize(row_height)
def resizeEvent(self, event):
width = event.size().width()
if self.lite:
self.setColumnWidth(0, int(width * 0.40))
self.setColumnWidth(1, int(width * 0.60))
else:
self.setColumnWidth(0, int(width * 0.30))
self.setColumnWidth(1, int(width * 0.38))
self.setColumnWidth(2, int(width * 0.10))
self.setColumnWidth(3, int(width * 0.22))
# ROW IS HIGHLIGHTED THE MOMENT THE TABLE IS FOCUSED
def focusInEvent(self, event):
Qw.QTableView.focusInEvent(self, event)
row = self.currentIndex().row()
if row != -1:
self.selectRow(row)
def keyPressEvent(self, event):
# ENTER KEY AND NUMPAD ENTER, AND WITH SHIFT
if event.key() == 16777220 or event.key() == 16777221:
index = self.currentIndex()
if event.modifiers() == Qc.Qt.ShiftModifier:
self.parent().parent().key_press_Enter(index, shift=True)
return
self.parent().parent().key_press_Enter(index, shift=False)
return
# TAB KEY GOES TO NEXT WIDGET NOT NEXT ROW IN THE TABLE
if event.key() == 16777217:
self.clearSelection()
self.parent().focusNextChild()
return
# SHIFT + TAB KEY
if event.key() == 16777218:
self.clearSelection()
self.parent().focusPreviousChild()
return
Qw.QTableView.keyPressEvent(self, event)
def contextMenuEvent(self, event):
right_click_menu = Qw.QMenu(self)
act_open = right_click_menu.addAction('Open')
act_open.triggered.connect(self.parent().parent().right_clk_open)
act_open_path = right_click_menu.addAction('Open Path')
act_open_path.triggered.connect(self.parent().parent().right_clk_path)
right_click_menu.addSeparator()
act_copy_path = right_click_menu.addAction('Copy Path')
act_copy_path.triggered.connect(self.parent().parent().right_clk_copy)
right_click_menu.exec_(event.globalPos())
# THE PRIMARY GUI DEFINING INTERFACE WIDGET, THE WIDGET WITHIN THE MAINWINDOW
class CenterWidget(Qw.QWidget):
def __init__(self, setting_params=None):
super().__init__()
self.setting_params = setting_params
self.search_input = Qw.QLineEdit()
self.table = AngryTableView(self.setting_params['angrysearch_lite'],
self.setting_params['row_height'])
self.upd_button = Qw.QPushButton('update')
self.fts_checkbox = Qw.QCheckBox()
grid = Qw.QGridLayout()
grid.setSpacing(10)
grid.addWidget(self.search_input, 1, 1)
grid.addWidget(self.fts_checkbox, 1, 3)
grid.addWidget(self.upd_button, 1, 4)
grid.addWidget(self.table, 2, 1, 4, 4)
self.setLayout(grid)
self.setTabOrder(self.search_input, self.table)
self.setTabOrder(self.table, self.upd_button)
# THE MAIN APPLICATION WINDOW WITH THE STATUS BAR AND LOGIC
# LOADS AND SAVES QSETTINGS FROM ~/.config/angrysearch
# INITIALIZES AND SETS GUI, WAITING FOR USER INPUTS
class AngryMainWindow(Qw.QMainWindow):
def __init__(self, parent=None):
super().__init__()
self.settings = Qc.QSettings(CONFIG_PATH, Qc.QSettings.IniFormat)
self.setting_params = {
'angrysearch_lite': True,
'fts': True,
'typing_delay': False,
'darktheme': False,
'fm_path_doubleclick_selects': False,
'icon_theme': 'adwaita',
'file_manager': 'xdg-open',
'row_height': 0,
'number_of_results': 500,
'directories_excluded': [],
'conditional_mounts_for_autoupdate': [],
'notifications': True,
'regex_mode': False,
'close_on_execute': False
}
# FOR REGEX MODE, WHEN REGEX QUERY CAN BE RUN SO ONLY ONE ACCESS DB
self.regex_query_ready = True
self.read_settings()
self.init_gui()
def keyPressEvent(self, event):
if type(event) == Qg.QKeyEvent:
# ESC
if event.key() == 16777216:
self.close()
# CTRL + Q
if event.key() == 81:
if event.modifiers() == Qc.Qt.ControlModifier:
self.close()
# F6 KEY
if event.key() == 16777269:
self.center.search_input.selectAll()
self.center.search_input.setFocus()
# ALT + D
if event.key() == 68 and event.modifiers() == Qc.Qt.AltModifier:
self.center.search_input.selectAll()
self.center.search_input.setFocus()
# CTRL + L
if event.key() == 76:
if event.modifiers() == Qc.Qt.ControlModifier:
self.center.search_input.selectAll()
self.center.search_input.setFocus()
# F8 FOR REGEX SEARCH MODE
if event.key() == 16777271:
self.setting_params['regex_mode'] = not self.setting_params['regex_mode']
self.settings.setValue('regex_mode', self.setting_params['regex_mode'])
self.regex_mode_color_indicator()
if self.setting_params['regex_mode']:
self.status_bar.showMessage('REGEX MODE ENABLED')
else:
self.status_bar.showMessage('REGEX MODE DISABLED')
# CTRL + W
if event.key() == 87:
if event.modifiers() == Qc.Qt.ControlModifier:
input_text = self.center.search_input.text().split()
if not input_text:
return
last_removed = ' '.join(input_text[:-1])
if len(input_text) > 1:
last_removed = last_removed + ' '
self.center.search_input.setText(last_removed)
event.accept()
else:
event.ignore()
def regex_mode_color_indicator(self):
if self.setting_params['regex_mode']:
self.center.search_input.setStyleSheet(
'background: #FF6A00; color: #000000;')
else:
self.center.search_input.setStyleSheet('')
def read_settings(self):
if self.settings.value('Last_Run/geometry'):
self.restoreGeometry(self.settings.value('Last_Run/geometry'))
else:
self.resize(720, 540)
qr = self.frameGeometry()
cp = Qw.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
self.move(qr.topLeft())
if self.settings.value('Last_Run/window_state'):
self.restoreState(self.settings.value('Last_Run/window_state'))
self.read_qsettings_item('angrysearch_lite', 'bool')
self.read_qsettings_item('fast_search_but_no_substring', 'bool')
self.read_qsettings_item('typing_delay', 'bool')
self.read_qsettings_item('darktheme', 'bool')
self.read_qsettings_item('fm_path_doubleclick_selects', 'bool')
self.read_qsettings_item('icon_theme', 'str')
self.read_qsettings_item('row_height', 'int')
self.read_qsettings_item('number_of_results', 'int')
self.read_qsettings_item('directories_excluded', 'list')
self.read_qsettings_item('file_manager', 'fm')
self.read_qsettings_item('conditional_mounts_for_autoupdate', 'list')
self.read_qsettings_item('notifications', 'bool')
self.read_qsettings_item('regex_mode', 'bool')
self.read_qsettings_item('close_on_execute', 'bool')
if self.settings.value('Last_Run/last_sort'):
k = self.settings.value('Last_Run/last_sort')
if isinstance(k, list) and len(k) == 2:
if self.setting_params['angrysearch_lite'] and int(k[0]) > 1:
k[0] = 1
self.setting_params['last_sort'] = [int(x) for x in k]
else:
self.setting_params['last_sort'] = [1, 0]
else:
self.setting_params['last_sort'] = [1, 0]
def read_qsettings_item(self, item, type_):
if self.settings.value(item):
k = self.settings.value(item)
if type_ == 'bool':
if k.lower() in ['false', 'no', '0', 'n', 'none']:
if item == 'fast_search_but_no_substring':
item = 'fts'
self.setting_params[item] = False
else:
self.setting_params[item] = True
if type_ == 'str':
self.setting_params[item] = k
if type_ == 'int':
if k.isdigit():
self.setting_params[item] = int(k)
if type_ == 'list':
self.setting_params[item] = shlex.split(k.strip())
if type_ == 'fm':
if k in ['', 'xdg-open']:
self.setting_params[item] = self.detect_file_manager()
else:
self.setting_params[item] = k
else:
if type_ == 'fm':
self.setting_params[item] = self.detect_file_manager()
def detect_file_manager(self):
try:
fm = subprocess.check_output(['xdg-mime',
'query',
'default',
'inode/directory'])
detected_fm = fm.decode('utf-8').strip().lower()
known_fm = ['dolphin',
'nemo',
'nautilus',
'doublecmd',
'thunar',
'pcmanfm-qt',
'pcmanfm',
'spacefm']
for x in known_fm:
if x in detected_fm:
print('autodetected file manager: ' + x)
return x
return 'xdg-open'
except Exception as err:
print(err)
return 'xdg-open'
def closeEvent(self, event):
self.settings.setValue('Last_Run/geometry', self.saveGeometry())
self.settings.setValue('Last_Run/window_state', self.saveState())
if not self.settings.contains('angrysearch_lite'):
self.settings.setValue('angrysearch_lite', True)
if not self.settings.contains('fast_search_but_no_substring'):
self.settings.setValue('fast_search_but_no_substring', True)
if not self.settings.contains('typing_delay'):
self.settings.setValue('typing_delay', False)
if not self.settings.contains('darktheme'):
self.settings.setValue('darktheme', False)
if not self.settings.contains('fm_path_doubleclick_selects'):
self.settings.setValue('fm_path_doubleclick_selects', False)
if not self.settings.contains('icon_theme'):
self.settings.setValue('icon_theme', 'adwaita')
if not self.settings.contains('file_manager'):
self.settings.setValue('file_manager', '')
if not self.settings.contains('row_height'):
self.settings.setValue('row_height', 0)
if not self.settings.contains('number_of_results'):
self.settings.setValue('number_of_results', 500)
if not self.settings.contains('directories_excluded'):
self.settings.setValue('directories_excluded', '')
if not self.settings.contains('conditional_mounts_for_autoupdate'):
self.settings.setValue('conditional_mounts_for_autoupdate', '')
if not self.settings.contains('notifications'):
self.settings.setValue('notifications', True)
if not self.settings.contains('regex_mode'):
self.settings.setValue('regex_mode', False)
if not self.settings.contains('close_on_execute'):
self.settings.setValue('close_on_execute', False)
# TRAY ICON NEEDS TO BE HIDDEN
# SO THAT THE MAIN WINDOW INSTANCE AUTOMATICALLY DELETES IT ON CLOSING
self.tray_icon.hide()
event.accept()
def init_gui(self):
self.icon = self.get_tray_icon()
self.setWindowIcon(self.icon)
if self.setting_params['darktheme']:
self.style_data = ''
if os.path.isfile('qdarkstylesheet.qss'):
f = open('qdarkstylesheet.qss', 'r')
self.style_data = f.read()
f.close()
self.setStyleSheet(self.style_data)
elif os.path.isfile('/usr/share/angrysearch/qdarkstylesheet.qss'):
f = open('/usr/share/angrysearch/qdarkstylesheet.qss', 'r')
self.style_data = f.read()
f.close()
self.setStyleSheet(self.style_data)
elif os.path.isfile('/opt/angrysearch/qdarkstylesheet.qss'):
f = open('/opt/angrysearch/qdarkstylesheet.qss', 'r')
self.style_data = f.read()
f.close()
self.setStyleSheet(self.style_data)
self.queries_threads = []
self.waiting_threads = []
self.mime_type_threads = []
self.last_keyboard_input = {'time': 0, 'input': ''}
self.last_number_of_results = 500
self.file_list = []
self.icon_dictionary = self.get_mime_icons()
self.center = CenterWidget(self.setting_params)
self.setCentralWidget(self.center)
self.setWindowTitle('ANGRYsearch')
self.status_bar = Qw.QStatusBar(self)
self.setStatusBar(self.status_bar)
self.center.fts_checkbox.setToolTip(
'check = fast search but no substrings\n'
'uncheck = slower but substrings work')
if self.setting_params['fts']:
self.center.fts_checkbox.setChecked(True)
self.center.fts_checkbox.stateChanged.connect(self.checkbox_fts_click)
self.center.table.setGridStyle(0)
self.center.table.setSortingEnabled(True)
self.center.table.sortByColumn(1, 0)
self.center.table.setEditTriggers(Qw.QAbstractItemView.NoEditTriggers)
self.center.table.setSelectionBehavior(Qw.QAbstractItemView.SelectRows)
self.center.table.horizontalHeader().setStretchLastSection(True)
self.center.table.setAlternatingRowColors(True)
self.center.table.verticalHeader().setVisible(False)
self.center.table.setVerticalScrollBarPolicy(Qc.Qt.ScrollBarAlwaysOn)
self.center.table.setSelectionMode(
Qw.QAbstractItemView.SingleSelection)
self.center.table.setItemDelegate(self.HTMLDelegate())
self.center.table.activated.connect(self.double_click_enter)
self.center.search_input.textChanged[str].connect(
self.wait_for_finishing_typing)
self.center.upd_button.clicked.connect(self.clicked_button_updatedb)
self.database_age()
self.show()
self.show_first_500()
self.make_sys_tray()
self.center.search_input.setFocus()
self.center.search_input.returnPressed.connect(self.focusNextChild)
self.regex_mode_color_indicator()
def make_sys_tray(self):
if Qw.QSystemTrayIcon.isSystemTrayAvailable():
menu = Qw.QMenu()
menu.addAction('v1.0.4')
menu.addSeparator()
exitAction = menu.addAction('Quit')
exitAction.triggered.connect(self.close)
self.tray_icon = Qw.QSystemTrayIcon()
self.tray_icon.setIcon(self.icon)
self.tray_icon.setContextMenu(menu)
self.tray_icon.show()
self.tray_icon.setToolTip('ANGRYsearch')
self.tray_icon.activated.connect(self.sys_tray_clicking)
def sys_tray_clicking(self, reason):
if (reason == Qw.QSystemTrayIcon.DoubleClick or
reason == Qw.QSystemTrayIcon.Trigger):
self.show()
elif (reason == Qw.QSystemTrayIcon.MiddleClick):
self.close()
def get_tray_icon(self):
base64_data = '''iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHN
CSVQICAgIfAhkiAAAAQNJREFUOI3t1M9KAlEcxfHPmP0xU6Ogo
G0teoCiHjAIfIOIepvKRUE9R0G0KNApfy0c8hqKKUMrD9zVGc4
9nPtlsgp5n6qSVSk7cBG8CJ6sEX63UEcXz4jE20YNPbygPy25Q
o6oE+fEPXFF7A5yA9Eg2sQDcU3sJd6k89O4iiMcYKVol3rH2Mc
a1meZ4hMdNPCIj+SjHHfFZU94/0Nwlv4rWoY7vhrdeLNoO86bG
lym/ge3lsHDdI2fojbBG6sUtzOiQ1wQOwk6GwWKHeJyHtxOcFi
0TpFaxmnhNcyIW45bQ6RS3Hq4MeB7Ltyahki9Gd2xidWiwG9va
nCZqi7xlZGVHfwN6+5nU/ccBUYAAAAASUVORK5CYII='''
pm = Qg.QPixmap()
pm.loadFromData(base64.b64decode(base64_data))
i = Qg.QIcon()
i.addPixmap(pm)
return i
# OFF BY DEFAULT
# 0.2 SEC DELAY TO LET USER FINISH TYPING BEFORE INPUT BECOMES A DB QUERY
def wait_for_finishing_typing(self, input_text):
if not self.setting_params['typing_delay']:
self.new_query_new_thread(input_text)
return
self.last_keyboard_input = input_text
self.waiting_threads.append(ThreadDelayDBQuery(input_text))
self.waiting_threads[-1].delay_signal.connect(
self.waiting_done, Qc.Qt.QueuedConnection)
self.waiting_threads[-1].start()
def waiting_done(self, waiting_data):
if self.last_keyboard_input == waiting_data:
self.new_query_new_thread(waiting_data)
if len(self.waiting_threads) > 100:
del self.waiting_threads[0:80]
# NEW DATABASE QUERY ADDED TO LIST OF RECENT RUNNING THREADS
def new_query_new_thread(self, input_text):
if not self.setting_params['fts'] or self.setting_params['regex_mode']:
self.status_bar.showMessage(' ...')
if input_text == '' and self.regex_query_ready:
self.show_first_500()
return
if self.setting_params['regex_mode']:
try:
re.compile(input_text)
is_valid = True
except re.error:
is_valid = False
if not is_valid:
self.status_bar.showMessage('regex not valid')
return
self.queries_threads.append(
{'input': input_text,
'thread': ThreadDBQuery(input_text, self.setting_params)})
self.queries_threads[-1]['thread'].db_query_signal.connect(