forked from akkana/scripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathquickbrowse
More file actions
executable file
·416 lines (343 loc) · 14.9 KB
/
quickbrowse
File metadata and controls
executable file
·416 lines (343 loc) · 14.9 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
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
#!/usr/bin/env python3
import os
import sys
import signal
import traceback
import posixpath
from PyQt5.QtCore import QUrl, Qt, QTimer, QEvent
from PyQt5.QtWidgets import QApplication, QMainWindow, QToolBar, QAction, \
QLineEdit, QStatusBar, QProgressBar, QTabWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView, QWebEnginePage, \
QWebEngineProfile
from PyQt5 import QtWidgets
# The file used to remotely trigger the browser to open more tabs.
# The %d will be the process ID of the running browser.
URL_FILE = "/tmp/quickbrowse-urls-%d"
class ReadlineEdit(QLineEdit):
def __init__(self):
super (ReadlineEdit, self).__init__()
def keyPressEvent(self, event):
# http://pyqt.sourceforge.net/Docs/PyQt4/qt.html#Key-enum
if (event.modifiers() & Qt.ControlModifier):
k = event.key()
if k == Qt.Key_Control:
return
if k == Qt.Key_A:
self.home(False)
elif k == Qt.Key_E:
self.end(False)
elif k == Qt.Key_B:
self.cursorBackward(False, 1)
elif k == Qt.Key_F:
self.cursorForward(False, 1)
elif k == Qt.Key_H:
self.backspace()
elif k == Qt.Key_D:
self.del_()
elif k == Qt.Key_W:
self.cursorWordBackward(True)
self.del_()
elif k == Qt.Key_U:
self.clear()
return
# For anything else, call the base class.
super(ReadlineEdit, self).keyPressEvent(event)
# Need to subclass QWebEngineView, in order to have an object that
# can own each load_finished() callback and have a pointer to
# the main BrowserWindow so it can figure out which tab is loading.
class BrowserView(QWebEngineView):
def __init__(self, browserwin):
super(BrowserView, self).__init__()
self.settings().defaultSettings().setDefaultTextEncoding("utf-8")
self.browser_win = browserwin
self.installEventFilter(self)
# ICK! I can't find any way to intercept a middle click and get
# the URL under the mouse during the click. But we do get hover
# events -- so if we always record the last hovered URL,
# then when we see a middleclick we can load that URL.
# Again, ICK!
self.last_hovered = None
def eventFilter(self, source, event):
if (event.type() == QEvent.ChildAdded and source is self
and event.child().isWidgetType()):
self._glwidget = event.child()
self._glwidget.installEventFilter(self)
elif (event.type() == QEvent.MouseButtonPress
and source is self._glwidget):
if event.button() == 4: # middle button is 4. Go figure.
self.browser_win.new_tab(self.last_hovered)
return True
return super().eventFilter(source, event)
# Override the context menu event so we can copy the clipboard
# selection to primary after a "Copy Link URL" action.
# Qt5 only copies it to Clipboard, making X primary paste impossible.
def contextMenuEvent(self, event):
menu = self.page().createStandardContextMenu()
# In theory we could loop over actions, find one and change it.
# for action in menu.actions():
# print("Action", action.text())
# if action.text().startswith("Copy Link"):
# pass
# You can also apparently change an action with
# action.triggered.connect(qApp.quit)
action = menu.exec_(event.globalPos())
if (action and action.text().startswith("Copy")):
# Copy clipboard text to the primary selection:
qc = QApplication.clipboard()
qc.setText(qc.text(qc.Clipboard), qc.Selection)
#
# Slots
#
def url_changed(self, url):
if url != self.browser_win.urlbar.text():
# I can't find any way to find out about load errors.
# But an attempted load that fails gives a url_changed(about:blank)
# so maybe we can detect it that way.
urlbar = self.browser_win.urlbar
if url.toString() == 'about:blank':
self.browser_win.statusBar().showMessage("Couldn't load '%s'" %
urlbar.text())
print("Couldn't load " + urlbar.text())
else:
urlbar.setText(url.toDisplayString())
def link_hover(self, url):
self.browser_win.statusBar().showMessage(url)
self.last_hovered = url
def load_started(self):
# Setting the default encoding in __init__ doesn't do anything;
# it gets reset as soon as we load a page.
# There's no documentation on where it's supposed to be set,
# but setting it here seems to work.
# self.settings().setDefaultTextEncoding("utf-8")
self.browser_win.progress.show()
def load_finished(self, ok):
# OK is useless: if we try to load a bad URL, we won't get a
# loadFinished on that; instead it will switch to about:blank,
# load that successfully and call loadFinished with ok=True.
self.browser_win.progress.hide()
# print("load_finished")
# print("In load_finished, view is", self.webviews[self.active_tab], "and page is", self.webviews[self.active_tab].page())
# print("Profile off the record?", self.profile.isOffTheRecord())
# print("Webpage off the record?", self.webviews[self.active_tab].page().profile().isOffTheRecord())
self.browser_win.set_tab_text(self.title(), self)
def load_progress(self, progress):
self.browser_win.progress.setValue(progress)
class BrowserWindow(QMainWindow):
def __init__(self, *args, **kwargs):
super(BrowserWindow, self).__init__(*args, **kwargs)
self.setWindowTitle("Quickbrowse")
toolbar = QToolBar("Toolbar")
self.addToolBar(toolbar)
btn_act = QAction("Back", self)
# for an icon: QAction(QIcon("bug.png"), "Your button", self)
btn_act.setStatusTip("Go back")
btn_act.triggered.connect(self.go_back)
toolbar.addAction(btn_act)
btn_act = QAction("Forward", self)
btn_act.setStatusTip("Go forward")
btn_act.triggered.connect(self.go_forward)
toolbar.addAction(btn_act)
btn_act = QAction("Reload", self)
btn_act.setStatusTip("Reload")
btn_act.triggered.connect(self.reload)
toolbar.addAction(btn_act)
self.urlbar = ReadlineEdit()
self.urlbar.setPlaceholderText("URL goes here")
self.urlbar.returnPressed.connect(self.urlbar_load)
toolbar.addWidget(self.urlbar)
self.profile = QWebEngineProfile()
# print("Profile initially off the record?",
# self.profile.isOffTheRecord())
self.tabwidget = QTabWidget()
self.webviews = []
self.setCentralWidget(self.tabwidget)
self.tabwidget.tabBar().installEventFilter(self)
self.prev_middle = -1
self.active_tab = 0
self.setStatusBar(QStatusBar(self))
self.progress = QProgressBar()
self.statusBar().addPermanentWidget(self.progress)
# Key bindings
# For keys like function keys, use QtGui.QKeySequence("F12")
QtWidgets.QShortcut("Ctrl+Q", self, activated=self.close)
QtWidgets.QShortcut("Ctrl+L", self, activated=self.select_urlbar)
QtWidgets.QShortcut("Ctrl+T", self, activated=self.new_tab)
QtWidgets.QShortcut("Ctrl+R", self, activated=self.reload)
self.resize(1024, 768)
def eventFilter(self, object, event):
if object == self.tabwidget.tabBar() and \
event.type() in [QEvent.MouseButtonPress,
QEvent.MouseButtonRelease] and \
event.button() == Qt.MidButton:
tabindex = object.tabAt(event.pos())
if event.type() == QEvent.MouseButtonPress:
self.prev_middle = tabindex
else:
if tabindex != -1 and tabindex == self.prev_middle:
self.close_tab(tabindex)
self.prev_middle = -1
return True
return False
def new_tab(self, url=None):
webview = BrowserView(self)
self.webviews.append(webview)
# We need a QWebEnginePage in order to get linkHovered events,
# and to set an anonymous profile.
# print("New tab, profile still off the record?",
# self.profile.isOffTheRecord())
webpage = QWebEnginePage(self.profile, webview)
# print("New Webpage off the record?",
# webpage.profile().isOffTheRecord())
webview.setPage(webpage)
# print("New view's page off the record?",
# webview.page().profile().isOffTheRecord())
# print("In new tab, view is", webview, "and page is", webpage)
self.tabwidget.addTab(webview, "New tab")
webview.urlChanged.connect(webview.url_changed)
webview.loadStarted.connect(webview.load_started)
webview.loadFinished.connect(webview.load_finished)
webview.loadProgress.connect(webview.load_progress)
webpage.linkHovered.connect(webview.link_hover)
if url:
save_active = self.active_tab
self.active_tab = len(self.webviews)-1
self.load_url(url)
self.active_tab = save_active
def close_tab(self, tabindex):
self.tabwidget.removeTab(tabindex)
def load_url(self, url):
qurl = QUrl(url)
if not qurl.scheme():
if os.path.exists(url):
qurl.setScheme('file')
if not os.path.isabs(url):
# Is it better to use posixpath.join or os.path.join?
# Both work on Linux.
qurl.setPath(os.path.normpath(os.path.join(os.getcwd(),
url)))
else:
qurl.setScheme('http')
self.webviews[self.active_tab].load(qurl)
self.urlbar.setText(url)
def select_urlbar(self):
self.urlbar.selectAll()
self.urlbar.setFocus()
def find_view(self, view):
for i, v in enumerate(self.webviews):
if v == view:
return i
return None
def set_tab_text(self, title, view):
'''Set tab and, perhaps, window title after a page load.
view is the requesting BrowserView, and will be compared
to our webviews[] to figure out which tab to set.
'''
whichtab = None
whichtab = self.find_view(view)
if whichtab == None:
print("Warning: set_tab_text for unknown view")
return
self.tabwidget.setTabText(whichtab, title)
def update_buttons(self):
# TODO: To enable/disable buttons, check e.g.
# self.webview.page().action(QWebEnginePage.Back).isEnabled())
pass
def signal_handler(self, signal, frame):
with open(URL_FILE % os.getpid()) as url_fp:
for url in url_fp:
self.new_tab(url.strip())
#
# Slots
#
def urlbar_load(self):
url = self.urlbar.text()
self.load_url(url)
def go_back(self):
self.webviews[self.active_tab].back()
def go_forward(self):
self.webviews[self.active_tab].forward()
def reload(self):
self.webviews[self.active_tab].reload()
#
# PyQt is super crashy. Any little error, like an extra argument in a slot,
# causes it to kill Python with a core dump.
# Setting sys.excepthook works around this behavior, and execution continues.
#
def excepthook(excType=None, excValue=None, tracebackobj=None, *,
message=None, version_tag=None, parent=None):
# print("exception! excValue='%s'" % excValue)
# logging.critical(''.join(traceback.format_tb(tracebackobj)))
# logging.critical('{0}: {1}'.format(excType, excValue))
traceback.print_exception(excType, excValue, tracebackobj)
sys.excepthook = excepthook
if __name__ == '__main__':
SIGNAL = signal.SIGUSR1
args = sys.argv[1:]
def get_procname(procargs):
'''Return the program name: either the first commandline argument,
or, if that argument is some variant of "python", the second.
'''
basearg = os.path.basename(procargs[0])
if basearg.startswith('python'):
basearg = os.path.basename(procargs[1])
return basearg
progname = get_procname(sys.argv)
def find_proc_by_name(name):
"""Looks for a process with the given basename, ignoring a possible
"python" prefix in case it's another Python script.
Will ignore the current running process.
Returns the pid, or None.
"""
PROCDIR = '/proc'
for proc in os.listdir(PROCDIR):
if not proc[0].isdigit():
continue
# Race condition: processes can come and go, so we may not be
# able to open something just because it was there when we
# did the listdir.
try:
with open(os.path.join(PROCDIR, proc, 'cmdline')) as procfp:
procargs = procfp.read().split('\0')
basearg = get_procname(procargs)
if basearg == name and int(proc) != os.getpid():
return int(proc)
except Exception as e:
print("Exception", e)
pass
return None
if args and args[0] == "--new-tab":
# Try to use an existing instance of quickbrowse
# instead of creating a new window.
urls = args[1:]
progname = get_procname(sys.argv)
pid = find_proc_by_name(progname)
print("progname is", progname, ", pid is", pid)
if pid:
# Create the file of URLs:
with open(URL_FILE % pid, 'w') as url_fp:
for url in urls:
print(url, file=url_fp)
os.kill(int(pid), SIGNAL)
sys.exit(0)
print("No existing %s process: starting a new one." % progname)
# Return control to the shell before creating the window:
rc = os.fork()
if rc:
sys.exit(0)
app = QApplication(sys.argv)
win = BrowserWindow()
for url in args:
win.new_tab(url)
win.show()
# Handle SIGUSR1 signal so we can be signalled to open other tabs:
signal.signal(SIGNAL, win.signal_handler)
# The Qt main loop blocks the ability to listen for Unix signals.
# The solution to this is apparently to run a timer to block the
# Qt main loop every so often so signals have a chance to get through.
# XXX For a better solution using sockets:
# https://github.com/qutebrowser/qutebrowser/blob/v0.10.x/qutebrowser/misc/crashsignal.py#L304-L314
# http://doc.qt.io/qt-4.8/unix-signals.html
timer = QTimer()
timer.start(500) # You may change this if you wish.
timer.timeout.connect(lambda: None) # Let the interpreter run each 500 ms.
app.exec_()