Files
hypr-xp/bin/xp-shutdown-dialog

453 lines
14 KiB
Python
Executable File

#!/usr/bin/env python3
"""Authentic Windows XP SP3 msgina.dll Turn Off Computer dialog (DIALOG 20100)."""
import os
import signal
import subprocess
import sys
import cairo
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 Gdk, GdkPixbuf, GLib, Gtk, GtkLayerShell # noqa: E402
from PIL import Image # noqa: E402
MSGINA_DIR = "/home/carsten/.local/src/xp-iso-extracted/res/msgina/bitmaps"
BG_PATH = f"{MSGINA_DIR}/20142.png"
FLAG_PATH = f"{MSGINA_DIR}/20141.png"
SPRITES_PATH = f"{MSGINA_DIR}/20150.png"
SOUND_SCRIPT = "/home/carsten/.config/hypr/scripts/xp-sound.sh"
MUTE_FILE = "/home/carsten/.config/hypr/mute-xp-sounds"
PID_FILE = f"/tmp/xp-shutdown-dialog-{os.getuid()}.pid"
DIALOG_W = 313
DIALOG_H = 198
# 20150.png vertical 32x32 sprite indices: (normal, pressed, hover)
BTN_SPRITES = {
"turnoff": (0, 1, 2),
"standby": (3, 4, 5),
"restart": (6, 7, 8),
}
CSS = b"""
window#xp-shutdown-backdrop {
background-color: rgba(0, 0, 0, 0.42);
}
#xp-shutdown-card {
background-color: #003399;
box-shadow: 0 0 0 1px #001B5A, 0 8px 24px rgba(0, 0, 0, 0.58);
}
#xp-shutdown-title {
color: #FFFFFF;
font-family: "Tahoma", "Trebuchet MS", sans-serif;
font-size: 12.5pt;
font-weight: bold;
text-shadow: 1px 1px 2px #001850;
}
.xp-power-btn {
background: transparent;
border: none;
border-radius: 4px;
padding: 0;
margin: 0;
box-shadow: none;
min-width: 32px;
min-height: 32px;
}
.xp-power-btn:focus {
outline: 1px dotted rgba(255, 255, 255, 0.85);
outline-offset: 2px;
}
.xp-power-label {
color: #FFFFFF;
font-family: "Tahoma", sans-serif;
font-size: 8.5pt;
font-weight: bold;
text-shadow: 1px 1px 1px #002373;
}
.xp-bar-btn {
background-image: linear-gradient(to bottom, #FFFFFF 0%, #F4F3EE 35%, #E7E3D4 85%, #D5CFC0 100%);
color: #000000;
font-family: "Tahoma", sans-serif;
font-size: 8pt;
font-weight: normal;
border: 1px solid #003C74;
border-radius: 3px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.85);
padding: 0 6px;
min-height: 0;
min-width: 0;
}
.xp-bar-btn:hover {
border-color: #E59700;
box-shadow: inset 0 0 0 1px #FCD37D;
}
.xp-bar-btn:active {
background-image: linear-gradient(to bottom, #CDC9BC 0%, #E5E1D4 100%);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.2);
}
.xp-bar-btn:focus {
outline: 1px dotted #000000;
outline-offset: -3px;
}
"""
def pil_to_pixbuf(im: Image.Image) -> GdkPixbuf.Pixbuf:
rgba = im.convert("RGBA")
w, h = rgba.size
return GdkPixbuf.Pixbuf.new_from_bytes(
GLib.Bytes.new(rgba.tobytes()),
GdkPixbuf.Colorspace.RGB,
True,
8,
w,
h,
w * 4,
)
def load_button_sprites() -> dict[str, dict[str, GdkPixbuf.Pixbuf]]:
sheet = Image.open(SPRITES_PATH).convert("RGBA")
px = sheet.load()
for y in range(sheet.height):
for x in range(sheet.width):
r, g, b, _ = px[x, y]
if r >= 235 and g <= 25 and b >= 235:
px[x, y] = (0, 0, 0, 0)
sprites: dict[str, dict[str, GdkPixbuf.Pixbuf]] = {}
for key, (n_idx, p_idx, h_idx) in BTN_SPRITES.items():
sprites[key] = {
"normal": pil_to_pixbuf(sheet.crop((0, n_idx * 32, 32, (n_idx + 1) * 32))),
"pressed": pil_to_pixbuf(sheet.crop((0, p_idx * 32, 32, (p_idx + 1) * 32))),
"hover": pil_to_pixbuf(sheet.crop((0, h_idx * 32, 32, (h_idx + 1) * 32))),
}
return sprites
class TurnOffDialog(Gtk.Window):
def __init__(self) -> None:
super().__init__(type=Gtk.WindowType.TOPLEVEL)
self.set_name("xp-shutdown-backdrop")
self.set_title("Turn off computer")
self.set_decorated(False)
self.set_app_paintable(True)
screen = self.get_screen()
visual = screen.get_rgba_visual()
if visual is not None:
self.set_visual(visual)
GtkLayerShell.init_for_window(self)
GtkLayerShell.set_namespace(self, "xp-shutdown-dialog")
GtkLayerShell.set_layer(self, GtkLayerShell.Layer.OVERLAY)
GtkLayerShell.set_exclusive_zone(self, -1)
GtkLayerShell.set_keyboard_mode(self, GtkLayerShell.KeyboardMode.EXCLUSIVE)
for edge in (
GtkLayerShell.Edge.TOP,
GtkLayerShell.Edge.BOTTOM,
GtkLayerShell.Edge.LEFT,
GtkLayerShell.Edge.RIGHT,
):
GtkLayerShell.set_anchor(self, edge, True)
provider = Gtk.CssProvider()
provider.load_from_data(CSS)
Gtk.StyleContext.add_provider_for_screen(
screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION
)
self.sprites = load_button_sprites()
self.buttons: dict[str, Gtk.Button] = {}
self.btn_images: dict[str, Gtk.Image] = {}
self.btn_hovered: dict[str, bool] = {}
self.btn_pressed: dict[str, bool] = {}
center_box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL)
center_box.set_halign(Gtk.Align.CENTER)
center_box.set_valign(Gtk.Align.CENTER)
self.add(center_box)
card = Gtk.EventBox()
card.set_name("xp-shutdown-card")
card.set_size_request(DIALOG_W, DIALOG_H)
center_box.pack_start(card, False, False, 0)
fixed = Gtk.Fixed()
fixed.set_size_request(DIALOG_W, DIALOG_H)
card.add(fixed)
# msgina.dll 20142.png 313x198 background plate
bg_pb = pil_to_pixbuf(Image.open(BG_PATH))
bg_img = Gtk.Image.new_from_pixbuf(bg_pb)
fixed.put(bg_img, 0, 0)
# msgina.dll 20141.png 48x40 Windows flag header (DIALOG 20100 item 20101)
flag_pb = pil_to_pixbuf(Image.open(FLAG_PATH))
flag_img = Gtk.Image.new_from_pixbuf(flag_pb)
fixed.put(flag_img, DIALOG_W - 48, 1)
# Title (DIALOG 20100 item 20102)
title_lbl = Gtk.Label(label="Turn off computer")
title_lbl.set_name("xp-shutdown-title")
title_lbl.set_size_request(246, 42)
title_lbl.set_xalign(0.0)
title_lbl.set_yalign(0.5)
fixed.put(title_lbl, 12, 0)
# Three primary msgina 32x32 action buttons (DIALOG 20100 items 20104, 20103, 20105)
specs = [
("standby", "<u>S</u>tand By", 54, 32, self.on_standby),
("turnoff", "T<u>u</u>rn Off", 140, 118, self.on_turnoff),
("restart", "<u>R</u>estart", 226, 204, self.on_restart),
]
for key, markup, btn_x, lbl_x, handler in specs:
self._add_power_button(fixed, key, markup, btn_x, 76, lbl_x, 114, handler)
# Bottom bar compact controls (Lock / Log Off / Mute Sounds) + Cancel (item 2)
self._add_bar_button(fixed, "Lock", 10, 166, 44, 22, self.on_lock)
self._add_bar_button(fixed, "Log Off", 58, 166, 54, 22, self.on_logoff)
self.mute_btn = self._add_bar_button(
fixed, self._mute_label(), 116, 166, 96, 22, self.on_toggle_mute
)
self.cancel_btn = self._add_bar_button(
fixed, "Cancel", 241, 166, 61, 22, lambda *_: self.close_dialog()
)
self.connect("draw", self.on_draw)
self.connect("key-press-event", self.on_key_press)
self.connect("destroy", self.on_destroy)
self.show_all()
self.cancel_btn.grab_focus()
@staticmethod
def on_draw(_widget, ctx) -> bool:
ctx.save()
ctx.set_operator(cairo.OPERATOR_SOURCE)
ctx.set_source_rgba(0.0, 0.0, 0.0, 0.42)
ctx.paint()
ctx.restore()
return False
def _add_power_button(
self,
fixed: Gtk.Fixed,
key: str,
markup: str,
btn_x: int,
btn_y: int,
lbl_x: int,
lbl_y: int,
handler,
) -> None:
btn = Gtk.Button()
btn.get_style_context().add_class("xp-power-btn")
btn.set_relief(Gtk.ReliefStyle.NONE)
btn.set_size_request(32, 32)
btn.set_can_focus(True)
img = Gtk.Image.new_from_pixbuf(self.sprites[key]["normal"])
btn.set_image(img)
btn.set_always_show_image(True)
self.buttons[key] = btn
self.btn_images[key] = img
self.btn_hovered[key] = False
self.btn_pressed[key] = False
btn.add_events(
Gdk.EventMask.ENTER_NOTIFY_MASK
| Gdk.EventMask.LEAVE_NOTIFY_MASK
| Gdk.EventMask.BUTTON_PRESS_MASK
| Gdk.EventMask.BUTTON_RELEASE_MASK
)
btn.connect("enter-notify-event", lambda *_: self._set_state(key, hovered=True))
btn.connect("leave-notify-event", lambda *_: self._set_state(key, hovered=False, pressed=False))
btn.connect("button-press-event", lambda *_: self._set_state(key, pressed=True))
btn.connect("button-release-event", lambda *_: self._set_state(key, pressed=False))
btn.connect("clicked", lambda *_: handler())
fixed.put(btn, btn_x, btn_y)
lbl = Gtk.Label()
lbl.set_markup(markup)
lbl.get_style_context().add_class("xp-power-label")
lbl.set_size_request(76, 16)
lbl.set_xalign(0.5)
lbl.set_yalign(0.5)
fixed.put(lbl, lbl_x, lbl_y)
def _add_bar_button(
self,
fixed: Gtk.Fixed,
label: str,
x: int,
y: int,
w: int,
h: int,
handler,
) -> Gtk.Button:
btn = Gtk.Button(label=label)
btn.get_style_context().add_class("xp-bar-btn")
btn.set_size_request(w, h)
btn.connect("clicked", lambda *_: handler())
fixed.put(btn, x, y)
return btn
def _set_state(self, key: str, hovered=None, pressed=None) -> bool:
if hovered is not None:
self.btn_hovered[key] = hovered
if pressed is not None:
self.btn_pressed[key] = pressed
if self.btn_pressed[key]:
state = "pressed"
elif self.btn_hovered[key]:
state = "hover"
else:
state = "normal"
self.btn_images[key].set_from_pixbuf(self.sprites[key][state])
return False
@staticmethod
def _mute_label() -> str:
return "Unmute Sounds" if os.path.exists(MUTE_FILE) else "Mute Sounds"
@staticmethod
def _play_sound(name: str) -> None:
if os.path.exists(SOUND_SCRIPT):
subprocess.Popen(
[SOUND_SCRIPT, name],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
def _run_after_sound(self, sound_name: str, delay_ms: int, cmd: list[str]) -> None:
self._play_sound(sound_name)
self.hide()
def execute():
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.close_dialog()
return False
GLib.timeout_add(delay_ms, execute)
def on_standby(self) -> None:
self._run_after_sound("shutdown", 600, ["systemctl", "suspend"])
def on_turnoff(self) -> None:
self._run_after_sound("shutdown", 600, ["systemctl", "poweroff"])
def on_restart(self) -> None:
self._run_after_sound("shutdown", 600, ["systemctl", "reboot"])
def on_lock(self) -> None:
self.hide()
subprocess.Popen(["hyprlock"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
self.close_dialog()
def on_logoff(self) -> None:
self._run_after_sound("logoff", 500, ["hyprctl", "dispatch", "exit"])
def on_toggle_mute(self) -> None:
if os.path.exists(MUTE_FILE):
try:
os.remove(MUTE_FILE)
except OSError:
pass
self._play_sound("ding")
subprocess.Popen(
["notify-send", "-i", "audio-volume-high", "XP Sounds", "System sounds enabled"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
else:
open(MUTE_FILE, "a").close()
subprocess.Popen(
["notify-send", "-i", "audio-volume-muted", "XP Sounds", "System sounds muted"],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
self.mute_btn.set_label(self._mute_label())
def on_key_press(self, _widget, event) -> bool:
keyval = event.keyval
if keyval == Gdk.KEY_Escape:
self.close_dialog()
return True
if keyval in (Gdk.KEY_s, Gdk.KEY_S):
self.on_standby()
return True
if keyval in (Gdk.KEY_u, Gdk.KEY_U):
self.on_turnoff()
return True
if keyval in (Gdk.KEY_r, Gdk.KEY_R):
self.on_restart()
return True
order = ["standby", "turnoff", "restart"]
focused = self.get_focus()
if keyval in (Gdk.KEY_Left, Gdk.KEY_Right):
for idx, key in enumerate(order):
if focused is self.buttons[key]:
step = -1 if keyval == Gdk.KEY_Left else 1
self.buttons[order[(idx + step) % len(order)]].grab_focus()
return True
return False
def close_dialog(self) -> None:
self.destroy()
Gtk.main_quit()
def on_destroy(self, *_args) -> None:
remove_pid()
def write_pid() -> None:
try:
with open(PID_FILE, "w", encoding="utf-8") as fh:
fh.write(str(os.getpid()))
except OSError:
pass
def remove_pid() -> None:
try:
if os.path.exists(PID_FILE):
with open(PID_FILE, "r", encoding="utf-8") as fh:
if fh.read().strip() == str(os.getpid()):
os.remove(PID_FILE)
except OSError:
pass
def main() -> int:
write_pid()
win = TurnOffDialog()
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGTERM, lambda *_: win.close_dialog())
GLib.unix_signal_add(GLib.PRIORITY_DEFAULT, signal.SIGINT, lambda *_: win.close_dialog())
try:
Gtk.main()
finally:
remove_pid()
return 0
if __name__ == "__main__":
sys.exit(main())