Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions bin/omarchy-install-service-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
#!/bin/bash

# omarchy:summary=Install Slack Desktop with live Omarchy theme support
# omarchy:requires-sudo=true

set -euo pipefail

omarchy-pkg-add slack-desktop
if omarchy-setup-slack; then
setsid uwsm-app -- gtk-launch slack >/dev/null 2>&1 &
else
echo "Slack theme setup failed; opening packaged Slack." >&2
setsid uwsm-app -- gio launch /usr/share/applications/slack.desktop >/dev/null 2>&1 &
fi
18 changes: 18 additions & 0 deletions bin/omarchy-launch-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
#!/bin/bash

# omarchy:summary=Launch Slack with live Omarchy theme support
# omarchy:args=[slack-arguments...]
# omarchy:hidden=true

# Slack's own restarts come back through here with the pipe flag the
# launcher added; the launcher adds it again with a pipe behind it.
arguments=()
for argument in "$@"; do
[[ $argument == "--remote-debugging-pipe" ]] || arguments+=("$argument")
done

if [[ -f $HOME/.local/state/omarchy/slack/enabled ]]; then
exec /usr/bin/python "$OMARCHY_PATH/default/slack/launcher.py" "${arguments[@]}"
else
exec /usr/bin/slack "${arguments[@]}"
fi
4 changes: 4 additions & 0 deletions bin/omarchy-remove-launcher-entry
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ if [[ $exec_line =~ (^|[[:space:]])(\$TERMINAL|xdg-terminal-exec)[[:space:]].*-e
exit 0
fi

if [[ $desktop_file_name == "slack.desktop" && $exec_line =~ ^omarchy-launch-slack($|[[:space:]]) ]]; then
exec omarchy-launch-floating-terminal-with-presentation omarchy-remove-service-slack
fi

if is_user_desktop_file; then
display_name="${entry_name:-$desktop_name}"
rm -f "$desktop_file"
Expand Down
15 changes: 15 additions & 0 deletions bin/omarchy-remove-service-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/bin/bash

# omarchy:summary=Uninstall Slack Desktop and clean up its theme integration
# omarchy:hidden=true
# omarchy:requires-sudo=true

set -euo pipefail

omarchy-pkg-drop slack-desktop
override="$HOME/.local/share/applications/slack.desktop"
if [[ -f $override ]] && grep -qE '^Exec=omarchy-launch-slack( |$)' "$override"; then
rm "$override"
update-desktop-database "${override%/*}"
fi
rm -rf "$HOME/.local/state/omarchy/slack"
43 changes: 43 additions & 0 deletions bin/omarchy-setup-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
#!/bin/bash

# omarchy:summary=Make Slack follow Omarchy themes live

set -euo pipefail

if (( EUID == 0 )); then
echo "Run this command as your desktop user, without sudo." >&2
exit 1
fi

[[ -f /usr/bin/slack ]] || { echo "Install Slack Desktop first." >&2; exit 1; }

if [[ ! -f $HOME/.local/state/omarchy/current/theme/slack.json ]]; then
omarchy-theme-refresh
fi

desktop="/usr/share/applications/slack.desktop"
override="$HOME/.local/share/applications/slack.desktop"
state="$HOME/.local/state/omarchy/slack"
if ! grep -qE '^Exec=(/usr/bin/)?slack( |$)' "$desktop"; then
echo "Slack's desktop launcher has changed; refusing to replace it." >&2
exit 1
fi

mkdir -p "${override%/*}" "$state"
if [[ -f $override ]] && ! grep -qE '^Exec=omarchy-launch-slack( |$)' "$override"; then
if [[ -e $override.before-omarchy ]]; then
echo "An earlier launcher backup already exists: $override.before-omarchy" >&2
exit 1
fi
cp -a "$override" "$override.before-omarchy"
fi
pending=$(mktemp "$override.XXXXXX")
trap 'rm -f "$pending"' EXIT
sed -E 's#^Exec=(/usr/bin/)?slack( |$)#Exec=omarchy-launch-slack\2#' "$desktop" >"$pending"
mv "$pending" "$override"
touch "$state/enabled"
update-desktop-database "${override%/*}"
omarchy-theme-set-slack

echo "Slack theme sync enabled. Fully quit Slack and reopen it from the launcher once."
echo "Future Omarchy theme changes will recolor open Slack windows automatically."
1 change: 1 addition & 0 deletions bin/omarchy-theme-set
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,7 @@ other_theme_commands=(
omarchy-theme-set-claude
omarchy-theme-set-hermes
omarchy-theme-set-t3code
omarchy-theme-set-slack
omarchy-theme-set-browser
omarchy-theme-set-vscode
omarchy-theme-set-obsidian
Expand Down
21 changes: 21 additions & 0 deletions bin/omarchy-theme-set-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
#!/bin/bash

# omarchy:summary=Sync the generated Omarchy theme to running Slack windows
# omarchy:hidden=true

set -euo pipefail

state="$HOME/.local/state/omarchy/slack"
theme="$HOME/.local/state/omarchy/current/theme/slack.json"
[[ -f $state/enabled && -f $theme ]] || exit 0

pending=$(mktemp "$state/theme.XXXXXX")
trap 'rm -f "$pending"' EXIT
if jq -e 'select(.mode == "light" or .mode == "dark") |
select([.background, .accent, .green, .red] | all(type == "string" and test("^#[0-9a-fA-F]{6}([0-9a-fA-F]{2})?$"))) |
{mode, background, accent, green, red} |
with_entries(if .key == "mode" then . else .value |= .[0:7] end)' "$theme" >"$pending"; then
mv "$pending" "$state/theme.json"
else
echo "Skipping invalid Slack theme." >&2
fi
2 changes: 1 addition & 1 deletion default/omarchy/omarchy-menu.jsonc
Original file line number Diff line number Diff line change
Expand Up @@ -299,7 +299,7 @@
"install.service.dropbox": {"icon":"","label":"Dropbox","when":"[[ $(getconf PAGESIZE) == 4096 ]]","disabled":"omarchy-pkg-present dropbox","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-dropbox"},
"install.service.spotify": {"icon":"󰓇","label":"Spotify","disabled":"omarchy-pkg-present spotify || [[ -f $HOME/.local/share/applications/Spotify.desktop ]]","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-spotify"},
"install.service.signal": {"icon":"󰭹","label":"Signal","disabled":"omarchy-pkg-present signal-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-signal"},
"install.service.slack": {"icon":"󰒱","label":"Slack","disabled":"omarchy-pkg-present slack-desktop","action":"omarchy-install-and-launch Slack slack-desktop slack"},
"install.service.slack": {"icon":"󰒱","label":"Slack","disabled":"omarchy-pkg-present slack-desktop","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-slack"},
"install.service.tailscale": {"icon":"","iconFont":"omarchy","label":"Tailscale","disabled":"omarchy-pkg-present tailscale","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-tailscale"},
"install.service.nordvpn": {"icon":"󱇱","label":"NordVPN","disabled":"omarchy-pkg-present nordvpn-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-nordvpn"},
"install.service.once": {"icon":"󰏖","label":"ONCE","disabled":"omarchy-pkg-present once-bin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-install-service-once"},
Expand Down
143 changes: 143 additions & 0 deletions default/slack/launcher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Apply native theme preferences to packaged Slack over inherited pipes."""

import json
import os
from pathlib import Path
import signal
import sys

from gi.repository import Gio, GLib


class Slack:
def __init__(self, directory):
self.directory = Path(directory)
self.theme_file = self.directory / 'theme.json'
self.theme = ''
self.script = Path(__file__).with_name('theme.js').read_text().strip()
self.sessions = set()
self.callbacks = {}
self.next_id = 0
self.buffer = b''
self.outbox = []
self.loop = GLib.MainLoop()

def start(self, arguments, binary='/usr/bin/slack', name=None):
# Chromium reads descriptor 3 and writes descriptor 4. The inherited
# pipes belong to this launch; no debugging socket or port is opened.
outgoing, writer = os.pipe()
reader, incoming = os.pipe()
launcher = Gio.SubprocessLauncher.new(Gio.SubprocessFlags.NONE)
launcher.take_fd(outgoing, 3)
launcher.take_fd(incoming, 4)
# Slack's restart actions relaunch the command line it started with,
# and Electron quits when the pipe flag arrives without the pipe.
# Starting Slack under the launcher's name brings those restarts back
# through it, so the new Slack gets a pipe of its own.
self.child = launcher.spawnv(['/bin/bash', '-c', 'exec -a "$0" "$@"', name or binary,
binary, '--remote-debugging-pipe', *arguments])
self.input = Gio.UnixInputStream.new(reader, True)
self.output = Gio.UnixOutputStream.new(writer, True)
self.input.read_bytes_async(65536, 0, None, self.received)
self.child.wait_async(None, self.exited)
self.monitor = Gio.File.new_for_path(str(self.directory)).monitor_directory(Gio.FileMonitorFlags.WATCH_MOVES, None)
self.monitor.connect('changed', self.changed)
Comment thread
acrogenesis marked this conversation as resolved.
Resolved
self.theme = self.theme_file.read_text() if self.theme_file.exists() else ''
self.send('Target.setAutoAttach', {'autoAttach': True, 'waitForDebuggerOnStart': False, 'flatten': True,
'filter': [{'type': 'page'}, {'exclude': True}]})
for number in (signal.SIGTERM, signal.SIGINT):
GLib.unix_signal_add(0, number, self.stop, number)

def send(self, method, params=None, session=None, callback=None):
self.next_id += 1
message = {'id': self.next_id, 'method': method, 'params': params or {}}
if session:
message['sessionId'] = session
if callback:
self.callbacks[self.next_id] = callback
self.outbox.append(json.dumps(message).encode() + b'\0')
if len(self.outbox) == 1:
self.write()

def write(self):
self.output.write_all_async(self.outbox[0], 0, None, self.written)

def written(self, stream, result):
try:
stream.write_all_finish(result)
self.outbox.pop(0)
if self.outbox:
self.write()
except GLib.Error as error:
print('Slack theme pipe:', error.message, file=sys.stderr)

def received(self, stream, result):
try:
data = stream.read_bytes_finish(result).get_data()
if not data:
return
self.buffer += data
while b'\0' in self.buffer:
message, self.buffer = self.buffer.split(b'\0', 1)
try:
self.dispatch(json.loads(message))
except (KeyError, ValueError) as error:
# Stop reading and Slack queues every later message in memory.
print('Slack theme pipe:', repr(error), file=sys.stderr)
stream.read_bytes_async(65536, 0, None, self.received)
except GLib.Error as error:
print('Slack theme pipe:', error.message, file=sys.stderr)

def dispatch(self, message):
callback = self.callbacks.pop(message.get('id'), None)
if callback:
callback(message)
params, session = message.get('params', {}), message.get('sessionId')
if message.get('method') == 'Target.attachedToTarget':
session = params['sessionId']
self.sessions.add(session)
# Page events mark each new document of the window. Runtime.enable
# would also stream all of Slack's console output, about 7 MB at
# startup and a message a second after.
self.send('Page.enable', session=session)
self.apply(session)
elif message.get('method') == 'Target.detachedFromTarget':
self.sessions.discard(params['sessionId'])
elif message.get('method') == 'Page.domContentEventFired':
self.apply(session)

def apply(self, session):
if self.theme and session in self.sessions:
# Native preference actions are synchronous. Pipe ordering keeps
# rapid changes in order, without stylesheet or navigation handles.
self.send('Runtime.evaluate', {'expression': self.script + '(' + self.theme + ')'}, session)

def changed(self, monitor, file, other, event):
if any(item and item.get_basename() == 'theme.json' for item in (file, other)):
try:
theme = self.theme_file.read_text()
except OSError:
return
if theme != self.theme:
self.theme = theme
for session in self.sessions:
self.apply(session)

def stop(self, number):
self.child.send_signal(number)
return GLib.SOURCE_REMOVE

def exited(self, child, result):
child.wait_finish(result)
self.monitor.cancel()
self.loop.quit()

def run(self, arguments):
self.start(arguments, name=os.environ['OMARCHY_PATH'] + '/bin/omarchy-launch-slack')
self.loop.run()
return self.child.get_exit_status() if self.child.get_if_exited() else 128 + self.child.get_term_sig()


if __name__ == '__main__':
directory = Path.home() / '.local/state/omarchy/slack'
sys.exit(Slack(directory).run(sys.argv[1:]))
58 changes: 58 additions & 0 deletions default/slack/theme.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
(colors => {
const state = window.omarchySlackTheme ??= {};
state.colors = colors;
state.apply ??= () => {
if (!state.runtime && window.rspackChunkGantryV2) {
window.rspackChunkGantryV2.push([["omarchy-theme"], {}, runtime => { state.runtime = runtime; }]);
}
if (!state.runtime) return;
if (!state.actions) {
// A look walks every export of Slack's ~13,000 modules, about 20 ms, and
// the observer calls this on each DOM change. Look at most once a second,
// and give up after a minute on a Slack build whose actions have moved.
const now = Date.now();
if (state.lookedAt !== undefined && now - state.lookedAt < 1000) {
// Slack can finish loading inside that second and then go quiet, so
// look again once it's up instead of waiting for another DOM change.
state.retry ??= setTimeout(() => { state.retry = undefined; state.apply(); }, 1000 - (now - state.lookedAt));
return;
}
state.lookedAt = now;
state.firstLook ??= now;
const values = Object.values(state.runtime.c).flatMap(module => Object.values(module.exports || {}));
const find = key => values.find(value => typeof value === "function" && (value.meta?.key === key || value.name === key));
const actions = ["getStoreInstanceMap", "tryGetClientStoreInstance", "createActionSetUserPref", "createActionSetClientThemeInternal"].map(find);
if (actions.includes(undefined)) {
if (now - state.firstLook > 60000) state.observer?.disconnect();
return;
}
state.actions = actions;
}
const [storeMap, clientStore, preference, mode] = state.actions;
const stores = storeMap();
const client = clientStore();
if (!stores || !Object.keys(stores).length || !client) return;
const { background, accent, green, red, mode: scheme } = state.colors;
const color = hex => ({ palette: "gray", custom: hex });
const theme = {
primary: color(background), highlight1: color(accent),
highlight2: color(green), important: color(red),
brightness: scheme === "light" ? 1 : 6,
sidebarInverted: false, useCustomHex: true
};
// These reducer actions stay local; the API setter would sync the account.
for (const store of Object.values(stores)) {
store.dispatch(preference({ pref: "ia_theme", value: theme }));
store.dispatch(mode(scheme));
}
client.dispatch(mode(scheme));
clearTimeout(state.retry);
state.retry = undefined;
state.observer?.disconnect();
return true;
};
if (!state.apply()) {
state.observer ??= new MutationObserver(state.apply);
state.observer.observe(document, { childList: true, subtree: true });
}
})
7 changes: 7 additions & 0 deletions default/themed/slack.json.tpl
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"mode": "{{ mode }}",
"background": "{{ background }}",
"accent": "{{ gradient_start accent blue }}",
"green": "{{ green }}",
"red": "{{ red }}"
}
Loading
Loading