/
dmenu-do
executable file
·309 lines (269 loc) · 8.92 KB
/
dmenu-do
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
#!/usr/bin/env python
# Copyright (C) 2012 Eyal Erez
#
# This program is free software; you can redistribute it and/or modify it under the terms of the GNU
# General Public License as published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
# even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License along with this program; if not,
# write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
# 02110-1301, USA.
import sys
import os
from subprocess import Popen, PIPE
from optparse import OptionParser
from ConfigParser import ConfigParser
from collections import defaultdict
import logging as log
##########
# CONSTS #
##########
def home(path):
return path.replace('~', os.environ['HOME'])
## File used to read configuration
CONFIG_FILE = home('~/.dmenu-do.conf')
SEC_SESSION = 'Session'
SEC_LOGGING = 'Logging'
SEC_HISTORY = 'History'
SEC_BROWSE = 'Browse'
SEC_COMMANDS = 'Commands'
OPT_FILE = 'file'
OPT_LEVEL = 'level'
OPT_DIRS = 'dirs'
OPT_DMENU = 'dmenu'
OPT_EXEC = 'executables'
#########
# UTILS #
#########
def execute(command,):
'''Execute command'''
log.debug('EXECUTE %s' % command)
os.popen(command + '&')
def is_executable(path):
'''Is this path an executable file'''
return os.path.isfile(path) and os.access(path, os.X_OK)
def is_directory(path):
'''Is this path a directory'''
return os.path.isdir(path)
##########
# CONFIG #
##########
class Config(object):
def __init__(self, config_file):
self._config = ConfigParser()
self._config.read(config_file)
# Init logging
log.basicConfig(filename=home(self._config.get(SEC_LOGGING, OPT_FILE)),
level=self._config.get(SEC_LOGGING, OPT_LEVEL))
# Get config values
self.session = dict(self._config.items(SEC_SESSION))
self.folders = [f.strip() for f in self._config.get(SEC_BROWSE, OPT_DIRS).split(',')]
self.history_file = home(self._config.get(SEC_HISTORY, OPT_FILE))
self.dmenu = [f.strip() for f in self._config.get(SEC_COMMANDS, OPT_DMENU).split(' ')]
self._exec = [f.strip() for f in self._config.get(SEC_COMMANDS, OPT_EXEC).split(' ')]
@property
def executables(self):
'''Get list of executables based on $PATH'''
path = os.environ['PATH'].split(':')
proc = Popen(self._exec + path, stdout=PIPE)
lines = []
line = proc.stdout.readline()
while line:
lines.append(line.strip())
line = proc.stdout.readline()
return lines
############
# LRU DICT #
############
class _LRUDict(object):
'''An OrderedDict allows a user to add key/value pairs, like a dict, but maintains the order of
addition. If an item is added more the once, it will move to the end of the list. So, the order
is LRU first. (Note: this implementation is not thread-safe)
'''
def __init__(self):
'''Create an empty dict'''
self._d = {}
self._k = []
def __len__(self):
self._dedup()
return len(self._k)
def __getitem__(self, key):
'''Get value'''
return self._d[key]
def __setitem__(self, key, value):
'''Set value'''
self._k.append(key)
self._d[key] = value
def __delitem__(self, key):
'''Remove item'''
self._k.remove(key)
del self._d[key]
def __contains__(self, key):
'''Contains key'''
return key in self._d
def keys(self):
'''Return list of keys in order of insertion'''
self._dedup()
return self._k
def items(self):
'''Return items as a list of (key, value) tuples'''
self._dedup()
items = []
for k in self._k:
items.append((k, self._d[k]))
return items
def _dedup(self):
'''Remove all key duplicates'''
# Count the number of duplicates
dups = defaultdict(int)
for k in self._k:
dups[k] += 1
ks = []
for k in self._k:
dups[k] -= 1
if dups[k] == 0:
ks.append(k)
self._k = ks
def __str__(self):
s = []
for k in self._k:
s.append('%s: %s' % (k, self._d[k]))
return '{%s}' % ', '.join(s)
###########
# HISTORY #
###########
class History(object):
TYPE_EXECUTABLE = "EXECUTABLE"
TYPE_FILE = "FILE"
def __init__(self, filename):
self._filename = filename
self._commands = _LRUDict()
try:
with file(self._filename, 'r') as reader:
for line in reader:
line = line.strip()
if line:
log.debug('READ HISTORY %s' % line)
name, command_type, command = line.split(',')
self._commands[name] = command_type, command
except IOError:
pass # file not found, this is fine, we'll just created it later.
def add_executable(self, command):
self._commands[command] = (self.TYPE_EXECUTABLE, command)
def add_file(self, name, path):
self._commands[name] = (self.TYPE_FILE, path)
def execute(self, name):
command_type, command = self._commands[name]
if self.TYPE_EXECUTABLE == command_type:
execute(command)
elif self.TYPE_FILE == command_type:
execute('see "%s"' % command)
else:
raise ValueError('Unknown command type "%s"' % command_type)
# Pop to first place
self._commands[name] = command_type, command
def keys(self):
return self._commands.keys()
def __contains__(self, key):
'''Contains key'''
return key in self._commands
def close(self):
log.debug('CLOSING')
log.debug('WRITING HISTORY %s' % self._filename)
with file(self._filename, 'w+') as writer:
for (name, (command_type, command)) in self._commands.items():
line = "%s,%s,%s" % (name, command_type, command)
log.debug(line)
writer.write(line)
writer.write('\n')
log.debug('DONE WRITING HISTORY %s' % self._filename)
#########
# DMENU #
#########
class DMenu(object):
def __init__(self, config, history):
self._current = None
self._config = config
self._history = history
def run(self, command=''):
'''Run the dmenu command recursively'''
items = []
# Figure out which items to display
if command:
# If current is empty, we are not walking a directory tree. So, try and see if this is a
# session command or a path executable.
if not self._current:
if command in self._history:
log.debug('HISTORY: %s' % command)
# This is a history command, so run it.
self._history.execute(command)
return
if command in self._config.session.keys():
log.debug('SESSION: %s' % command)
# This is a session command, so run it.
execute(self._config.session[command])
return
if command in self._config.executables:
log.debug('EXECUTABLE: %s' % command)
self._history.add_executable(command)
# This is an executable, so run it.
execute(command)
return
# Otherwise, we must be walking a path, so join our current path
path = os.path.join(self._current, home(command));
if is_directory(path):
log.debug('DIRECTORY: %s' % command)
# Update current path
self._current = path
# This is a directory, so we are going to list all child files and folders.
items = ['..'] + os.listdir(path)
elif is_executable(command):
# This is a full path executable, so run it.
log.debug('EXECUTABLE: %s' % command)
execute(command, path)
return
else:
# This is just a file, use mailcap and try to find the right program to run it.
log.debug('FILE: %s' % path)
self._history.add_file(command, path)
execute('see "%s"' % path)
return
else:
# If no command was passed in, show everything
items = self._history.keys() + \
self._config.folders + \
list(self._config.session.keys()) + \
sorted(self._config.executables)
# Open the dmenu command
proc = Popen(self._config.dmenu, shell=False, stdout=PIPE, stdin=PIPE)
# Run dmenu with the items defined above
for item in items:
proc.stdin.write(item)
proc.stdin.write('\n')
command = proc.communicate()[0]
# If we got something back, run dmenu again
if command:
self.run(command.strip())
########
# MAIN #
########
def main(config_file):
'''main method'''
config = Config(config_file)
history = History(config.history_file)
try:
dmenu = DMenu(config, history)
dmenu.run()
finally:
history.close()
if __name__ == '__main__':
parser = OptionParser()
parser.add_option("-c", "--config", dest="config_file",
help="Location of configuration file (defaults to %s" % CONFIG_FILE,
metavar="FILE", default=CONFIG_FILE)
(options, args) = parser.parse_args()
main(options.config_file)