106 lines
4.3 KiB
Python
106 lines
4.3 KiB
Python
"""Правило окна KWin (KDE Plasma) для оверлея.
|
|
|
|
В Plasma 6 подсказка «под всеми окнами» от самого приложения часто игнорируется, а сам KWin
|
|
не даёт исключить окно из «Показать рабочий стол» (это сделано намеренно). Окно типа «док»
|
|
при «Показать рабочий стол» остаётся на месте, а правило KWin «Держать под другими» (Force)
|
|
опускает его под обычные окна. Правило привязано к классу окна `ruweather`; здесь мы просто
|
|
создаём его в ~/.config/kwinrulesrc — так же, как это делает «Правила для окон» в Параметрах системы.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import configparser
|
|
import os
|
|
import shutil
|
|
from pathlib import Path
|
|
|
|
RULE_ID = "ruweather-overlay"
|
|
|
|
RULE = {
|
|
"Description": "Погода Гидрометцентра (ruweather)",
|
|
"wmclass": "ruweather",
|
|
"wmclasscomplete": "false",
|
|
"wmclassmatch": "1", # 1 = точное совпадение класса окна
|
|
"below": "true", "belowrule": "2", # Держать под другими: Force
|
|
"skiptaskbar": "true", "skiptaskbarrule": "2", # не показывать в панели задач: Force
|
|
"skippager": "true", "skippagerrule": "2",
|
|
"skipswitcher": "true", "skipswitcherrule": "2", # не показывать в Alt+Tab
|
|
}
|
|
|
|
|
|
def rules_path() -> Path:
|
|
return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config") / "kwinrulesrc"
|
|
|
|
|
|
def _load() -> configparser.RawConfigParser:
|
|
cp = configparser.RawConfigParser(strict=False, delimiters=("=",), comment_prefixes=("#", ";"))
|
|
cp.optionxform = str # type: ignore[assignment] # регистр ключей важен
|
|
path = rules_path()
|
|
if path.exists():
|
|
cp.read(path, encoding="utf-8")
|
|
return cp
|
|
|
|
|
|
def _save(cp: configparser.RawConfigParser) -> None:
|
|
path = rules_path()
|
|
if path.exists():
|
|
backup = path.with_name(path.name + ".ruweather-backup")
|
|
if not backup.exists():
|
|
shutil.copy2(path, backup)
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
cp.write(f, space_around_delimiters=False)
|
|
|
|
|
|
def _rule_ids(cp: configparser.RawConfigParser) -> list:
|
|
raw = cp.get("General", "rules", fallback="") if cp.has_section("General") else ""
|
|
return [r for r in raw.split(",") if r]
|
|
|
|
|
|
def reload_kwin() -> bool:
|
|
"""Попросить KWin перечитать правила (как это делает модуль «Правила для окон»)."""
|
|
try:
|
|
from PySide6.QtDBus import QDBusConnection, QDBusInterface
|
|
bus = QDBusConnection.sessionBus()
|
|
if not bus.isConnected():
|
|
return False
|
|
iface = QDBusInterface("org.kde.KWin", "/KWin", "org.kde.KWin", bus)
|
|
if not iface.isValid():
|
|
return False
|
|
iface.call("reconfigure")
|
|
return True
|
|
except Exception: # noqa: BLE001
|
|
return False
|
|
|
|
|
|
def install() -> str:
|
|
cp = _load()
|
|
if not cp.has_section("General"):
|
|
cp.add_section("General")
|
|
ids = _rule_ids(cp)
|
|
if RULE_ID not in ids:
|
|
ids.append(RULE_ID)
|
|
cp.set("General", "rules", ",".join(ids))
|
|
cp.set("General", "count", str(len(ids)))
|
|
if cp.has_section(RULE_ID):
|
|
cp.remove_section(RULE_ID)
|
|
cp.add_section(RULE_ID)
|
|
for key, value in RULE.items():
|
|
cp.set(RULE_ID, key, value)
|
|
_save(cp)
|
|
ok = reload_kwin()
|
|
return ("Правило добавлено и применено." if ok else
|
|
"Правило добавлено в kwinrulesrc. Выполните вход заново или перезапустите KWin, чтобы оно подействовало.")
|
|
|
|
|
|
def remove() -> str:
|
|
cp = _load()
|
|
ids = [r for r in _rule_ids(cp) if r != RULE_ID]
|
|
if cp.has_section(RULE_ID):
|
|
cp.remove_section(RULE_ID)
|
|
if cp.has_section("General"):
|
|
cp.set("General", "rules", ",".join(ids))
|
|
cp.set("General", "count", str(len(ids)))
|
|
_save(cp)
|
|
reload_kwin()
|
|
return "Правило удалено."
|