-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlurch
More file actions
executable file
·325 lines (281 loc) · 10.6 KB
/
lurch
File metadata and controls
executable file
·325 lines (281 loc) · 10.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
#!/usr/bin/env python3
import argparse
import signal
import sys
import os
import subprocess
import time
import webbrowser
from PyQt5.Qt import *
from pynput.keyboard import Key, Controller
import pyotp
def do_autotype(gui, filter, entry):
"""
Auto type value into the currently focusses window.
"""
gui.hide()
keyboard = Controller()
keyboard.type(entry['value'])
if 'enter' not in entry or entry['enter'] is True:
time.sleep(0.2)
keyboard.press(Key.enter)
time.sleep(0.2)
keyboard.release(Key.enter)
time.sleep(0.2)
gui.quit()
def do_browser(gui, filter, entry):
"""
Open value in browser. {q} is replaced with the filter typed by the user.
"""
url = entry["value"].format(filter=filter)
webbrowser.open_new_tab(url)
gui.quit()
def do_exec(gui, filter, entry):
"""
Execute value as a command. Optionally capture the output and show it in
the console.
"""
# If we need to capture output of the command, do so. Otherwise, just run
# it.
if (entry.get("output_win", False) is True or
entry.get("output_inline", False) is True):
p = subprocess.Popen(
entry["value"].replace('{filter}', filter),
shell=entry.get("shell", False),
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT
)
output = p.communicate()[0]
else:
p = subprocess.Popen(
entry["value"].replace('{filter}', filter),
shell=entry.get("shell", False),
)
# Clear filter typed by user
if entry.get('clear_input', True) is True:
gui.clear_filter()
# Display command output in seperate window, or in the inline console.
if entry.get('output_win', False) is True:
msg(output)
elif entry.get('output_inline', False) is True:
gui.append_console_output(output.decode('utf8'))
# Do not quit the main gui
return
gui.quit()
def do_totp(gui, filter, entry):
"""
Generate TOTP / rfc6238 / two-factor / Google Authenticator authentication
codes, and autotype them.
"""
totp = pyotp.TOTP(entry["value"])
code = totp.now()
gui.hide()
keyboard = Controller()
keyboard.type(code)
gui.quit()
do_mapper = {
"autotype": do_autotype,
"browser": do_browser,
"exec": do_exec,
"totp": do_totp,
}
class BaseGUI(QMainWindow):
def __init__(self, app_vendor, app_name, args, icon=None, toolbar_items=None):
self.app_vendor = app_vendor
self.app_name = app_name
self.args = args
self.icon = icon
self.toolbar_items = toolbar_items
# Make sure ctrl-c on the commandline stops the application
signal.signal(signal.SIGINT, signal.SIG_DFL)
self.app = QApplication(args)
self.settings = QSettings(self.app_vendor, self.app_name)
self.central_widget = QWidget()
QMainWindow.__init__(self)
self.setWindowTitle(self.app_name)
if self.icon is not None:
self.setWindowIcon(QIcon(self.icon))
self.setMinimumSize(450, 600)
self.setCentralWidget(self.central_widget)
# Create toolbar
if self.toolbar_items is not None:
self.toolbar = self.addToolBar('toolbar')
for toolbar_item in self.toolbar_items:
action = QAction(QIcon.fromTheme(toolbar_item["icon"]),
toolbar_item["label"],
self)
action.setData(toolbar_item["id"])
if toolbar_item["type"] == "check":
action.setCheckable(True)
if toolbar_item["shortcut"] is not None:
action.setShortcut(toolbar_item["shortcut"])
event_cb = getattr(self, "_ev_{}".format(toolbar_item["event"]))
action.triggered.connect(event_cb)
self.toolbar.addAction(action)
def run(self):
self.show()
self.app.exec_()
def quit(self):
QCoreApplication.quit()
def closeEvent(self, event):
self.quit()
class Lurch(BaseGUI):
def __init__(self, entries, console_height, *args, **kwargs):
self.entries = entries
self.console_height = console_height
self.icons = {}
BaseGUI.__init__(self, *args, **kwargs)
self.filter = QLineEdit()
self.filter.setStyleSheet(
"""
QLineEdit {
background: #252525;
color: #FFFFFF;
font-size: 16px;
border-radius: 0px;
padding: 10px;
}
"""
);
self.splitter = QSplitter(Qt.Vertical)
self.mini_console = QTextEdit()
#font-family: monospace;
self.mini_console.setStyleSheet(
"""
QTextEdit {
background: #000000;
color: #FFFFFF;
border-radius: 0px;
padding: 10px;
}
"""
);
self.mini_console.setWordWrapMode(QTextOption.NoWrap)
self.list = QListWidget(self);
self.list.setStyleSheet(
"""
QListWidget {
font-size: 16px;
}
"""
);
self.populate_list()
self.layout = QVBoxLayout()
self.layout.setSpacing(0)
self.central_widget.setLayout(self.layout)
self.splitter.addWidget(self.mini_console)
self.splitter.addWidget(self.list)
self.splitter.setSizes([0, 1])
self.layout.setContentsMargins(0, 0, 0, 0);
self.layout.addWidget(self.filter)
self.layout.addWidget(self.splitter)
self.filter.textEdited.connect(self._ev_text_edited)
self.filter.textEdited.connect(self._ev_text_edited)
self.filter.returnPressed.connect(self._ev_return_pressed)
self.list.itemActivated.connect(self._ev_return_pressed)
# Setup keybindings
QShortcut(QKeySequence("Escape"), self).activated.connect(self.quit)
QShortcut(QKeySequence("Up"), self).activated.connect(self.cursor_up)
QShortcut(QKeySequence("Ctrl+k"), self).activated.connect(self.cursor_up)
QShortcut(QKeySequence("Down"), self).activated.connect(self.cursor_down)
QShortcut(QKeySequence("Ctrl+j"), self).activated.connect(self.cursor_down)
self.filter.setFocus()
def populate_list(self, filter=""):
self.list.clear()
match_entries = self.entries
if filter != "":
parts = filter.lower().split(' ')
for part in parts:
match_entries = [
entry for entry in match_entries
if part in entry["title"].lower() or
entry.get("always", False) is True
]
for entry in match_entries:
item = QListWidgetItem(self._get_entry_icon(entry),
entry["title"],
self.list);
self.list.setCurrentRow(0)
def clear_filter(self):
self.filter.clear()
self.populate_list()
def append_console_output(self, output):
sizes = self.splitter.sizes()
self.splitter.setSizes([self.console_height, sizes[1] - self.console_height])
self.splitter.refresh()
self.mini_console.moveCursor(QTextCursor.End)
self.mini_console.insertHtml("<code>{}<br></code>".format(output.replace("\n", "<br>")))
def cursor_up(self):
if self.list.currentRow() == 0:
self.list.setCurrentRow(self.list.count() - 1)
else:
self.list.setCurrentRow(self.list.currentRow() - 1)
def cursor_down(self):
if self.list.currentRow() == self.list.count() - 1:
self.list.setCurrentRow(0)
else:
self.list.setCurrentRow(self.list.currentRow() + 1)
def _get_entry_icon(self, entry):
icon_name = entry.get("icon", None)
if icon_name is not None:
if icon_name not in self.icons:
self.icons[icon_name] = QIcon("/usr/local/lib/lurch/icons/{}.png".format(icon_name))
return self.icons[icon_name]
else:
return QIcon("icons/json.png")
def _ev_text_edited(self, text):
self.populate_list(text)
def _ev_return_pressed(self):
cur_item = self.list.currentItem().text()
filter = self.filter.text()
for entry in self.entries:
if entry["title"] == cur_item:
method = do_mapper[entry['type']]
method(self, filter, entry)
return
def read_entries(lines):
"""
Parse `lines` (stdin, usually) into actual entries that lurch can use.
Entries are separated with two newlines in `lines` (a.k.a. one empty line).
"""
bool_keys = ("shell", "always", "output_win", "output_inline", "clear_input", "enter")
required_keys = ("type", "title", "value")
entries = []
cur_entry = {}
for line in lines:
line = line.strip("\n")
try:
if line == "":
# End of current entry. Make sure the user has specified all
# required keys
assert(all([key in cur_entry for key in required_keys]))
entries.append(cur_entry)
cur_entry = {}
else:
# Additional key/value for current entry.
key, value = [part.lstrip() for part in line.split(":", 1)]
if key in bool_keys:
cur_entry[key] = {"true": True, "false": False}[value.lower()]
else:
cur_entry[key] = value
except Exception as err:
raise
# Add last entry, unless input ends with empty line
if cur_entry:
assert(all([key in cur_entry for key in required_keys]))
entries.append(cur_entry)
return entries
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--width', metavar='WIDTH', dest='width', type=int, default=500)
parser.add_argument('--height', metavar='HEIGHT', dest='height', type=int, default=600)
parser.add_argument('--console-height', metavar='CONSOLE_HEIGHT', dest='console_height', type=int, default=70)
args = parser.parse_args()
app = Lurch(read_entries(sys.stdin.readlines()),
args.console_height,
"electricmonk",
"lurch",
sys.argv,
icon=os.path.join(os.path.dirname(sys.argv[0]), 'icon.png'),
)
app.run()