Created
December 13, 2020 20:51
-
-
Save benoit-pierre/330482b5c10f9514914046cfac060789 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
from tempfile import NamedTemporaryFile | |
import os | |
import shlex | |
import sys | |
import subprocess | |
from dogtail import tree | |
from dogtail.predicate import config as dogtail_config | |
from dogtail.predicate import GenericPredicate | |
import pyinotify | |
from dogtail_utils import * | |
dogtail_config.logDebugToFile = False | |
dogtail_config.logDebugToStdOut = True | |
args = sys.argv[1:] | |
if args: | |
filename = args[0] | |
else: | |
filename = None | |
class FireMonkeyEditor: | |
def __init__(self, filename): | |
tab = next(find_firefox_tabs('FireMonkey Options')) | |
self.save_button = find_descendant_breadth_first(tab, lambda x: x.getRole() == pyatspi.ROLE_PUSH_BUTTON and x.name == '💾 Save') | |
self.text_entry = find_descendant_breadth_first(tab, lambda x: x.getRole() == pyatspi.ROLE_ENTRY) | |
self.filename = filename | |
def update(self): | |
with open(self.filename, 'r') as fp: | |
text = fp.read() | |
if text != self.text_entry.text: | |
print('🖪', end=' ') | |
self.text_entry.text = text | |
self.save_button.actions['press'].do() | |
cleanups = [] | |
try: | |
if filename is None: | |
tmpf = NamedTemporaryFile(mode='w+', delete=False) | |
cleanups.append(lambda: os.unlink(tmpf.name)) | |
tmpf.write(text_entry.text) | |
tmpf.close() | |
filename = tmpf.name | |
external_editor = subprocess.Popen(shlex.split(os.environ['EDITOR']) + [filename]) | |
cleanups.append(external_editor.wait) | |
firemonkey_editor = FireMonkeyEditor(filename) | |
filename = os.path.realpath(filename) | |
class EventHandler(pyinotify.ProcessEvent): | |
def process_IN_CLOSE_WRITE(self, event): | |
if event.pathname == filename: | |
firemonkey_editor.update() | |
handler = EventHandler() | |
wm = pyinotify.WatchManager() | |
notifier = pyinotify.Notifier(wm, handler, timeout=250) | |
wdd = wm.add_watch(os.path.dirname(filename), pyinotify.IN_CLOSE_WRITE, rec=False) | |
print('✓ ready') | |
notifier.loop(callback=lambda n: external_editor.poll() is not None) | |
finally: | |
for fn in reversed(cleanups): | |
fn() | |
sys.exit(external_editor.returncode) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment