me.fier.gawk/user/addon/startupNewWindow/_main.py

119 lines
2.6 KiB
Python

import sys
import os
import socket
import fcntl
import time
config = mfp.require("config")
if not os.path.isdir(config.paths[0]):
try:
os.makedirs(config.paths[0])
except Exception:
pass
lockFile = mfp.p(config.paths[0],"session.lock")
socketFile = mfp.p(config.paths[0],"session.socket")
tries = 1
while tries <= 10:
print("Opening new window, try " +str(tries)+ " ...")
host = True
try:
lockFileHandle = open(lockFile,"w")
fcntl.flock(lockFileHandle,fcntl.LOCK_EX | fcntl.LOCK_NB)
except Exception as e:
host = False
if host:
try:
os.remove(socketFile)
except: pass
s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
s.bind(socketFile)
s.listen(65535)
break
else:
try:
s = socket.socket(socket.AF_UNIX,socket.SOCK_STREAM)
s.connect(socketFile)
if len(sys.argv) < 2:
uri = "about:blank"
else:
uri = sys.argv[1]
s.send((uri + "\n").encode("utf-8"))
print("Successfully merged into pre-existing process, exiting.")
sys.exit(0)
except Exception as e:
print(e)
tries += 1
time.sleep(1)
if tries >= 11:
print("Could not acquire new window from pre-existing process.")
sys.exit(1)
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib
import threading
import queue
browser = mfp.require("browser")
browserWindow = browser.module.require(mfp.p("window","browser.py"))
def makeWindow(uri):
ts = round(time.time())
window = browserWindow.create(uri)
browser.windows.append(window)
window.obj.present_with_time(ts)
class uriThread(threading.Thread):
def __init__(self,*args,**kwargs):
super().__init__(*args,**kwargs)
def run(self):
global s
global q
while True:
c,addr = s.accept()
data = c.recv(1)
if data == b"": # Empty URI, could be a command
try:
cmd = q.get(False)
except queue.Empty:
data = b""
else:
if cmd == "exit": return
continue
else:
while True:
addData = c.recv(1)
if addData == b"": break
data += addData
uri = data.decode("utf-8",errors="ignore")
GLib.idle_add(makeWindow,uri)
onCloseOld = browserWindow.onClose
def onClose(*args,**kwargs):
global q, socketFile
rtn = onCloseOld(*args,**kwargs)
if len(browser.windows) == 0:
q.put("exit")
try:
with socket.socket(socket.AF_UNIX,socket.SOCK_STREAM) as s:
s.connect(socketFile)
s.close()
except Exception:
pass
return rtn
browserWindow.onClose = onClose
q = queue.Queue()
thread = uriThread()
def onWebviewCreated(webView):
del eventHandler["webview:created"]
thread.start()
eventHandler = mfp.Bunch()
eventHandler["webview:created"] = onWebviewCreated