#!/usr/bin/env python3
"""1:1 Windows XP CoolSwitch Alt+Tab Task Switcher daemon (GTK3 + GtkLayerShell)."""

import configparser
import fcntl
import json
import os
import signal
import socket
import subprocess
import sys
import threading
import time
from pathlib import Path

UID = os.getuid()
RUNTIME_DIR = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{UID}"
SOCK_PATH = os.path.join(RUNTIME_DIR, "xp-alttab.sock")
LOCK_PATH = os.path.join(RUNTIME_DIR, "xp-alttab.lock")
THEME_ENV_PATH = Path("/home/carsten/.config/hypr/xp-theme.env")

THEME_PALETTES = {
    "Windows XP style (Blue)": {
        "bg": "#ECE9D8", "sunken_bg": "#F3F1E6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#316AC5", "sel_bg": "#DCE8FA", "hover_bg": "#E4E1D0",
        "outer_border": "#003C74", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Windows XP style (Olive Green)": {
        "bg": "#ECE9D8", "sunken_bg": "#F3F1E6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#93A070", "sel_bg": "#E8EED9", "hover_bg": "#E4E1D0",
        "outer_border": "#375223", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Windows XP style (Silver)": {
        "bg": "#E0DFE3", "sunken_bg": "#ECEBF0", "fg": "#000000", "muted": "#555555",
        "sel_border": "#7A7E96", "sel_bg": "#D4D6E4", "hover_bg": "#D5D4DA",
        "outer_border": "#5A5B66", "hi": "#FFFFFF", "shadow": "#9D9DA1", "classic": False,
    },
    "Media Center style (Royale)": {
        "bg": "#EBE9ED", "sunken_bg": "#F4F2F6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#335EA8", "sel_bg": "#D8E6FA", "hover_bg": "#E0DEE4",
        "outer_border": "#1B4485", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Media Center style (Royale Noir)": {
        "bg": "#EBE9ED", "sunken_bg": "#F4F2F6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#587394", "sel_bg": "#DCE3EC", "hover_bg": "#E0DEE4",
        "outer_border": "#1D2433", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Zune style": {
        "bg": "#E2E2E2", "sunken_bg": "#ECECEC", "fg": "#000000", "muted": "#555555",
        "sel_border": "#E36B14", "sel_bg": "#F8E5D6", "hover_bg": "#D6D6D6",
        "outer_border": "#222222", "hi": "#FFFFFF", "shadow": "#A6A6A6", "classic": False,
    },
    "Embedded style": {
        "bg": "#EBE9ED", "sunken_bg": "#F4F2F6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#3E9DE8", "sel_bg": "#D8ECFC", "hover_bg": "#E0DEE4",
        "outer_border": "#1E4B8A", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Professional": {
        "bg": "#ECE9D8", "sunken_bg": "#F3F1E6", "fg": "#000000", "muted": "#555555",
        "sel_border": "#5296F7", "sel_bg": "#DCEBFC", "hover_bg": "#E4E1D0",
        "outer_border": "#2C60B2", "hi": "#FFFFFF", "shadow": "#ACA899", "classic": False,
    },
    "Windows Classic style": {
        "bg": "#D4D0C8", "sunken_bg": "#D4D0C8", "fg": "#000000", "muted": "#404040",
        "sel_border": "#0A246A", "sel_bg": "#C8D0E4", "hover_bg": "#CCC8C0",
        "outer_border": "#404040", "hi": "#FFFFFF", "shadow": "#808080", "classic": True,
    },
}

