Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
10 changes: 10 additions & 0 deletions bin/omarchy-install-service-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/bin/bash

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

set -euo pipefail

omarchy-pkg-add slack-desktop
omarchy-setup-slack
setsid uwsm-app -- gtk-launch slack >/dev/null 2>&1 &
7 changes: 7 additions & 0 deletions bin/omarchy-launch-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
#!/bin/bash

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

exec python "$OMARCHY_PATH/default/slack/integration.py" launch "$@"
19 changes: 19 additions & 0 deletions bin/omarchy-setup-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/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/lib/slack/resources/app.asar ]] || { echo "Install Slack Desktop first." >&2; exit 1; }

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

python "$OMARCHY_PATH/default/slack/integration.py" setup
omarchy-theme-set-slack
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
11 changes: 11 additions & 0 deletions bin/omarchy-theme-set-slack
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
#!/bin/bash

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

set -euo pipefail

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

python "$OMARCHY_PATH/default/slack/integration.py" theme
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
21 changes: 21 additions & 0 deletions default/slack/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2026 GruperTal

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
173 changes: 173 additions & 0 deletions default/slack/integration.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,173 @@
"""Opt-in Slack theme loader. All changes stay in the user's home directory."""

import fcntl
import hashlib
import json
import mmap
import os
from pathlib import Path
import re
import shutil
import struct
import subprocess
import sys
import tempfile

import palette


SLACK = Path("/usr/lib/slack")
SOURCE = Path(os.environ["OMARCHY_PATH"]) / "default/slack"
STATE = Path.home() / ".local/state/omarchy/slack"
CACHE = Path.home() / ".cache/omarchy/slack"


