forked from MarkHedleyJones/dmenu-extended
-
Notifications
You must be signed in to change notification settings - Fork 0
/
dmenu_extended.py
executable file
·1368 lines (1157 loc) · 52.7 KB
/
dmenu_extended.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
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import os
import subprocess
import signal
import json
import codecs
import locale
# Python 3 urllib import with Python 2 fallback
try:
import urllib.request as urllib2
except:
import urllib2
# Find out the system's favouite encoding
system_encoding = locale.getpreferredencoding()
path_base = os.path.expanduser('~') + '/.config/dmenu-extended'
path_cache = path_base + '/cache'
path_prefs = path_base + '/config'
path_plugins = path_base + '/plugins'
file_prefs = path_prefs + '/dmenuExtended_preferences.txt'
file_cache = path_cache + '/dmenuExtended_all.txt'
file_cache_binaries = path_cache + '/dmenuExtended_binaries.txt'
file_cache_files = path_cache + '/dmenuExtended_files.txt'
file_cache_folders = path_cache + '/dmenuExtended_folders.txt'
file_cache_aliases = path_cache + '/dmenuExtended_aliases.txt'
file_cache_aliasesLookup = path_cache + '/dmenuExtended_aliases_lookup.json'
file_cache_plugins = path_cache + '/dmenuExtended_plugins.txt'
# file_shCmd = '~/.dmenuEextended_shellCommand.sh'
default_prefs = {
"valid_extensions": [
"py", # Python script
"svg", # Vector graphics
"pdf", # Portable document format
"txt", # Plain text
"png", # Image file
"jpg", # Image file
"gif", # Image file
"php", # PHP source-code
"tex", # LaTeX document
"odf", # Open document format
"ods", # Open document spreadsheet
"avi", # Video file
"mpg", # Video file
"mp3", # Music file
"lyx", # Lyx document
"bib", # LaTeX bibliograpy
"iso", # CD image
"ps", # Postscript document
"zip", # Compressed archive
"xcf", # Gimp image format
"doc", # Microsoft document format
"docx" # Microsoft document format
"xls", # Microsoft spreadsheet format
"xlsx", # Microsoft spreadsheet format
"md", # Markup document
"html", # HTML document
"sublime-project" # Project file for sublime
],
"watch_folders": ["~/"], # Base folders through which to search
"follow_symlinks": False, # Follow links to other locations
"ignore_folders": [], # Folders to exclude from the search
"scan_hidden_folders": False, # Enter hidden folders while scanning for items
"include_hidden_files": False, # Include hidden files in the cache
"include_hidden_folders": False, # Include hidden folders in the cache
"include_items": [], # Extra items to display - manually added
"exclude_items": [], # Items to hide - manually hidden
"include_binaries": True,
"filter_binaries": False, # Only include binaries that have an associated .desktop file
"include_applications": True, # Add items from /usr/share/applications
"alias_applications": False, # Alias applications with their common names
"aliased_applications_format": "{name} ({command})",
"path_shellCommand": "~/.dmenuEextended_shellCommand.sh",
"menu": 'dmenuv', # Executable for the menu
"menu_arguments": [
"-b", # Place at bottom of screen
"-i", # Case insensitive searching
"-nf", # Element foreground colour
"#888888",
"-nb", # Element background colour
"#1D1F21",
"-sf", # Selected element foreground colour
"#ffffff",
"-sb", # Selected element background colour
"#1D1F21",
"-fn", # Font and size
"-*-terminus-medium-*-*-*-14-*-*-*-*-*-*-*",
"-l", # Number of lines to display
"20",
"-w",
"0.4",
"-g",
"Tc"
],
"fileopener": "xdg-open", # Program to handle opening files
"filebrowser": "xdg-open", # Program to handle opening paths
"webbrowser": "xdg-open", # Program to hangle opening urls
"terminal": "terminator", # Terminal
"indicator_submenu": "->", # Symbol to indicate a submenu item
"indicator_edit": "*", # Symbol to indicate an item will launch an editor
"indicator_alias": "#" # Symbol to indecate an aliased command
}
def setup_user_files():
""" Returns nothing
Create a path for the users prefs files to be stored in their
home folder. Create default config files and place them in the relevant
directory.
"""
print('Setting up dmenu-extended prefs files...')
try:
os.makedirs(path_plugins)
print('Plugins directory created')
except OSError:
print('Plugins directory exists - skipped')
try:
os.makedirs(path_cache)
print('Cache directory created')
except OSError:
print('Cache directory exists - skipped')
try:
os.makedirs(path_prefs)
print('prefs directory created')
except OSError:
print('prefs directory exists - skipped')
# If relevant binaries exist, swap them out for the more appropriate items
# It has been decided against setting gnome-open or gvfs-open as a default
# file handler to prevent intermittent failure to open a text editor
# required to edit the configuration file.
# if os.path.exists('/usr/bin/gnome-open'):
# default_prefs['fileopener'] = 'gnome-open'
# default_prefs['webbrowser'] = 'gnome-open'
# default_prefs['filebrowser'] = 'gnome-open'
if os.path.exists('/usr/bin/gnome-terminal'):
default_prefs['terminal'] = 'gnome-terminal'
if os.path.exists('/usr/bin/urxvt'):
default_prefs['terminal'] = 'urxvt'
# Dump the prefs file
if os.path.exists(file_prefs) == False:
with open(file_prefs,'w') as f:
json.dump(default_prefs, f, sort_keys=True, indent=4)
print('Preferences file created at: ' + file_prefs)
else:
print('Existing preferences file found, will not overwrite.')
# Create package __init__ - for easy access to the plugins
with open(path_plugins + '/__init__.py','w') as f:
f.write('import os\n')
f.write('import glob\n')
f.write('__all__ = [ os.path.basename(f)[:-3] for f in glob.glob(os.path.dirname(__file__)+"/*.py")]')
if (os.path.exists(path_plugins + '/__init__.py') and
os.path.exists(file_cache) and
os.path.exists(file_prefs)):
sys.path.append(path_base)
else:
setup_user_files()
sys.path.append(path_base)
import plugins
def load_plugins(debug=False):
if debug:
print('Loading plugins')
plugins_loaded = [{"filename": "plugin_settings.py",
"plugin": extension()}]
if debug:
plugins_loaded[0]['plugin'].debug = True
for plugin in plugins.__all__:
if plugin not in ['__init__', 'plugin_settings.py']:
try:
__import__('plugins.' + plugin)
exec('plugins_loaded.append({"filename": "' + plugin + '.py", "plugin": plugins.' + plugin + '.extension()})')
if debug:
plugins_loaded[-1]['plugin'].debug = True
print('Loaded plugin ' + plugin)
except Exception as e:
if debug:
print('Error loading plugin ' + plugin)
print(str(e))
os.remove(path_plugins + '/' + plugin + '.py')
if debug:
print('!! Plugin was deleted to prevent interruption to dmenuExtended')
return plugins_loaded
class dmenu(object):
plugins_loaded = False
prefs = False
debug = False
preCommand = False
def get_plugins(self, force=False):
""" Returns a list of loaded plugins
This method will load plugins in the plugins directory if they
havent already been loaded. Optionally, you may force the
reloading of plugins by setting the parameter 'force' to true.
"""
if self.plugins_loaded == False:
self.plugins_loaded = load_plugins(self.debug)
elif force:
if self.debug:
print("Forced reloading of plugins")
# For Python2/3 compatibility
try:
# Python2
reload(plugins)
except NameError:
# Python3
from imp import reload
reload(plugins)
self.plugins_loaded = load_plugins(self.debug)
return self.plugins_loaded
def system_path(self):
"""
Array containing system paths
"""
# Get the PATH environmental variable
path = os.environ.get('PATH')
# If we're in Python <3 (less-than-three), we want this to be a unicode string
# In python 3, all strings are unicode already, trying to decode gives AttributeError
try:
path = path.decode(sys.getfilesystemencoding())
except AttributeError:
pass
# Split and remove duplicates
path = list(set(path.split(':')))
# Some paths contain an extra separator, remove the empty path
try:
path.remove('')
except ValueError:
pass
return path
def application_paths(self):
""" Array containing the paths to application flies
Based on PyXDG (https://github.com/takluyver/pyxdg)
"""
# Get the home applications directory (usually ~/.local/share/applications)
home_folder = os.path.expanduser('~')
data_home = os.environ.get('XDG_DATA_HOME',os.path.join(home_folder,'.local','share'))
paths = [os.path.join(data_home,'applications')]
# Get other directories
data_other = os.environ.get('XDG_DATADIRS','/usr/local/share:/usr/share').split(":")
paths.extend([os.path.join(direc,'applications') for direc in data_other])
# Filter paths that don't exist
paths = filter(os.path.isdir, paths)
return paths
def load_json(self, path):
""" Loads and retuns the parsed contents of a specified json file
This method will return 'False' if either the file does not exist
or the specified file could not be parsed as valid json.
"""
if os.path.exists(path):
with codecs.open(path,'r',encoding=system_encoding) as f:
try:
return json.load(f)
except:
if self.debug:
print("Error parsing prefs from json file " + path)
self.prefs = default_prefs
option = "Edit file manually"
response = self.menu("There is an error opening " + path + "\n" + option)
if response == option:
self.open_file(path)
else:
if self.debug:
print('Error opening json file ' + path)
print('File does not exist')
return False
def save_json(self, path, items):
""" Saves a dictionary to a specified path using the json format"""
with codecs.open(path, 'w', encoding=system_encoding) as f:
json.dump(items, f, sort_keys=True, indent=4)
def load_preferences(self):
if self.prefs == False:
self.prefs = self.load_json(file_prefs)
if self.prefs == False:
self.open_file(file_prefs)
sys.exit()
else:
# If there are things in the default that aren't in the
# user config, resave the user configuration
resave = False
for key, value in default_prefs.items():
if key not in self.prefs:
self.prefs[key] = value
resave = True
if resave:
self.save_preferences()
def save_preferences(self):
self.save_json(file_prefs, self.prefs)
def connect_to(self, url):
request = urllib2.Request(url)
response = urllib2.urlopen(request)
return response.read().decode(system_encoding)
def download_text(self, url):
return self.connect_to(url)
def download_json(self, url):
return json.loads(self.connect_to(url))
def message_open(self, message):
self.load_preferences()
self.message = subprocess.Popen([self.prefs['menu']] + self.prefs['menu_arguments'],
stdin=subprocess.PIPE,
preexec_fn=os.setsid)
msg = str(message)
msg = "Proszę czekać: " + msg
msg = msg.encode(system_encoding)
self.message.stdin.write(msg)
self.message.stdin.close()
def message_close(self):
os.killpg(self.message.pid, signal.SIGTERM)
def menu(self, items, prompt=False):
self.load_preferences()
if prompt == False:
p = subprocess.Popen([self.prefs['menu']] + self.prefs['menu_arguments'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
else:
p = subprocess.Popen([self.prefs['menu']] + self.prefs['menu_arguments'] + ['-p', prompt],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
if type(items) == list:
items = "\n".join(items)
out = p.communicate(items.encode(system_encoding))[0]
if out.strip() == '':
sys.exit()
else:
return out.decode().strip('\n')
def select(self, items, prompt=False, numeric=False):
result = self.menu(items, prompt)
for index, item in enumerate(items):
if result.find(item) != -1:
if numeric:
return index
else:
return item
return -1
def sort_shortest(self, items):
items.sort(key=len)
return items
def open_url(self, url):
self.load_preferences()
if self.debug:
print('Opening url: "' + url + '" with ' + self.prefs['webbrowser'])
self.execute(self.prefs['webbrowser'] + ' ' + url.replace(' ', '%20'))
def open_directory(self, path):
self.load_preferences()
if self.debug:
print('Opening folder: "' + path + '" with ' + self.prefs['filebrowser'])
self.execute(self.prefs['filebrowser'] + ' "' + path + '"')
def open_terminal(self, command, hold=False, direct=False):
self.load_preferences()
sh_command_file = os.path.expanduser(self.prefs['path_shellCommand']);
with open(sh_command_file, 'w') as f:
f.write("#! /bin/bash\n")
f.write(command + ";\n")
if hold == True:
f.write('echo "\n\nPress enter to exit";')
f.write('read var;')
os.chmod(os.path.expanduser(sh_command_file), 0o744)
os.system(self.prefs['terminal'] + ' -e ' + sh_command_file)
def open_file(self, path):
self.load_preferences()
if self.debug:
print('Opening file with command: ' + self.prefs['fileopener'] + " '" + path + "'")
exit_code = self.execute(self.prefs['fileopener'] + ' "' + path + '"', fork=False)
if exit_code is not 0:
open_failure = False
offer = None
if exit_code == 256 and self.prefs['fileopener'] == 'gnome-open':
open_failure = True
offer = 'xdg-open'
elif exit_code == 4 and self.prefs['fileopener'] == 'xdg-open':
open_failure = True
if open_failure:
mimetype = str(self.command_output('xdg-mime query filetype ' + path)[0])
message = ["Error: " + self.prefs['fileopener'] + " reports no application is associated with this filetype (MIME type: " + mimetype + ")"]
if offer is not None:
option = "Try opening with " + offer + "?"
message.append(option)
if self.menu(message) == option:
self.prefs['fileopener'] = offer
self.open_file(path)
def execute(self, command, fork=None):
"""
Execute a command on behalf of dmenu. Will fork into background
by default unless fork=False. Will prepend the value of
self.preCommand to the given command, necessary for sudo calls.
"""
if fork == False:
extra = ''
else:
extra = ' &'
if self.preCommand:
command = self.preCommand + command
return os.system(command + extra)
def cache_regenerate(self, message=True):
if message:
self.message_open('budowanie cache...\nTo może chwilę potrwać (wciśnij enter aby kontynuować w tle).')
cache = self.cache_build()
if message:
self.message_close()
return cache
def cache_save(self, items, path):
with codecs.open(path, 'w',encoding=system_encoding) as f:
if type(items) == list:
for item in items:
f.write(item+"\n")
else:
f.write(items)
return 1
def cache_open(self, path):
try:
if self.debug:
print('Opening cache at ' + path)
with codecs.open(path,'r',encoding=system_encoding) as f:
return f.read()
except:
return False
def cache_load(self, exitOnFail=False):
cache_plugins = self.cache_open(file_cache_plugins)
cache_scanned = self.cache_open(file_cache)
if cache_plugins == False or cache_scanned == False:
if exitOnFail:
sys.exit()
else:
if self.cache_regenerate() == False:
self.menu(['Error caching data'])
sys.exit()
else:
return self.cache_load(exitOnFail=True)
return cache_plugins + cache_scanned
def command_output(self, command, split=True):
if type(command) != list:
command = command.split(" ")
tmp = subprocess.check_output(command)
out = tmp.decode(system_encoding)
if split:
return out.split("\n")
else:
return out
def scan_binaries(self):
out = []
for path in self.system_path():
if not os.path.exists(path):
continue
for binary in os.listdir(path):
if binary[:3] is not 'gpk':
out.append(binary)
return out
def format_alias(self, name, command):
return self.prefs['indicator_alias'] + ' ' + self.prefs['aliased_applications_format'].format(name=name, command=command)
def scan_applications(self):
paths = self.system_path()
applications = []
for app_path in self.application_paths():
for filename in os.listdir(app_path):
pathname = os.path.join(app_path,filename)
if os.path.isfile(pathname):
# Open the application file using the system's preferred encoding (probably utf-8)
with codecs.open(pathname,'r',encoding=system_encoding, errors='ignore') as f:
name = None
command = None
terminal = None
for line in f.readlines():
if line[0:5] == 'Exec=':
command_tmp = line[5:-1].split()
command = ''
space = ''
for piece in command_tmp:
if piece.find('%') == -1:
command += space + piece
space = ' '
else:
break
elif line[0:5] == 'Name=':
name = line[5:-1]
elif line[0:9] == 'Terminal=':
if line[9:-1].lower() == 'true':
terminal = True
else:
terminal = False
if name is not None and command is not None:
if terminal is None:
terminal = False
for path in paths:
if command[0:len(path)] == path:
if command[len(path)+1:].find('/') == -1:
command = command[len(path)+1:]
applications.append({
'name': name,
'command': command,
'terminal': terminal,
'descriptor': filename.replace('.desktop','')
})
break
return applications
def retrieve_aliased_command(self, alias):
"""
Return the command intended to be executed by the given alias.
"""
aliases = self.load_json(file_cache_aliasesLookup)
if self.debug:
print("Converting '" + str(alias) + "' into its aliased command")
for item in aliases:
if item[0] == alias:
return item[1]
if self.debug:
print("No suitable candidate was found")
def plugins_available(self):
self.load_preferences()
if self.debug:
print('Ładuję dostępne pluginy...')
plugins = self.get_plugins(True)
plugin_titles = []
for plugin in plugins:
if hasattr(plugin['plugin'], 'is_submenu') and plugin['plugin'].is_submenu:
plugin_titles.append(self.prefs['indicator_submenu'] + ' ' + plugin['plugin'].title)
else:
plugin_titles.append(plugin['plugin'].title)
if self.debug:
print('Zrobione!')
print('Załadowane pluginy:')
print('First 5 items: ')
print(plugin_titles[:5])
print(str(len(plugin_titles)) + ' loaded in total')
print('')
out = self.sort_shortest(plugin_titles)
self.cache_save(out, file_cache_plugins)
return out
def try_remove(self, needle, haystack):
"""
Gracefully try to remove an item from an array. It not found, fire no
errors. This is a convenience function to reduce code size.
"""
try:
haystack.remove(needle)
except ValueError:
pass
def cache_build(self):
self.load_preferences()
valid_extensions = []
if 'valid_extensions' in self.prefs:
for extension in self.prefs['valid_extensions']:
if extension == '*':
valid_extensions = True
break
elif extension == '':
valid_extensions.append('')
elif extension[0] != '.':
extension = '.' + extension
valid_extensions.append(extension.lower())
applications = []
# Holds what binaries have been found
binaries = []
# Holds the directly searchable "# Htop (htop;)" lines
aliased_items = []
# Holds the [command, name] pairs for future lookup
aliases = []
# If we're going to include the applications or we want them for
# filtering purposes, scan the .desktop files and get the applications
if self.prefs['include_applications'] or self.prefs['filter_binaries']:
applications = self.scan_applications()
# Do we want to add binaries into the cache?
if self.prefs['include_binaries'] is True:
if self.prefs['filter_binaries'] is True:
binaries_raw = self.scan_binaries()
filterlist = [x['command'] for x in applications] + [x['descriptor'] for x in applications]
for item in filterlist:
if item in binaries_raw:
binaries.append(item)
else:
binaries = self.scan_binaries()
binaries = list(set(binaries))
# Do we want to add applications from .desktop files into the cache?
if self.prefs['include_applications']:
if self.prefs['alias_applications']:
if os.path.exists(file_cache_aliases):
os.remove(file_cache_aliases)
for app in applications:
command = app['command']
if app['terminal']:
command += ';'
if app['name'].lower() != app['command'].lower():
title = self.format_alias(app['name'], command)
self.try_remove(app['command'], binaries)
aliased_items.append(title)
aliases.append([title, command])
else:
binaries.append(command)
if app['terminal']:
# Remove any non-terminal invoking versions from cache
self.try_remove(app['command'], binaries)
else:
for app in applications:
command = app['command']
# Add the "run in terminal" indicator to the command
if app['terminal']:
command += ';'
binaries.append(command)
# Remove any non-terminal invoking versions from cache
if app['terminal']:
self.try_remove(app['command'], binaries)
binaries = list(set(binaries))
watch_folders = []
if 'watch_folders' in self.prefs:
watch_folders = self.prefs['watch_folders']
watch_folders = map(lambda x: x.replace('~', os.path.expanduser('~')), watch_folders)
if self.debug:
print('Done!')
print('Watch folders:')
print('Loading the list of folders to be excluded from the index...')
ignore_folders = []
if 'ignore_folders' in self.prefs:
for exclude_folder in self.prefs['ignore_folders']:
ignore_folders.append(exclude_folder.replace('~', os.path.expanduser('~')))
if self.debug:
print('Done!')
print('Excluded folders:')
print('First 5 items: ')
print(ignore_folders[:5])
print(str(len(ignore_folders)) + ' ignore_folders loaded in total')
print('')
filenames = []
foldernames = []
follow_symlinks = False
try:
if 'follow_symlinks' in self.prefs:
follow_symlinks = self.prefs['follow_symlinks']
except:
pass
if self.debug:
if follow_symlinks:
print('Indexing will not follow linked folders')
else:
print('Indexing will follow linked folders')
print('Scanning files and folders, this may take a while...')
for watchdir in watch_folders:
for root, dirs , files in os.walk(watchdir, followlinks=follow_symlinks):
dirs[:] = [d for d in dirs if os.path.join(root,d) not in ignore_folders]
if self.prefs['scan_hidden_folders'] or root.find('/.') == -1:
for name in files:
if self.prefs['include_hidden_files'] or name.startswith('.') == False:
if valid_extensions == True or os.path.splitext(name)[1].lower() in valid_extensions:
filenames.append(os.path.join(root,name))
for name in dirs:
if self.prefs['include_hidden_folders'] or name.startswith('.') == False:
foldernames.append(os.path.join(root,name) + '/')
foldernames = list(filter(lambda x: x not in ignore_folders, foldernames))
include_items = []
if 'include_items' in self.prefs:
include_items = []
for item in self.prefs['include_items']:
if type(item) == list:
if len(item) > 1:
title = self.prefs['indicator_alias']
title += ' ' + item[0]
aliased_items.append(title)
aliases.append([title, item[1]])
else:
if self.debug:
print("There are aliased items in the configuration with no command.")
else:
include_items.append(item)
else:
include_items = []
# Remove any manually added include items differing by a colon
# e.g. ["htop", "htop;"] becomes just ["htop;"]
for item in include_items:
if item[-1] == ';' and item[0:-1] in binaries:
binaries.remove(item[0:-1])
plugins = self.plugins_available()
# Save the alias lookup file and aliased_items
self.save_json(file_cache_aliasesLookup, aliases)
self.cache_save(aliased_items, file_cache_aliases)
self.cache_save(binaries, file_cache_binaries)
self.cache_save(foldernames, file_cache_folders)
self.cache_save(filenames, file_cache_files)
other = self.sort_shortest(include_items + aliased_items + binaries + foldernames + filenames)
if 'exclude_items' in self.prefs:
for item in self.prefs['exclude_items']:
try:
other.remove(item)
except ValueError:
pass
other += ['rebuild cache']
self.cache_save(other, file_cache)
out = plugins
out += other
if self.debug:
print('Done!')
print('Cache building has finished.')
print('')
return out
class extension(dmenu):
title = 'Ustawienia'
is_submenu = True
def __init__(self):
self.load_preferences()
plugins_index_url = 'https://raw.githubusercontent.com/manjaropl/dmenu-extended-plugins/master/plugins_index.json'
def rebuild_cache(self):
if self.debug:
print('Counting items in original cache')
cacheSize = len(self.cache_load().split("\n"))
if self.debug:
print('Przebudowywanie cache...')
result = self.cache_regenerate()
if self.debug:
print('Cache built')
print('Counting items in new cache')
newSize = len(self.cache_load().split("\n"))
if self.debug:
print('New cache size = ' + str(newSize))
cacheSizeChange = newSize - cacheSize
if self.debug:
if cacheSizeChange != 0:
print('This differs from original by ' + str(cacheSizeChange) + ' items')
else:
print('Cache size did not change')
response = []
if cacheSizeChange != 0:
if cacheSizeChange == 1:
status = 'jedna nowa pozycja została dodana.'
elif cacheSizeChange == -1:
status = 'jedna pozycja została usunięta.'
elif cacheSizeChange > 0:
status = str(cacheSizeChange) + ' pozycje zostały dodane.'
elif cacheSizeChange < 0:
status = str(abs(cacheSizeChange)) + ' pozycje zostały usunięte.'
else:
status = 'Nie dodano żadnych nowych pozycji'
response.append('Cache updated successfully; ' + status)
if result == 2:
response.append('NOTICE: Performance issues were encountered while caching data')
else:
response.append('Cache rebuilt; its size did not change.')
response.append('Cache zawiera ' + str(cacheSize) + ' pozycji.')
self.menu(response)
def rebuild_cache_plugin(self):
self.plugins_loaded = self.get_plugins(True)
self.cache_regenerate()
def download_plugins(self):
self.message_open('Pobieram listę pluginów...')
try:
plugins = self.download_json(self.plugins_index_url)
except:
self.message_close()
self.menu(["Błąd: Nie mogę się połączyć z repozytorium pluginów.",
"Sprawdź połączenie internetowe i spróbuj ponownie."])
sys.exit()
items = []
substitute = ('plugin_', '')
installed_plugins = self.get_plugins()
installed_pluginFilenames = []
for tmp in installed_plugins:
installed_pluginFilenames.append(tmp['filename'])
for plugin in plugins:
if plugin + '.py' not in installed_pluginFilenames:
items.append(plugin.replace(substitute[0], substitute[1]) + ' - ' + plugins[plugin]['desc'])
self.message_close()
if len(items) == 0:
self.menu(['Nie ma nowych pluginów do instalacji'])
else:
item = substitute[0] + self.select(items, 'Instaluj:')
if item != -1:
self.message_open("Pobieranie wybranego pluginu...")
plugin_name = item.split(' - ')[0]
plugin = plugins[plugin_name]
plugin_source = self.download_text(plugin['url'])
with open(path_plugins + '/' + plugin_name + '.py', 'w') as f:
for line in plugin_source:
f.write(line)
self.get_plugins(True)
self.message_close()
self.message_open("Rebuilding plugin cache")
self.plugins_available()
self.message_close()
self.menu(['Plugin pobrany i zainstalowany'])
if self.debug:
print("Dostępne pluginy:")
for plugin in self.plugins_available():
print(plugin)
def installed_plugins(self):
plugins = []
for plugin in self.get_plugins():
if plugin["plugin"].title is not "Ustawienia":
plugins.append(plugin["plugin"].title.replace(':','') + ' (' + plugin["filename"] + ')')
return plugins
def remove_plugin(self):
plugins = self.installed_plugins()
pluginText = self.select(plugins, prompt='Plugin do usunięcia:')
if pluginText != -1:
plugin = pluginText.split('(')[1].replace(')', '')
path = path_plugins + '/' + plugin
if os.path.exists(path):
os.remove(path)
self.menu(['Plugin "' + plugin + '" usunięty.'])
if self.debug:
print("Plugins available:")
for plugin in self.plugins_available():
print(plugin)
else:
self.plugins_available()
else:
if self.debug:
print('Error - Plugin not found')
else:
if self.debug:
print('Selection was not understood')
def update_plugins(self):
self.message_open('Sprawdzam aktualizację pluginów...')
plugins_here = list(map(lambda x: x['filename'].split('.')[0], self.get_plugins()))
plugins_here.remove('plugin_settings')
plugins_there = self.download_json(self.plugins_index_url)
updated = []
for here in plugins_here:
for there in plugins_there:
if there == here:
there_sha = plugins_there[there]['sha1sum']
here_sha = self.command_output("sha1sum " + path_plugins + '/' + here + '.py')[0].split()[0]
if self.debug:
print('Checking ' + here)
print('Local copy has sha of ' + here_sha)
print('Remote copy has sha of ' + there_sha)
if there_sha != here_sha:
sys.stdout.write("Hashes do not match, updating...\n")