CLASS_ICON_HINTS = {
    "com.mitchellh.ghostty": ["utilities-terminal", "terminal", "com.mitchellh.ghostty"],
    "ghostty": ["utilities-terminal", "terminal"],
    "thunar": ["system-file-manager", "org.xfce.thunar", "folder"],
    "firefox": ["firefox", "web-browser", "internet-web-browser"],
    "firefox_firefox": ["firefox", "web-browser", "internet-web-browser"],
    "swappy": ["accessories-screenshot", "applets-screenshooter", "image-x-generic"],
    "mousepad": ["accessories-text-editor", "org.xfce.mousepad", "text-editor"],
    "ristretto": ["image-viewer", "org.xfce.ristretto", "eog"],
    "engrampa": ["archive-manager", "file-roller", "package-x-generic"],
    "org.pulseaudio.pavucontrol": ["multimedia-volume-control", "audio-volume-high"],
    "blueman-manager": ["bluetooth", "blueman"],
    "nm-connection-editor": ["preferences-system-network", "network-wired"],
    "discord": ["discord", "internet-chat"],
    "code": ["visual-studio-code", "vscode", "code", "accessories-text-editor"],
    "spotify": ["spotify", "multimedia-audio-player"],
}

COLUMNS = 7
ICON_SIZE = 32


def parse_theme_env():
    theme_name = "Windows XP style (Blue)"
    icon_theme = "luna"
    if THEME_ENV_PATH.exists():
        try:
            for raw in THEME_ENV_PATH.read_text(encoding="utf-8").splitlines():
                line = raw.strip()
                if not line or line.startswith("#") or "=" not in line:
                    continue
                k, v = line.split("=", 1)
                k = k.strip()
                v = v.strip().strip('"').strip("'")
                if k == "XP_THEME_NAME" and v:
                    theme_name = v
                elif k == "XP_ICON_THEME" and v:
                    icon_theme = v
        except OSError:
            pass
    return theme_name, icon_theme


def send_socket_command(cmd, timeout=0.5):
    with socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) as s:
        s.settimeout(timeout)
        s.connect(SOCK_PATH)
        s.sendall((cmd + "\n").encode("utf-8"))
        try:
            return s.recv(128).decode("utf-8", errors="ignore").strip()
        except socket.timeout:
            return ""


def run_client(args):
    cmd = args[0] if args else "next"
    try:
        send_socket_command(cmd)
        return 0
    except OSError:
        if cmd in ("commit", "cancel", "reload", "quit"):
            return 0
    subprocess.Popen(
        [sys.executable, os.path.abspath(__file__), "--daemon"],
        start_new_session=True,
        stdin=subprocess.DEVNULL,
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
        close_fds=True,
    )
    deadline = time.monotonic() + 3.0
    while time.monotonic() < deadline:
        try:
            send_socket_command(cmd)
            return 0
        except OSError:
            time.sleep(0.015)
    return 1


if "--daemon" not in sys.argv[1:]:
    sys.exit(run_client(sys.argv[1:]))


# --- Daemon Mode ---
os.environ.setdefault("DCONF_PROFILE", "/home/carsten/.config/hypr/dconf/profile")

import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("GdkPixbuf", "2.0")
gi.require_version("GtkLayerShell", "0.1")
from gi.repository import Gtk, Gdk, GdkPixbuf, GLib, GtkLayerShell, Pango


class DesktopIconIndex:
    """Fast cached mapping from WM_CLASS / app_id -> icon name from .desktop files."""

    def __init__(self):
        self.by_key = {}
        self._scan()

    def _scan(self):
        dirs = [
            Path.home() / ".local/share/applications",
            Path("/usr/local/share/applications"),
            Path("/usr/share/applications"),
            Path("/var/lib/snapd/desktop/applications"),
            Path("/var/lib/flatpak/exports/share/applications"),
        ]
        for d in dirs:
            if not d.is_dir():
                continue
            for p in d.glob("*.desktop"):
                try:
                    cp = configparser.ConfigParser(interpolation=None, strict=False)
                    cp.read(p, encoding="utf-8")
                    if not cp.has_section("Desktop Entry"):
                        continue
                    ent = cp["Desktop Entry"]
                    icon = ent.get("Icon", "").strip()
                    if not icon:
                        continue
                    stem = p.stem.lower()
                    self.by_key.setdefault(stem, icon)
                    if "_" in stem:
                        self.by_key.setdefault(stem.split("_", 1)[0], icon)
                    wm = ent.get("StartupWMClass", "").strip().lower()
                    if wm:
                        self.by_key[wm] = icon
                    ex = ent.get("Exec", "").strip()
                    if ex:
                        exe = os.path.basename(ex.split()[0]).lower()
                        self.by_key.setdefault(exe, icon)
                except Exception:
                    continue

    def lookup_icon_name(self, cls, init_cls=""):
        for raw in (cls, init_cls):
            c = (raw or "").strip().lower()
            if not c:
                continue
            if c in self.by_key:
                return self.by_key[c]
            if "." in c:
                tail = c.rsplit(".", 1)[-1]
                if tail in self.by_key:
                    return self.by_key[tail]
            if "_" in c:
                head = c.split("_", 1)[0]
                if head in self.by_key:
                    return self.by_key[head]
        return None


