|
| 1 | +"""Apply native theme preferences to packaged Slack over inherited pipes.""" |
| 2 | + |
| 3 | +import json |
| 4 | +import os |
| 5 | +from pathlib import Path |
| 6 | +import signal |
| 7 | +import sys |
| 8 | + |
| 9 | +from gi.repository import Gio, GLib |
| 10 | + |
| 11 | + |
| 12 | +class Slack: |
| 13 | + def __init__(self, directory): |
| 14 | + self.directory = Path(directory) |
| 15 | + self.theme_file = self.directory / 'theme.json' |
| 16 | + self.theme = '' |
| 17 | + self.script = Path(__file__).with_name('theme.js').read_text().strip() |
| 18 | + self.sessions = set() |
| 19 | + self.callbacks = {} |
| 20 | + self.next_id = 0 |
| 21 | + self.buffer = b'' |
| 22 | + self.outbox = [] |
| 23 | + self.loop = GLib.MainLoop() |
| 24 | + |
| 25 | + def start(self, arguments, binary='/usr/bin/slack', name=None): |
| 26 | + # Chromium reads descriptor 3 and writes descriptor 4. The inherited |
| 27 | + # pipes belong to this launch; no debugging socket or port is opened. |
| 28 | + outgoing, writer = os.pipe() |
| 29 | + reader, incoming = os.pipe() |
| 30 | + launcher = Gio.SubprocessLauncher.new(Gio.SubprocessFlags.NONE) |
| 31 | + launcher.take_fd(outgoing, 3) |
| 32 | + launcher.take_fd(incoming, 4) |
| 33 | + # Slack's restart actions relaunch the command line it started with, |
| 34 | + # and Electron quits when the pipe flag arrives without the pipe. |
| 35 | + # Starting Slack under the launcher's name brings those restarts back |
| 36 | + # through it, so the new Slack gets a pipe of its own. |
| 37 | + self.child = launcher.spawnv(['/bin/bash', '-c', 'exec -a "$0" "$@"', name or binary, |
| 38 | + binary, '--remote-debugging-pipe', *arguments]) |
| 39 | + self.input = Gio.UnixInputStream.new(reader, True) |
| 40 | + self.output = Gio.UnixOutputStream.new(writer, True) |
| 41 | + self.input.read_bytes_async(65536, 0, None, self.received) |
| 42 | + self.child.wait_async(None, self.exited) |
| 43 | + self.monitor = Gio.File.new_for_path(str(self.directory)).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None) |
| 44 | + self.monitor.connect('changed', self.changed) |
| 45 | + self.theme = self.theme_file.read_text() if self.theme_file.exists() else '' |
| 46 | + self.send('Target.setAutoAttach', {'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True, |
| 47 | + 'filter': [{'type': 'page'}, {'exclude': True}]}) |
| 48 | + for number in (signal.SIGTERM, signal.SIGINT): |
| 49 | + GLib.unix_signal_add(0, number, self.stop, number) |
| 50 | + |
| 51 | + def send(self, method, params=None, session=None, callback=None): |
| 52 | + self.next_id += 1 |
| 53 | + message = {'id': self.next_id, 'method': method, 'params': params or {}} |
| 54 | + if session: |
| 55 | + message['sessionId'] = session |
| 56 | + if callback: |
| 57 | + self.callbacks[self.next_id] = callback |
| 58 | + self.outbox.append(json.dumps(message).encode() + b'\0') |
| 59 | + if len(self.outbox) == 1: |
| 60 | + self.write() |
| 61 | + |
| 62 | + def write(self): |
| 63 | + self.output.write_all_async(self.outbox[0], 0, None, self.written) |
| 64 | + |
| 65 | + def written(self, stream, result): |
| 66 | + try: |
| 67 | + stream.write_all_finish(result) |
| 68 | + self.outbox.pop(0) |
| 69 | + if self.outbox: |
| 70 | + self.write() |
| 71 | + except GLib.Error as error: |
| 72 | + print('Slack theme pipe:', error.message, file=sys.stderr) |
| 73 | + |
| 74 | + def received(self, stream, result): |
| 75 | + try: |
| 76 | + data = stream.read_bytes_finish(result).get_data() |
| 77 | + if not data: |
| 78 | + return |
| 79 | + self.buffer += data |
| 80 | + while b'\0' in self.buffer: |
| 81 | + message, self.buffer = self.buffer.split(b'\0', 1) |
| 82 | + try: |
| 83 | + self.dispatch(json.loads(message)) |
| 84 | + except (KeyError, ValueError) as error: |
| 85 | + # Stop reading and Slack queues every later message in memory. |
| 86 | + print('Slack theme pipe:', repr(error), file=sys.stderr) |
| 87 | + stream.read_bytes_async(65536, 0, None, self.received) |
| 88 | + except GLib.Error as error: |
| 89 | + print('Slack theme pipe:', error.message, file=sys.stderr) |
| 90 | + |
| 91 | + def dispatch(self, message): |
| 92 | + callback = self.callbacks.pop(message.get('id'), None) |
| 93 | + if callback: |
| 94 | + callback(message) |
| 95 | + params, session = message.get('params', {}), message.get('sessionId') |
| 96 | + if message.get('method') == 'Target.attachedToTarget': |
| 97 | + session = params['sessionId'] |
| 98 | + self.sessions.add(session) |
| 99 | + # Page events mark each new document of the window. Runtime.enable |
| 100 | + # would also stream all of Slack's console output, about 7 MB at |
| 101 | + # startup and a message a second after. |
| 102 | + self.send('Page.enable', session=session) |
| 103 | + self.apply(session) |
| 104 | + elif message.get('method') == 'Target.detachedFromTarget': |
| 105 | + self.sessions.discard(params['sessionId']) |
| 106 | + elif message.get('method') == 'Page.domContentEventFired': |
| 107 | + self.apply(session) |
| 108 | + |
| 109 | + def apply(self, session): |
| 110 | + if self.theme and session in self.sessions: |
| 111 | + # Native preference actions are synchronous. Pipe ordering keeps |
| 112 | + # rapid changes in order, without stylesheet or navigation handles. |
| 113 | + self.send('Runtime.evaluate', {'expression': self.script + '(' + self.theme + ')'}, session) |
| 114 | + |
| 115 | + def changed(self, monitor, file, other, event): |
| 116 | + if any(item and item.get_basename() == 'theme.json' for item in (file, other)): |
| 117 | + try: |
| 118 | + theme = self.theme_file.read_text() |
| 119 | + except OSError: |
| 120 | + return |
| 121 | + if theme != self.theme: |
| 122 | + self.theme = theme |
| 123 | + for session in self.sessions: |
| 124 | + self.apply(session) |
| 125 | + |
| 126 | + def stop(self, number): |
| 127 | + self.child.send_signal(number) |
| 128 | + return GLib.SOURCE_REMOVE |
| 129 | + |
| 130 | + def exited(self, child, result): |
| 131 | + child.wait_finish(result) |
| 132 | + self.monitor.cancel() |
| 133 | + self.loop.quit() |
| 134 | + |
| 135 | + def run(self, arguments): |
| 136 | + self.start(arguments, name=os.environ['OMARCHY_PATH'] + '/bin/omarchy-launch-slack') |
| 137 | + self.loop.run() |
| 138 | + return self.child.get_exit_status() if self.child.get_if_exited() else 128 + self.child.get_term_sig() |
| 139 | + |
| 140 | + |
| 141 | +if __name__ == '__main__': |
| 142 | + directory = Path.home() / '.local/state/omarchy/slack' |
| 143 | + sys.exit(Slack(directory).run(sys.argv[1:])) |
0 commit comments