-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
291 lines (251 loc) · 10.9 KB
/
Copy pathapp.py
File metadata and controls
291 lines (251 loc) · 10.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""Keydial Config — Web GUI for Huion Keydial Mini (K20) key remapping via keyd."""
import json
import os
import re
import subprocess
from pathlib import Path
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
PROFILES_DIR = Path(__file__).parent / "profiles"
ACTIVE_CONF = Path(__file__).parent / "active.conf"
DEVICE_ID = "256c:8251"
# Physical layout: row definitions mapping position → raw keycode
# Derived from evtest/keyd monitor capture of the actual device
LAYOUT = {
"rows": [
{"keys": ["k", "g", "l", "delete"]},
{"keys": ["i", "d", "b", "e"]},
{"keys": ["s", "z", "c", "v"]},
{"keys": ["leftcontrol", "leftalt", "leftshift"]},
{"keys": ["space", "n"]},
],
"standalone": ["enter"],
"dial_push": "playpause",
"dial_scroll": "native (page up/down)",
"device_id": DEVICE_ID,
}
# Actions available in the UI
ACTIONS = {
"keys": [
{"id": "escape", "label": "Escape", "keyd": "escape"},
{"id": "enter", "label": "Enter", "keyd": "enter"},
{"id": "tab", "label": "Tab", "keyd": "tab"},
{"id": "shift-tab", "label": "Shift+Tab", "keyd": "S-tab"},
{"id": "up", "label": "Up Arrow", "keyd": "up"},
{"id": "down", "label": "Down Arrow", "keyd": "down"},
{"id": "left", "label": "Left Arrow", "keyd": "left"},
{"id": "right", "label": "Right Arrow", "keyd": "right"},
{"id": "backspace", "label": "Backspace", "keyd": "backspace"},
{"id": "delete-key", "label": "Delete", "keyd": "delete"},
{"id": "space-key", "label": "Space", "keyd": "space"},
{"id": "home", "label": "Home", "keyd": "home"},
{"id": "end", "label": "End", "keyd": "end"},
{"id": "pageup", "label": "Page Up", "keyd": "pageup"},
{"id": "pagedown", "label": "Page Down", "keyd": "pagedown"},
],
"combos": [
{"id": "ctrl-c", "label": "Ctrl+C", "keyd": "C-c"},
{"id": "ctrl-z", "label": "Ctrl+Z", "keyd": "C-z"},
{"id": "ctrl-a", "label": "Ctrl+A", "keyd": "C-a"},
{"id": "ctrl-l", "label": "Ctrl+L (clear)", "keyd": "C-l"},
{"id": "ctrl-d", "label": "Ctrl+D", "keyd": "C-d"},
{"id": "ctrl-s", "label": "Ctrl+S (save)", "keyd": "C-s"},
{"id": "ctrl-x", "label": "Ctrl+X (cut)", "keyd": "C-x"},
{"id": "ctrl-v", "label": "Ctrl+V (paste)", "keyd": "C-v"},
{"id": "ctrl-b", "label": "Ctrl+B (tmux)", "keyd": "C-b"},
{"id": "ctrl-e", "label": "Ctrl+E", "keyd": "C-e"},
],
"macros": [
{"id": "yes-enter", "label": "y + Enter", "keyd": "macro(y enter)"},
{"id": "no-enter", "label": "n + Enter", "keyd": "macro(n enter)"},
{"id": "double-ctrl-c", "label": "Ctrl+C x2", "keyd": "macro(C-c 50ms C-c)"},
{"id": "slash-commit", "label": "/commit", "keyd": "macro(/ c o m m i t)"},
{"id": "slash-review", "label": "/review", "keyd": "macro(/ r e v i e w)"},
{"id": "slash-clear", "label": "/clear", "keyd": "macro(/ c l e a r)"},
{"id": "slash-compact", "label": "/compact", "keyd": "macro(/ c o m p a c t)"},
{"id": "slash-help", "label": "/help", "keyd": "macro(/ h e l p)"},
{"id": "slash-begin", "label": "/begin", "keyd": "macro(/ b e g i n)"},
{"id": "slash-elegance", "label": "/elegance", "keyd": "macro(/ e l e g a n c e)"},
{"id": "slash-hitit", "label": "/hitit", "keyd": "macro(/ h i t i t)"},
{"id": "slash-quicksave", "label": "/quicksave", "keyd": "macro(/ q u i c k s a v e)"},
{"id": "slash-pushit", "label": "/pushit", "keyd": "macro(/ p u s h i t)"},
{"id": "slash-wrap", "label": "/wrap", "keyd": "macro(/ w r a p)"},
{"id": "slash-doublecheck", "label": "/doublecheck", "keyd": "macro(/ d o u b l e c h e c k)"},
{"id": "slash-doubt", "label": "/doubt", "keyd": "macro(/ d o u b t)"},
{"id": "slash-consensus", "label": "/consensus", "keyd": "macro(/ c o n s e n s u s)"},
{"id": "slash-thinkagain", "label": "/thinkagain", "keyd": "macro(/ t h i n k a g a i n)"},
{"id": "slash-ultraplan", "label": "/ultraplan", "keyd": "macro(/ u l t r a p l a n)"},
{"id": "slash-enhance", "label": "/enhance", "keyd": "macro(/ e n h a n c e)"},
{"id": "slash-harvest", "label": "/harvest", "keyd": "macro(/ h a r v e s t)"},
{"id": "slash-janitor", "label": "/janitor", "keyd": "macro(/ j a n i t o r)"},
{"id": "slash-shipit", "label": "/shipit", "keyd": "macro(/ s h i p i t)"},
{"id": "slash-plan", "label": "/plan", "keyd": "macro(/ p l a n)"},
],
}
def parse_keyd_conf(text: str) -> dict:
"""Parse a keyd .conf file into a {raw_key: keyd_action} dict."""
mappings = {}
for line in text.splitlines():
line = line.strip()
if not line or line.startswith("#") or line.startswith("["):
continue
m = re.match(r"^(\S+)\s*=\s*(.+)$", line)
if m:
mappings[m.group(1)] = m.group(2).strip()
return mappings
def generate_keyd_conf(mappings: dict, profile_name: str = "custom") -> str:
"""Generate a keyd .conf file from a {raw_key: keyd_action} dict."""
lines = [
f"# Keydial Mini config — profile: {profile_name}",
f"# Generated by keydial-config",
"",
"[ids]",
DEVICE_ID,
"",
"[main]",
"",
]
for raw_key, action in mappings.items():
lines.append(f"{raw_key} = {action}")
lines.append("")
return "\n".join(lines)
def action_keyd_to_id(keyd_str: str) -> dict:
"""Convert a keyd action string to a UI-friendly {id, type} dict."""
# Handle timeout(tap_action, ms, hold_action) dual-action
tm = re.match(r"^timeout\((.+),\s*(\d+),\s*(.+)\)$", keyd_str)
if tm:
tap = action_keyd_to_id(tm.group(1).strip())
hold = action_keyd_to_id(tm.group(3).strip())
return {
"id": "timeout",
"type": "timeout",
"tap": tap,
"hold": hold,
"ms": int(tm.group(2)),
"raw": keyd_str,
}
for category in ("keys", "combos", "macros"):
for action in ACTIONS[category]:
if action["keyd"] == keyd_str:
return {"id": action["id"], "type": category.rstrip("s")}
# Custom macro or unknown — return as custom
return {"id": "custom", "type": "custom", "raw": keyd_str}
def action_id_to_keyd(action_id: str, custom_raw: str = "") -> str:
"""Convert a UI action ID back to keyd syntax."""
if action_id == "custom":
return custom_raw
if action_id == "passthrough":
return ""
for category in ("keys", "combos", "macros"):
for action in ACTIONS[category]:
if action["id"] == action_id:
return action["keyd"]
return custom_raw or ""
# --- Routes ---
@app.route("/")
def index():
return render_template("index.html")
@app.route("/layout")
def layout_view():
return render_template("layout.html")
@app.route("/api/layout")
def get_layout():
"""Return the physical key layout and available actions."""
return jsonify({"layout": LAYOUT, "actions": ACTIONS})
@app.route("/api/config")
def get_config():
"""Return the current active config as structured data."""
if ACTIVE_CONF.exists():
text = ACTIVE_CONF.read_text()
else:
# Try to read from keyd directly
system_conf = Path("/etc/keyd/default.conf")
if system_conf.exists():
text = system_conf.read_text()
else:
return jsonify({"mappings": {}, "profile": "none"})
raw_mappings = parse_keyd_conf(text)
mappings = {}
for raw_key, keyd_action in raw_mappings.items():
mappings[raw_key] = action_keyd_to_id(keyd_action)
return jsonify({"mappings": mappings, "raw": raw_mappings})
@app.route("/api/config", methods=["POST"])
def save_config():
"""Save a new config and optionally apply it."""
data = request.json
mappings = {}
for raw_key, action_data in data.get("mappings", {}).items():
if isinstance(action_data, str):
keyd_str = action_id_to_keyd(action_data)
elif isinstance(action_data, dict):
keyd_str = action_id_to_keyd(
action_data.get("id", ""), action_data.get("raw", "")
)
else:
continue
if keyd_str:
mappings[raw_key] = keyd_str
profile = data.get("profile", "custom")
conf_text = generate_keyd_conf(mappings, profile)
ACTIVE_CONF.write_text(conf_text)
result = {"saved": True, "file": str(ACTIVE_CONF)}
if data.get("apply", False):
try:
subprocess.run(
["sudo", "/usr/local/bin/keyd-apply", str(ACTIVE_CONF)],
check=True,
capture_output=True,
text=True,
)
result["applied"] = True
except subprocess.CalledProcessError as e:
result["applied"] = False
result["error"] = e.stderr
except FileNotFoundError:
result["applied"] = False
result["error"] = "keyd-apply not installed. Run: sudo cp keyd-apply.sh /usr/local/bin/keyd-apply"
return jsonify(result)
@app.route("/api/apply", methods=["POST"])
def apply_config():
"""Apply the current active.conf to keyd."""
if not ACTIVE_CONF.exists():
return jsonify({"error": "No active config. Save first."}), 400
try:
subprocess.run(
["sudo", "/usr/local/bin/keyd-apply", str(ACTIVE_CONF)],
check=True,
capture_output=True,
text=True,
)
return jsonify({"applied": True})
except subprocess.CalledProcessError as e:
return jsonify({"applied": False, "error": e.stderr}), 500
except FileNotFoundError:
return jsonify({"applied": False, "error": "keyd-apply not installed"}), 500
@app.route("/api/profiles")
def list_profiles():
"""List available profiles."""
profiles = []
for f in sorted(PROFILES_DIR.glob("*.conf")):
profiles.append({"name": f.stem, "file": f.name})
return jsonify({"profiles": profiles})
@app.route("/api/profiles/<name>")
def get_profile(name):
"""Load a specific profile."""
conf_file = PROFILES_DIR / f"{name}.conf"
if not conf_file.exists():
return jsonify({"error": f"Profile '{name}' not found"}), 404
text = conf_file.read_text()
raw_mappings = parse_keyd_conf(text)
mappings = {}
for raw_key, keyd_action in raw_mappings.items():
mappings[raw_key] = action_keyd_to_id(keyd_action)
return jsonify({"mappings": mappings, "raw": raw_mappings, "profile": name})
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description="Keydial Config GUI")
parser.add_argument("--port", type=int, default=8484)
parser.add_argument("--host", default="127.0.0.1")
parser.add_argument("--debug", action="store_true")
args = parser.parse_args()
app.run(host=args.host, port=args.port, debug=args.debug)