class XPAltTabDaemon:
    def __init__(self):
        self.desktop_icons = DesktopIconIndex()
        self.pixbuf_cache = {}
        self.clients = []
        self.selected_idx = 0
        self.visible = False
        self.tile_widgets = []
        self.css_provider = Gtk.CssProvider()

        self.icon_theme = Gtk.IconTheme.get_default()
        self.luna_theme = Gtk.IconTheme.new()
        self.luna_theme.set_custom_theme("luna")

        self.win = Gtk.Window(type=Gtk.WindowType.TOPLEVEL)
        self.win.set_name("xp-alttab-window")
        self.win.set_decorated(False)
        self.win.set_resizable(False)
        self.win.set_app_paintable(True)
        visual = self.win.get_screen().get_rgba_visual()
        if visual is not None:
            self.win.set_visual(visual)

        GtkLayerShell.init_for_window(self.win)
        GtkLayerShell.set_layer(self.win, GtkLayerShell.Layer.OVERLAY)
        GtkLayerShell.set_namespace(self.win, "xp-alttab")
        GtkLayerShell.set_keyboard_mode(self.win, GtkLayerShell.KeyboardMode.NONE)
        GtkLayerShell.set_exclusive_zone(self.win, -1)

        # Outer frame -> inner bevel -> vertical box (grid + sunken title bar)
        self.outer = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
        self.outer.get_style_context().add_class("alttab-outer")

        self.bevel = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=10)
        self.bevel.get_style_context().add_class("alttab-bevel")
        self.outer.pack_start(self.bevel, True, True, 0)

        self.grid_align = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
        self.grid_align.set_halign(Gtk.Align.CENTER)
        self.grid = Gtk.Grid()
        self.grid.set_row_spacing(6)
        self.grid.set_column_spacing(6)
        self.grid.get_style_context().add_class("alttab-grid")
        self.grid_align.pack_start(self.grid, False, False, 0)
        self.bevel.pack_start(self.grid_align, False, False, 0)

        # Sunken XP status bar showing the active window title
        self.status_box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL, spacing=8)
        self.status_box.get_style_context().add_class("alttab-status")

        self.title_label = Gtk.Label(label="")
        self.title_label.set_xalign(0.0)
        self.title_label.set_ellipsize(Pango.EllipsizeMode.END)
        self.title_label.set_width_chars(1)
        self.title_label.set_hexpand(True)
        self.title_label.get_style_context().add_class("alttab-title")
        self.status_box.pack_start(self.title_label, True, True, 0)

        self.ws_label = Gtk.Label(label="")
        self.ws_label.set_xalign(1.0)
        self.ws_label.get_style_context().add_class("alttab-ws-info")
        self.status_box.pack_end(self.ws_label, False, False, 0)

        self.bevel.pack_start(self.status_box, False, False, 0)
        self.win.add(self.outer)

        self.apply_theme()

    def apply_theme(self):
        theme_name, icon_theme = parse_theme_env()
        pal = THEME_PALETTES.get(theme_name, THEME_PALETTES["Windows XP style (Blue)"])
        self.pixbuf_cache.clear()
        self.luna_theme = Gtk.IconTheme.new()
        self.luna_theme.set_custom_theme(icon_theme)

        radius = "0px" if pal["classic"] else "3px"
        css = f"""
        window#xp-alttab-window {{
            background-color: transparent;
        }}
        .alttab-outer {{
            background-color: {pal['bg']};
            border: 1px solid {pal['outer_border']};
            border-radius: {radius};
            box-shadow: 2px 3px 8px rgba(0, 0, 0, 0.38);
            margin: 8px;
        }}
        .alttab-bevel {{
            background-color: {pal['bg']};
            border-top: 1px solid {pal['hi']};
            border-left: 1px solid {pal['hi']};
            border-right: 1px solid {pal['shadow']};
            border-bottom: 1px solid {pal['shadow']};
            border-radius: {radius};
            padding: 14px 16px 12px 16px;
        }}
        .alttab-tile {{
            min-width: 48px;
            min-height: 48px;
            padding: 4px;
            border: 2px solid transparent;
            border-radius: {"0px" if pal["classic"] else "2px"};
            background-color: transparent;
            background-image: none;
            box-shadow: none;
        }}
        .alttab-tile:hover {{
            background-color: {pal['hover_bg']};
            border-color: {pal['shadow']};
        }}
        .alttab-tile.selected,
        .alttab-tile.selected:hover {{
            border: 2px solid {pal['sel_border']};
            background-color: {pal['sel_bg']};
            box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.55);
        }}
        .alttab-ws-badge {{
            font-family: "Tahoma", sans-serif;
            font-size: 7pt;
            font-weight: bold;
            color: {pal['muted']};
            background-color: rgba(255, 255, 255, 0.78);
            border: 1px solid {pal['shadow']};
            border-radius: 2px;
            padding: 0px 3px;
            min-width: 10px;
        }}
        .alttab-tile.selected .alttab-ws-badge {{
            color: #FFFFFF;
            background-color: {pal['sel_border']};
            border-color: {pal['outer_border']};
        }}
        .alttab-status {{
            background-color: {pal['sunken_bg']};
            border-top: 1px solid {pal['shadow']};
            border-left: 1px solid {pal['shadow']};
            border-right: 1px solid {pal['hi']};
            border-bottom: 1px solid {pal['hi']};
            padding: 5px 10px;
            min-width: 340px;
            min-height: 22px;
        }}
        .alttab-title {{
            font-family: "Tahoma", sans-serif;
            font-size: 9.5pt;
            font-weight: bold;
            color: {pal['fg']};
        }}
        .alttab-ws-info {{
            font-family: "Tahoma", sans-serif;
            font-size: 8.5pt;
            color: {pal['muted']};
        }}
        """
        self.css_provider.load_from_data(css.encode("utf-8"))
        Gtk.StyleContext.add_provider_for_screen(
            Gdk.Screen.get_default(),
            self.css_provider,
            Gtk.STYLE_PROVIDER_PRIORITY_USER,
        )

    def _load_pixbuf(self, name):
        if not name:
            return None
        if os.path.isabs(name) and os.path.exists(name):
            try:
                return GdkPixbuf.Pixbuf.new_from_file_at_scale(name, ICON_SIZE, ICON_SIZE, True)
            except Exception:
                return None
        flags = Gtk.IconLookupFlags.FORCE_SIZE | Gtk.IconLookupFlags.FORCE_REGULAR
        for theme in (self.luna_theme, self.icon_theme):
            try:
                info = theme.lookup_icon(name, ICON_SIZE, flags)
                if info:
                    pb = info.load_icon()
                    if pb:
                        if pb.get_width() != ICON_SIZE or pb.get_height() != ICON_SIZE:
                            pb = pb.scale_simple(ICON_SIZE, ICON_SIZE, GdkPixbuf.InterpType.BILINEAR)
                        return pb
            except Exception:
                continue
        return None

    def get_app_pixbuf(self, cls, init_cls=""):
        key = (cls or "").lower()
        if key in self.pixbuf_cache:
            return self.pixbuf_cache[key]

        candidates = []
        if key in CLASS_ICON_HINTS:
            candidates.extend(CLASS_ICON_HINTS[key])
        d_icon = self.desktop_icons.lookup_icon_name(cls, init_cls)
        if d_icon:
            candidates.append(d_icon)
        for raw in (cls, init_cls):
            c = (raw or "").strip().lower()
            if c:
                candidates.append(c)
                if "." in c:
                    candidates.append(c.rsplit(".", 1)[-1])
                if "_" in c:
                    candidates.append(c.split("_", 1)[0])
        candidates.extend(["application-x-executable", "window", "applications-other"])

        pb = None
        for cand in candidates:
            pb = self._load_pixbuf(cand)
            if pb is not None:
                break
        self.pixbuf_cache[key] = pb
        return pb

    def fetch_clients(self):
        try:
            out = subprocess.check_output(["hyprctl", "clients", "-j"], text=True, timeout=1.0)
            data = json.loads(out)
        except Exception:
            return []
        valid = []
        for c in data:
            if not c.get("mapped", True):
                continue
            if not c.get("address"):
                continue
            ws = c.get("workspace", {})
            if ws.get("id", 0) < 0:
                # Special/hidden workspace: keep only if it has a real title
                if not c.get("title"):
                    continue
            valid.append(c)
        # Sort by focusHistoryID ascending (0 = current, 1 = most recently used previous, ...)
        valid.sort(key=lambda c: c.get("focusHistoryID", 9999))
        return valid

    def rebuild_grid(self):
        for child in self.grid.get_children():
            self.grid.remove(child)
        self.tile_widgets = []

        workspaces = {c.get("workspace", {}).get("id", 0) for c in self.clients}
        multi_ws = len(workspaces) > 1

        for idx, client in enumerate(self.clients):
            row = idx // COLUMNS
            col = idx % COLUMNS

            eb = Gtk.EventBox()
            eb.set_visible_window(False)
            eb.connect("button-press-event", self._on_tile_click, idx)
            eb.connect("enter-notify-event", self._on_tile_enter, idx)

            tile = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
            tile.get_style_context().add_class("alttab-tile")

            overlay = Gtk.Overlay()
            pb = self.get_app_pixbuf(client.get("class", ""), client.get("initialClass", ""))
            img = Gtk.Image.new_from_pixbuf(pb) if pb else Gtk.Image.new_from_icon_name("application-x-executable", Gtk.IconSize.DND)
            img.set_halign(Gtk.Align.CENTER)
            img.set_valign(Gtk.Align.CENTER)
            img.set_margin_top(6)
            img.set_margin_bottom(6)
            img.set_margin_start(6)
            img.set_margin_end(6)
            overlay.add(img)

            if multi_ws:
                ws_id = client.get("workspace", {}).get("id", 0)
                if ws_id > 0:
                    badge = Gtk.Label(label=str(ws_id))
                    badge.get_style_context().add_class("alttab-ws-badge")
                    badge.set_halign(Gtk.Align.END)
                    badge.set_valign(Gtk.Align.END)
                    overlay.add_overlay(badge)

            tile.pack_start(overlay, True, True, 0)
            eb.add(tile)
            self.grid.attach(eb, col, row, 1, 1)
            self.tile_widgets.append(tile)

        cols = min(len(self.clients), COLUMNS)
        status_w = max(360, cols * 60 + 16)
        # Lock both min and natural width so GtkWindow(resizable=False) NEVER resizes when titles change
        char_budget = max(34, int((status_w - 95) / 7.5))
        self.title_label.set_width_chars(char_budget)
        self.title_label.set_max_width_chars(char_budget)
        self.status_box.set_size_request(status_w, -1)
        self.grid.show_all()

    def _on_tile_enter(self, _widget, _event, idx):
        if self.visible and 0 <= idx < len(self.clients):
            self.selected_idx = idx
            self.update_selection()
        return False

    def _on_tile_click(self, _widget, _event, idx):
        if 0 <= idx < len(self.clients):
            self.selected_idx = idx
            self.commit(reset_submap=True)
        return True

    def update_selection(self):
        for i, w in enumerate(self.tile_widgets):
            sc = w.get_style_context()
            if i == self.selected_idx:
                sc.add_class("selected")
            else:
                sc.remove_class("selected")

        if 0 <= self.selected_idx < len(self.clients):
            c = self.clients[self.selected_idx]
            title = (c.get("title") or c.get("class") or "Window").strip()
            ws_name = c.get("workspace", {}).get("name") or str(c.get("workspace", {}).get("id", ""))
            self.title_label.set_text(title)
            self.ws_label.set_text(f"Desktop {ws_name}" if ws_name else "")
        else:
            self.title_label.set_text("No open windows")
            self.ws_label.set_text("")

    def step(self, delta):
        if not self.visible:
            self.clients = self.fetch_clients()
            if not self.clients:
                subprocess.Popen(["hyprctl", "dispatch", "submap", "reset"],
                                 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
                return
            if len(self.clients) == 1:
                self.selected_idx = 0
            else:
                self.selected_idx = 1 if delta > 0 else len(self.clients) - 1
            self.rebuild_grid()
            self.update_selection()
            self.win.show_all()
            self.win.resize(1, 1)
            self.visible = True
        else:
            if not self.clients:
                return
            self.selected_idx = (self.selected_idx + delta) % len(self.clients)
            self.update_selection()

    def step_row(self, row_delta):
        if not self.visible or not self.clients:
            return
        nxt = self.selected_idx + row_delta * COLUMNS
        if 0 <= nxt < len(self.clients):
            self.selected_idx = nxt
            self.update_selection()

    def show_preview(self):
        """Show the switcher on the current window list without committing (for testing)."""
        self.clients = self.fetch_clients()
        if not self.clients:
            return
        self.selected_idx = 1 if len(self.clients) > 1 else 0
        self.rebuild_grid()
        self.update_selection()
        self.win.show_all()
        self.win.resize(1, 1)
        self.visible = True

    def commit(self, reset_submap=False):
        target_addr = None
        if self.visible and 0 <= self.selected_idx < len(self.clients):
            target_addr = self.clients[self.selected_idx].get("address")
        self.visible = False
        self.win.hide()
        if reset_submap:
            subprocess.Popen(["hyprctl", "dispatch", "submap", "reset"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        if target_addr:
            subprocess.Popen(["hyprctl", "dispatch", "focuswindow", f"address:{target_addr}"],
                             stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)

    def cancel(self):
        self.visible = False
        self.win.hide()

    def handle_command(self, cmd):
        if cmd == "next":
            self.step(1)
        elif cmd == "prev":
            self.step(-1)
        elif cmd == "up":
            self.step_row(-1)
        elif cmd == "down":
            self.step_row(1)
        elif cmd == "commit":
            self.commit(reset_submap=False)
        elif cmd == "cancel":
            self.cancel()
        elif cmd == "preview":
            self.show_preview()
        elif cmd == "reload":
            self.apply_theme()
        elif cmd == "quit":
            Gtk.main_quit()
        return False


def start_socket_server(app):
    try:
        os.unlink(SOCK_PATH)
    except FileNotFoundError:
        pass
    srv = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
    srv.bind(SOCK_PATH)
    os.chmod(SOCK_PATH, 0o600)
    srv.listen(16)

    def loop():
        while True:
            try:
                conn, _ = srv.accept()
                with conn:
                    data = conn.recv(128).decode("utf-8", errors="ignore").strip()
                    if data:
                        GLib.idle_add(app.handle_command, data)
                    conn.sendall(b"ok\n")
            except OSError:
                break

    t = threading.Thread(target=loop, daemon=True)
    t.start()
    return srv


def main():
    lock_fd = open(LOCK_PATH, "w")
    try:
        fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
    except BlockingIOError:
        sys.exit(0)

    app = XPAltTabDaemon()
    srv = start_socket_server(app)

    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGHUP, lambda: (app.apply_theme(), True)[1])
    GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda: (Gtk.main_quit(), False)[1])

    try:
        Gtk.main()
    finally:
        try:
            srv.close()
            os.unlink(SOCK_PATH)
        except OSError:
            pass
        lock_fd.close()


if __name__ == "__main__":
    main()