def publish(path, content):
path.parent.mkdir(parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(dir=path.parent)
try:
with os.fdopen(fd, "wb") as out:
out.write(content)
os.replace(tmp, path)
finally:
Path(tmp).unlink(missing_ok=True)


def patch_archive(source, target, loader):
"""Append to the entry point without moving any of the other ASAR entries."""
raw = source.read_bytes()
header_size = struct.unpack_from("<I", raw, 4)[0]
json_size = struct.unpack_from("<I", raw, 12)[0]
header = json.loads(raw[16:16 + json_size])
data = raw[8 + header_size:]

def entry(path):
node = header
for part in Path(path).parts:
if part != ".":
node = node["files"][part]
return node

package = entry("package.json")
offset = int(package["offset"])
main = json.loads(data[offset:offset + package["size"]])["main"]
boot = entry(main)
offset = int(boot["offset"])
script = data[offset:offset + boot["size"]] + b"\n;" + loader + b"\n"
boot.update(offset=str(len(data)), size=len(script))
if "integrity" in boot:
block_size = boot["integrity"]["blockSize"]
boot["integrity"].update(
hash=hashlib.sha256(script).hexdigest(),
blocks=[hashlib.sha256(script[i:i + block_size]).hexdigest()
for i in range(0, len(script), block_size)],
)
encoded = json.dumps(header, separators=(",", ":")).encode()
padding = -len(encoded) % 4
pickle = struct.pack("<II", 4 + len(encoded) + padding, len(encoded)) + encoded + b"\0" * padding
target.write_bytes(struct.pack("<II", 4, len(pickle)) + pickle + data + script)


def runtime():
archive = SLACK / "resources/app.asar"
binary = SLACK / "slack"
loader = (SOURCE / "loader.cjs").read_bytes()
# A new Slack package or loader gets its own runtime. A running instance
# keeps its old archive available for modules it has not loaded yet.
identity = [(str(p), p.stat().st_ino, p.stat().st_size, p.stat().st_mtime_ns)
for p in (binary, archive)]
key = hashlib.sha256(repr(identity).encode() + loader).hexdigest()[:20]
CACHE.mkdir(parents=True, exist_ok=True)
with (CACHE / "build.lock").open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
target = CACHE / key
if not target.exists():
# Never disable an Electron integrity policy. If a future package
# enables it, the launcher falls back to the unmodified Slack.
with binary.open("rb") as executable, mmap.mmap(executable.fileno(), 0, access=mmap.ACCESS_READ) as mapped:
# v1 wire: 32-byte sentinel, version, count, then fuse states.
marker = mapped.find(b"dL7pKGdnNz796PbbjQWNKmHXBZaB9tsX")
known_wire = marker >= 0 and marker + 39 <= len(mapped) and mapped[marker + 32] == 1 and mapped[marker + 33] >= 5
if not known_wire or mapped[marker + 38] != ord("0"):
raise RuntimeError("This Slack build does not allow a private themed archive.")
staging = Path(tempfile.mkdtemp(dir=CACHE))
try:
for item in SLACK.iterdir():
if item.name == "slack":
subprocess.run(["cp", "--reflink=auto", str(item), str(staging / item.name)], check=True)
elif item.name == "resources":
resources = staging / item.name
resources.mkdir()
for asset in item.iterdir():
if asset.name == "app.asar":
patch_archive(asset, resources / asset.name, loader)
else:
(resources / asset.name).symlink_to(asset)
else:
(staging / item.name).symlink_to(item)
staging.rename(target)
finally:
if staging.exists():
shutil.rmtree(staging)
return target / "slack"


def theme():
# The normal template renderer already resolved colours and legacy aliases
# while staging this theme. Read one snapshot, never re-resolve a live theme.
source = Path.home() / ".local/state/omarchy/current/theme/slack.json"
try:
css = palette.build(json.loads(source.read_text()))
except (ValueError, KeyError, TypeError) as error:
print(f"Skipping Slack theme: {error}", file=sys.stderr)
return
publish(STATE / "slack.css", css.encode())


def setup():
desktop = Path("/usr/share/applications/slack.desktop")
if not (SLACK / "resources/app.asar").is_file() or not desktop.is_file():
raise RuntimeError("Install Slack Desktop before running omarchy setup slack.")
runtime()
Comment thread
acrogenesis marked this conversation as resolved.
Resolved

# Keep the package's flags, icon and URL handler. Resolve the current
# Omarchy launcher on PATH rather than retaining a copy of its code.
lines = desktop.read_text().splitlines()
for i, line in enumerate(lines):
if line.startswith("Exec="):
match = re.match(r"Exec=(?:/usr/bin/)?slack(?=\s|$)", line)
if not match:
raise RuntimeError("Slack's desktop launcher has changed; refusing to replace it.")
lines[i] = "Exec=omarchy-launch-slack" + line[match.end():]
override = Path.home() / ".local/share/applications/slack.desktop"
if override.exists() and "Exec=omarchy-launch-slack" not in override.read_text():
backup = override.with_suffix(".desktop.before-omarchy")
if backup.exists():
raise RuntimeError(f"An earlier launcher backup already exists: {backup}")
shutil.copy2(override, backup)
publish(override, ("\n".join(lines) + "\n").encode())
Comment thread
acrogenesis marked this conversation as resolved.
Resolved
publish(STATE / "enabled", b"")
subprocess.run(["update-desktop-database", str(override.parent)], check=True)
print("Slack theme sync enabled. Fully quit Slack and reopen it from the launcher once.")
print("Future Omarchy theme changes will recolor open Slack windows automatically.")


if __name__ == "__main__":
try:
action = sys.argv[1]
if action == "setup":
setup()
elif action == "theme":
theme()
elif action == "launch":
try:
binary = runtime()
except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as error:
print(f"Slack theme sync: {error} Starting packaged Slack.", file=sys.stderr)
binary = SLACK / "slack"
os.execv(binary, [str(binary), *sys.argv[2:]])
else:
raise RuntimeError(f"Unknown Slack integration action: {action}")
except (OSError, ValueError, KeyError, RuntimeError, subprocess.CalledProcessError) as error:
print(f"Slack theme sync: {error}", file=sys.stderr)
sys.exit(1)
54 changes: 54 additions & 0 deletions default/slack/loader.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Runs only in Slack's main process; renderers keep their existing sandbox.
(() => {
const { app, webContents } = require("electron");
const fs = require("node:fs");
const path = require("node:path");
const directory = path.join(require("node:os").homedir(), ".local/state/omarchy/slack");
const stylesheet = path.join(directory, "slack.css");
const documents = new WeakMap();

// Serialize updates per window so a slow insertion cannot restore an older
// palette after a rapid sequence of theme changes.
function apply(contents) {
let state = documents.get(contents);
if (!state) {
state = { pending: Promise.resolve(), key: null, generation: 0 };
documents.set(contents, state);
}
const generation = state.generation;
state.pending = state.pending.then(async () => {
if (contents.isDestroyed() || generation !== state.generation) return;
const css = await fs.promises.readFile(stylesheet, "utf8");
const key = await contents.insertCSS(css, { cssOrigin: "user" });
if (contents.isDestroyed() || generation !== state.generation) return;
const old = state.key;
state.key = key;
if (old) await contents.removeInsertedCSS(old);
}).catch(error => console.warn("Omarchy Slack theme:", error.message));
}

app.on("web-contents-created", (_, contents) => {
contents.on("dom-ready", () => {
const state = documents.get(contents);
if (state) {
state.generation++;
state.key = null;
}
apply(contents);
});
});

// Watch the parent: theme writes atomically replace the stylesheet inode.
// fs.watch uses filesystem events and starts no idle timer or helper process.
try {
const watcher = fs.watch(directory, (_, filename) => {
if (filename === null || String(filename) === "slack.css") {
webContents.getAllWebContents().forEach(apply);
}
});
watcher.on("error", error => console.warn("Omarchy Slack theme:", error.message));
app.once("will-quit", () => watcher.close());
} catch (error) {
console.warn("Omarchy Slack theme:", error.message);
}
})();
Loading
Loading