touchflow-gestures 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
touch_flow/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """TouchFlow package."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,90 @@
1
+ """Categorized gesture action catalog and validation helpers for TouchFlow."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Dict, List, Tuple
7
+
8
+ from touch_flow.backend.kwin_engine import GestureAction, GestureRule
9
+
10
+
11
+ @dataclass(frozen=True)
12
+ class CatalogAction:
13
+ """Represents a pre-configured action entry in the catalog."""
14
+
15
+ label: str
16
+ kind: str
17
+ target: str
18
+ category: str
19
+
20
+
21
+ ACTION_CATALOG: Dict[str, List[Tuple[str, str, str]]] = {
22
+ "Window Controls": [
23
+ ("Tile Window Left", "plasma_shortcut", "kwin,Window Quick Tile Left"),
24
+ ("Tile Window Right", "plasma_shortcut", "kwin,Window Quick Tile Right"),
25
+ ("Maximize Window", "plasma_shortcut", "kwin,Window Maximize"),
26
+ ("Restore Window", "plasma_shortcut", "kwin,Window Restore"),
27
+ ("Minimize Window", "plasma_shortcut", "kwin,Window Minimize"),
28
+ ("Toggle Fullscreen", "plasma_shortcut", "kwin,Window Fullscreen"),
29
+ ("Close Window", "plasma_shortcut", "kwin,Window Close"),
30
+ ],
31
+ "Workspace & Multitasking": [
32
+ ("Mission Control (Overview)", "plasma_shortcut", "kwin,Overview"),
33
+ ("App Switcher (Alt+Tab)", "plasma_shortcut", "kwin,Walk Through Windows"),
34
+ ("App Switcher Reverse", "plasma_shortcut", "kwin,Walk Through Windows (Reverse)"),
35
+ ("Show Desktop", "plasma_shortcut", "kwin,Show Desktop"),
36
+ ("Switch Desktop Right", "plasma_shortcut", "kwin,Switch One Desktop to the Right"),
37
+ ("Switch Desktop Left", "plasma_shortcut", "kwin,Switch One Desktop to the Left"),
38
+ ("Lock Screen", "plasma_shortcut", "ksmserver,Lock Session"),
39
+ ],
40
+ "Media & Audio": [
41
+ ("Volume Up", "plasma_shortcut", "kmix,increase_volume"),
42
+ ("Volume Down", "plasma_shortcut", "kmix,decrease_volume"),
43
+ ("Mute Audio", "plasma_shortcut", "kmix,mute"),
44
+ ("Play / Pause Media", "plasma_shortcut", "mediacontrol,playpausemedia"),
45
+ ("Next Track", "plasma_shortcut", "mediacontrol,nextmedia"),
46
+ ("Previous Track", "plasma_shortcut", "mediacontrol,previousmedia"),
47
+ ],
48
+ "Browser Navigation": [
49
+ ("Navigate Back", "shortcut", "Alt+Left"),
50
+ ("Navigate Forward", "shortcut", "Alt+Right"),
51
+ ("New Tab", "shortcut", "Ctrl+T"),
52
+ ("Close Tab", "shortcut", "Ctrl+W"),
53
+ ],
54
+ }
55
+
56
+
57
+ def get_flat_catalog() -> List[CatalogAction]:
58
+ """Return all catalog actions as a flat list."""
59
+ items: List[CatalogAction] = []
60
+ for category, entries in ACTION_CATALOG.items():
61
+ for label, kind, target in entries:
62
+ items.append(CatalogAction(label=label, kind=kind, target=target, category=category))
63
+ return items
64
+
65
+
66
+ def validate_action(action: GestureAction) -> Tuple[bool, str]:
67
+ """Validate that a GestureAction has a supported kind and non-empty target."""
68
+ if not action.kind or not action.kind.strip():
69
+ return False, "Action kind cannot be empty."
70
+ if not action.target or not action.target.strip():
71
+ return False, "Action target cannot be empty."
72
+ return True, ""
73
+
74
+
75
+ def validate_rules(rules: List[GestureRule]) -> Tuple[bool, List[str]]:
76
+ """Validate a list of GestureRules, returning (is_valid, error_messages)."""
77
+ errors: List[str] = []
78
+ for idx, rule in enumerate(rules, start=1):
79
+ if rule.fingers < 2 or rule.fingers > 5:
80
+ errors.append(f"Rule #{idx}: finger count {rule.fingers} must be between 2 and 5.")
81
+ if rule.gesture_type not in ("swipe", "pinch", "hold"):
82
+ errors.append(f"Rule #{idx}: unsupported gesture type '{rule.gesture_type}'.")
83
+ if not rule.actions:
84
+ errors.append(f"Rule #{idx}: at least one action is required.")
85
+ continue
86
+ for action in rule.actions:
87
+ ok, msg = validate_action(action)
88
+ if not ok:
89
+ errors.append(f"Rule #{idx}: {msg}")
90
+ return len(errors) == 0, errors
@@ -0,0 +1,198 @@
1
+ """Conflict detector and remediation engine for Linux gesture daemons."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ from dataclasses import dataclass
9
+ from pathlib import Path
10
+ from typing import List, Optional
11
+
12
+
13
+ @dataclass
14
+ class ConflictIssue:
15
+ """Represents a detected conflicting gesture software or daemon."""
16
+
17
+ id: str
18
+ name: str
19
+ is_running: bool
20
+ is_autostart_active: bool
21
+ is_service_active: bool
22
+ description: str
23
+ recommendation: str
24
+
25
+ @property
26
+ def has_conflict(self) -> bool:
27
+ return self.is_running or self.is_autostart_active or self.is_service_active
28
+
29
+
30
+ class ConflictDetector:
31
+ """Scans and safely neutralizes competing or legacy gesture daemons."""
32
+
33
+ KNOWN_DAEMONS = [
34
+ {
35
+ "id": "touchegg",
36
+ "name": "Touchégg",
37
+ "process_name": "touchegg",
38
+ "service_name": "touchegg.service",
39
+ "system_autostart": "/etc/xdg/autostart/touchegg.desktop",
40
+ "user_autostart": Path.home() / ".config" / "autostart" / "touchegg.desktop",
41
+ "desc": "Legacy X11/Wayland gesture daemon. Conflicts with KWin Wayland libinput gestures.",
42
+ },
43
+ {
44
+ "id": "libinput-gestures",
45
+ "name": "libinput-gestures",
46
+ "process_name": "libinput-gestures",
47
+ "service_name": "libinput-gestures.service",
48
+ "system_autostart": "/etc/xdg/autostart/libinput-gestures.desktop",
49
+ "user_autostart": Path.home() / ".config" / "autostart" / "libinput-gestures.desktop",
50
+ "desc": "Custom libinput parser daemon. Can cause double gesture dispatch.",
51
+ },
52
+ {
53
+ "id": "fusuma",
54
+ "name": "Fusuma",
55
+ "process_name": "fusuma",
56
+ "service_name": "fusuma.service",
57
+ "system_autostart": None,
58
+ "user_autostart": Path.home() / ".config" / "autostart" / "fusuma.desktop",
59
+ "desc": "Ruby-based multi-touch gesture engine.",
60
+ },
61
+ ]
62
+
63
+ def scan_all(self) -> List[ConflictIssue]:
64
+ """Scan system for all known conflicting services."""
65
+ issues: List[ConflictIssue] = []
66
+
67
+ for item in self.KNOWN_DAEMONS:
68
+ proc_name = item["process_name"]
69
+ is_running = self._check_process(proc_name)
70
+
71
+ # Check service status
72
+ srv_name = item.get("service_name")
73
+ is_srv = self._check_service(srv_name) if srv_name else False
74
+
75
+ # Check autostart
76
+ is_autostart = self._check_autostart(
77
+ system_path=item.get("system_autostart"),
78
+ user_path=item.get("user_autostart"),
79
+ )
80
+
81
+ rec = (
82
+ f"Neutralize {item['name']} by disabling user autostart and stopping process."
83
+ if (is_running or is_autostart or is_srv)
84
+ else "Clean; no active conflict."
85
+ )
86
+
87
+ issue = ConflictIssue(
88
+ id=item["id"],
89
+ name=item["name"],
90
+ is_running=is_running,
91
+ is_autostart_active=is_autostart,
92
+ is_service_active=is_srv,
93
+ description=item["desc"],
94
+ recommendation=rec,
95
+ )
96
+ issues.append(issue)
97
+
98
+ return issues
99
+
100
+ def neutralize(self, conflict_id: str) -> bool:
101
+ """Safely neutralize a conflicting daemon without deleting system files."""
102
+ matched = next((d for d in self.KNOWN_DAEMONS if d["id"] == conflict_id), None)
103
+ if not matched:
104
+ return False
105
+
106
+ success = True
107
+
108
+ # 1. Kill running process if active
109
+ proc_name = matched["process_name"]
110
+ if self._check_process(proc_name):
111
+ try:
112
+ subprocess.run(["pkill", "-9", "-f", proc_name], check=False)
113
+ except Exception:
114
+ success = False
115
+
116
+ # 2. Disable user autostart by writing override with Hidden=true
117
+ user_autostart = matched.get("user_autostart")
118
+ if isinstance(user_autostart, Path):
119
+ try:
120
+ user_autostart.parent.mkdir(parents=True, exist_ok=True)
121
+ override_content = (
122
+ "[Desktop Entry]\n"
123
+ "Type=Application\n"
124
+ f"Name={matched['name']}\n"
125
+ "Hidden=true\n"
126
+ "X-GNOME-Autostart-enabled=false\n"
127
+ "X-KDE-autostart-after=none\n"
128
+ )
129
+ user_autostart.write_text(override_content, encoding="utf-8")
130
+ except Exception:
131
+ success = False
132
+
133
+ # 3. Disable user service if active
134
+ srv_name = matched.get("service_name")
135
+ if srv_name:
136
+ try:
137
+ subprocess.run(
138
+ ["systemctl", "--user", "stop", srv_name],
139
+ stdout=subprocess.PIPE,
140
+ stderr=subprocess.PIPE,
141
+ check=False,
142
+ )
143
+ except Exception:
144
+ pass
145
+
146
+ return success
147
+
148
+ def _check_process(self, proc_name: str) -> bool:
149
+ try:
150
+ res = subprocess.run(
151
+ ["pgrep", "-f", proc_name],
152
+ stdout=subprocess.PIPE,
153
+ stderr=subprocess.PIPE,
154
+ text=True,
155
+ check=False,
156
+ )
157
+ return res.returncode == 0 and bool(res.stdout.strip())
158
+ except Exception:
159
+ return False
160
+
161
+ def _check_service(self, srv_name: str) -> bool:
162
+ try:
163
+ res = subprocess.run(
164
+ ["systemctl", "is-active", srv_name],
165
+ stdout=subprocess.PIPE,
166
+ stderr=subprocess.PIPE,
167
+ text=True,
168
+ check=False,
169
+ )
170
+ if res.returncode == 0:
171
+ return True
172
+ res_user = subprocess.run(
173
+ ["systemctl", "--user", "is-active", srv_name],
174
+ stdout=subprocess.PIPE,
175
+ stderr=subprocess.PIPE,
176
+ text=True,
177
+ check=False,
178
+ )
179
+ return res_user.returncode == 0
180
+ except Exception:
181
+ return False
182
+
183
+ def _check_autostart(self, system_path: Optional[str], user_path: Optional[Path]) -> bool:
184
+ # Check user override first
185
+ if user_path and user_path.exists():
186
+ try:
187
+ text = user_path.read_text(encoding="utf-8", errors="replace")
188
+ if "Hidden=true" in text or "X-GNOME-Autostart-enabled=false" in text:
189
+ return False
190
+ return True
191
+ except Exception:
192
+ pass
193
+
194
+ # Check system autostart
195
+ if system_path and Path(system_path).exists():
196
+ return True
197
+
198
+ return False
@@ -0,0 +1,195 @@
1
+ """Hardware touchpad and desktop environment detection engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import re
7
+ import shutil
8
+ import subprocess
9
+ from dataclasses import dataclass, field
10
+ from pathlib import Path
11
+ from typing import List, Optional
12
+
13
+
14
+ @dataclass
15
+ class TouchpadDevice:
16
+ """Represents a detected touchpad device."""
17
+
18
+ name: str
19
+ vendor: str = ""
20
+ product: str = ""
21
+ bus: str = ""
22
+ sysfs_path: str = ""
23
+ event_node: str = ""
24
+ is_touchpad: bool = True
25
+ capabilities: List[str] = field(default_factory=list)
26
+
27
+
28
+ @dataclass
29
+ class DesktopEnvironment:
30
+ """Represents the active desktop and compositor environment."""
31
+
32
+ desktop: str
33
+ session_type: str # "wayland", "x11", "unknown"
34
+ compositor: str = ""
35
+ has_kwin_dbus: bool = False
36
+ has_inputactions_kwin: bool = False
37
+ details: str = ""
38
+
39
+
40
+ def detect_touchpads(devices_file: Path | str = "/proc/bus/input/devices") -> List[TouchpadDevice]:
41
+ """Parse /proc/bus/input/devices to find all physical and virtual touchpads."""
42
+ devices_path = Path(devices_file)
43
+ if not devices_path.exists():
44
+ return []
45
+
46
+ try:
47
+ content = devices_path.read_text(encoding="utf-8", errors="replace")
48
+ except Exception:
49
+ return []
50
+
51
+ touchpads: List[TouchpadDevice] = []
52
+ # Blocks in /proc/bus/input/devices are separated by blank lines
53
+ blocks = content.strip().split("\n\n")
54
+
55
+ for block in blocks:
56
+ lines = block.splitlines()
57
+ info: dict[str, str] = {}
58
+ handlers = ""
59
+
60
+ for line in lines:
61
+ line = line.strip()
62
+ if line.startswith("I:"):
63
+ # I: Bus=0018 Vendor=04f3 Product=307a Version=0100
64
+ for match in re.finditer(r"([A-Za-z]+)=([0-9a-fA-F]+)", line):
65
+ info[match.group(1).lower()] = match.group(2)
66
+ elif line.startswith("N: Name="):
67
+ info["name"] = line[len("N: Name="):].strip('"')
68
+ elif line.startswith("S: Sysfs="):
69
+ info["sysfs"] = line[len("S: Sysfs="):].strip()
70
+ elif line.startswith("H: Handlers="):
71
+ handlers = line[len("H: Handlers="):].strip()
72
+
73
+ name = info.get("name", "")
74
+ # Identify touchpad
75
+ is_tp = False
76
+ lower_name = name.lower()
77
+ if "touchpad" in lower_name or "trackpad" in lower_name or "synaptics" in lower_name:
78
+ is_tp = True
79
+ elif "elan" in lower_name or "alps" in lower_name:
80
+ if "mouse" in handlers.lower() or "event" in handlers.lower():
81
+ is_tp = True
82
+
83
+ if is_tp and name:
84
+ # Extract event handler (e.g. event11)
85
+ event_match = re.search(r"\b(event\d+)\b", handlers)
86
+ event_node = f"/dev/input/{event_match.group(1)}" if event_match else ""
87
+
88
+ caps = []
89
+ if "PROP=1" in block or "PROP=5" in block:
90
+ caps.append("pointer_device")
91
+
92
+ touchpads.append(
93
+ TouchpadDevice(
94
+ name=name,
95
+ vendor=info.get("vendor", ""),
96
+ product=info.get("product", ""),
97
+ bus=info.get("bus", ""),
98
+ sysfs_path=info.get("sysfs", ""),
99
+ event_node=event_node,
100
+ is_touchpad=True,
101
+ capabilities=caps,
102
+ )
103
+ )
104
+
105
+ return touchpads
106
+
107
+
108
+ def detect_desktop_environment() -> DesktopEnvironment:
109
+ """Detect current desktop environment, session type, and available gesture engines."""
110
+ xdg_desktop = os.environ.get("XDG_CURRENT_DESKTOP", "").strip()
111
+ session_type = os.environ.get("XDG_SESSION_TYPE", "unknown").lower()
112
+ session_desktop = os.environ.get("XDG_SESSION_DESKTOP", "").strip()
113
+
114
+ # Determine standard desktop name
115
+ desktop = "Unknown"
116
+ lower_xdg = xdg_desktop.lower()
117
+ lower_session = session_desktop.lower()
118
+ combined = f"{lower_xdg}:{lower_session}"
119
+
120
+ if "kde" in lower_xdg or "plasma" in lower_xdg or "kde" in lower_session or "plasma" in lower_session:
121
+ # If explicitly set to another desktop in XDG_CURRENT_DESKTOP, honor that
122
+ if "gnome" in lower_xdg:
123
+ desktop = "GNOME"
124
+ elif "hyprland" in lower_xdg:
125
+ desktop = "Hyprland"
126
+ elif "sway" in lower_xdg:
127
+ desktop = "Sway"
128
+ elif "xfce" in lower_xdg:
129
+ desktop = "XFCE"
130
+ elif "cinnamon" in lower_xdg:
131
+ desktop = "Cinnamon"
132
+ else:
133
+ desktop = "KDE"
134
+ elif "gnome" in combined:
135
+ desktop = "GNOME"
136
+ elif "hyprland" in combined:
137
+ desktop = "Hyprland"
138
+ elif "sway" in combined:
139
+ desktop = "Sway"
140
+ elif "xfce" in combined:
141
+ desktop = "XFCE"
142
+ elif "cinnamon" in combined:
143
+ desktop = "Cinnamon"
144
+ elif session_type == "x11":
145
+ desktop = "X11 Generic"
146
+
147
+ compositor = ""
148
+ has_kwin_dbus = False
149
+ has_inputactions_kwin = False
150
+
151
+ # Check for KWin D-Bus availability
152
+ qdbus_bin = shutil.which("qdbus6") or shutil.which("qdbus")
153
+ if qdbus_bin and desktop == "KDE":
154
+ try:
155
+ res = subprocess.run(
156
+ [qdbus_bin, "org.kde.KWin", "/KWin"],
157
+ stdout=subprocess.PIPE,
158
+ stderr=subprocess.PIPE,
159
+ text=True,
160
+ timeout=1.5,
161
+ )
162
+ if res.returncode == 0:
163
+ has_kwin_dbus = True
164
+ compositor = "kwin_wayland" if session_type == "wayland" else "kwin_x11"
165
+ except Exception:
166
+ pass
167
+
168
+ # Check inputactions KWin effect
169
+ if qdbus_bin and has_kwin_dbus:
170
+ try:
171
+ res = subprocess.run(
172
+ [qdbus_bin, "org.kde.KWin", "/Effects", "org.kde.kwin.Effects.isEffectLoaded", "kwin_gestures"],
173
+ stdout=subprocess.PIPE,
174
+ stderr=subprocess.PIPE,
175
+ text=True,
176
+ timeout=1.5,
177
+ )
178
+ if res.returncode == 0 and "true" in res.stdout.lower():
179
+ has_inputactions_kwin = True
180
+ except Exception:
181
+ pass
182
+
183
+ # Fallback check for ~/.config/inputactions/config.yaml
184
+ inputactions_cfg = Path.home() / ".config" / "inputactions" / "config.yaml"
185
+ if inputactions_cfg.exists():
186
+ has_inputactions_kwin = True
187
+
188
+ return DesktopEnvironment(
189
+ desktop=desktop,
190
+ session_type=session_type,
191
+ compositor=compositor,
192
+ has_kwin_dbus=has_kwin_dbus,
193
+ has_inputactions_kwin=has_inputactions_kwin,
194
+ details=f"{desktop} on {session_type} ({compositor or 'native'})",
195
+ )
@@ -0,0 +1,180 @@
1
+ """KDE Wayland InputActions gesture engine."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import time
9
+ from dataclasses import asdict, dataclass, field
10
+ from pathlib import Path
11
+ from typing import Any, Dict, List, Optional
12
+ import yaml
13
+
14
+
15
+ @dataclass
16
+ class GestureAction:
17
+ """Action executed on gesture trigger."""
18
+
19
+ kind: str # "plasma_shortcut", "command", "dbus", "shortcut"
20
+ target: str # e.g. "kwin,Window Quick Tile Left" or "/usr/bin/firefox"
21
+
22
+ def to_dict(self) -> dict[str, str]:
23
+ if self.kind in ("plasma_shortcut", "command", "dbus", "shortcut"):
24
+ return {self.kind: self.target}
25
+ return {"action": self.target}
26
+
27
+ @classmethod
28
+ def from_dict(cls, data: dict[str, Any]) -> "GestureAction":
29
+ if "plasma_shortcut" in data:
30
+ return cls(kind="plasma_shortcut", target=str(data["plasma_shortcut"]))
31
+ elif "command" in data:
32
+ return cls(kind="command", target=str(data["command"]))
33
+ key = next(iter(data), "unknown")
34
+ return cls(kind=key, target=str(data[key]))
35
+
36
+
37
+ @dataclass
38
+ class GestureRule:
39
+ """Individual gesture rule definition."""
40
+
41
+ gesture_type: str # "swipe", "pinch", "hold"
42
+ fingers: int # 3 or 4
43
+ direction: Optional[str] = None # "up", "down", "left", "right", "in", "out"
44
+ actions: List[GestureAction] = field(default_factory=list)
45
+ instant: bool = False
46
+
47
+ def to_dict(self) -> dict[str, Any]:
48
+ d: dict[str, Any] = {
49
+ "type": self.gesture_type,
50
+ "fingers": self.fingers,
51
+ }
52
+ if self.direction:
53
+ d["direction"] = self.direction
54
+ if self.instant:
55
+ d["instant"] = True
56
+ d["actions"] = [a.to_dict() for a in self.actions]
57
+ return d
58
+
59
+ @classmethod
60
+ def from_dict(cls, data: dict[str, Any]) -> "GestureRule":
61
+ g_type = data.get("type", "swipe")
62
+ fingers = int(data.get("fingers", 3))
63
+ direction = data.get("direction")
64
+ instant = bool(data.get("instant", False))
65
+
66
+ raw_actions = data.get("actions", [])
67
+ actions: List[GestureAction] = []
68
+ for raw in raw_actions:
69
+ if isinstance(raw, dict):
70
+ actions.append(GestureAction.from_dict(raw))
71
+
72
+ return cls(
73
+ gesture_type=g_type,
74
+ fingers=fingers,
75
+ direction=direction,
76
+ actions=actions,
77
+ instant=instant,
78
+ )
79
+
80
+
81
+ class KWinInputActionsEngine:
82
+ """Reads, validates, writes, and reloads KDE inputactions config.yaml."""
83
+
84
+ DEFAULT_CONFIG_PATH = Path.home() / ".config" / "inputactions" / "config.yaml"
85
+
86
+ def __init__(self, config_path: Optional[Path] = None):
87
+ self.config_path = config_path or self.DEFAULT_CONFIG_PATH
88
+
89
+ def load_rules(self) -> List[GestureRule]:
90
+ """Read gesture rules from config file."""
91
+ if not self.config_path.exists():
92
+ return []
93
+
94
+ try:
95
+ content = self.config_path.read_text(encoding="utf-8")
96
+ data = yaml.safe_load(content)
97
+ if not isinstance(data, dict):
98
+ return []
99
+
100
+ touchpad_sec = data.get("touchpad", {})
101
+ raw_gestures = touchpad_sec.get("gestures", [])
102
+ rules: List[GestureRule] = []
103
+
104
+ for raw in raw_gestures:
105
+ if isinstance(raw, dict):
106
+ rules.append(GestureRule.from_dict(raw))
107
+
108
+ return rules
109
+ except Exception:
110
+ return []
111
+
112
+ def save_rules(self, rules: List[GestureRule], backup: bool = True) -> bool:
113
+ """Atomically save rules to config file with optional backup."""
114
+ try:
115
+ self.config_path.parent.mkdir(parents=True, exist_ok=True)
116
+
117
+ if backup and self.config_path.exists():
118
+ backup_path = self.config_path.with_suffix(f".bak.{int(time.time())}")
119
+ shutil.copy2(self.config_path, backup_path)
120
+
121
+ payload = {
122
+ "touchpad": {
123
+ "gestures": [rule.to_dict() for rule in rules]
124
+ }
125
+ }
126
+
127
+ temp_path = self.config_path.with_suffix(".tmp")
128
+ with open(temp_path, "w", encoding="utf-8") as f:
129
+ f.write("# Generated by TouchFlow\n")
130
+ yaml.dump(payload, f, default_flow_style=False, sort_keys=False)
131
+
132
+ temp_path.replace(self.config_path)
133
+ return True
134
+ except Exception:
135
+ return False
136
+
137
+ def reload_kwin(self) -> bool:
138
+ """Signal KWin to reload configuration live via D-Bus."""
139
+ qdbus_bin = shutil.which("qdbus6") or shutil.which("qdbus")
140
+ if not qdbus_bin:
141
+ return False
142
+
143
+ success = True
144
+ try:
145
+ # 1. Trigger KWin reconfigure
146
+ res1 = subprocess.run(
147
+ [qdbus_bin, "org.kde.KWin", "/KWin", "org.kde.KWin.reconfigure"],
148
+ stdout=subprocess.PIPE,
149
+ stderr=subprocess.PIPE,
150
+ timeout=2.0,
151
+ )
152
+ if res1.returncode != 0:
153
+ success = False
154
+
155
+ # 2. Reload kwin_gestures effect if loaded
156
+ res2 = subprocess.run(
157
+ [qdbus_bin, "org.kde.KWin", "/Effects", "org.kde.kwin.Effects.isEffectLoaded", "kwin_gestures"],
158
+ stdout=subprocess.PIPE,
159
+ stderr=subprocess.PIPE,
160
+ text=True,
161
+ timeout=1.5,
162
+ )
163
+ if res2.returncode == 0 and "true" in res2.stdout.lower():
164
+ subprocess.run(
165
+ [qdbus_bin, "org.kde.KWin", "/Effects", "org.kde.kwin.Effects.unloadEffect", "kwin_gestures"],
166
+ stdout=subprocess.PIPE,
167
+ stderr=subprocess.PIPE,
168
+ timeout=1.5,
169
+ )
170
+ time.sleep(0.1)
171
+ subprocess.run(
172
+ [qdbus_bin, "org.kde.KWin", "/Effects", "org.kde.kwin.Effects.loadEffect", "kwin_gestures"],
173
+ stdout=subprocess.PIPE,
174
+ stderr=subprocess.PIPE,
175
+ timeout=1.5,
176
+ )
177
+ except Exception:
178
+ return False
179
+
180
+ return success