-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkjump-config.py
More file actions
executable file
·719 lines (619 loc) · 24.8 KB
/
Copy pathkjump-config.py
File metadata and controls
executable file
·719 lines (619 loc) · 24.8 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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
#!/usr/bin/python3
"""
kjump-config — GUI for editing ~/.config/kjump/apps.json.
After Save & Apply, calls Reload() on the running kjumpd over D-Bus so the
changes take effect immediately. If kjumpd isn't running, the JSON is still
saved and will be picked up next time the daemon starts.
Run: ./kjump-config.py
./kjump-config.py --version
"""
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
from configparser import ConfigParser
from pathlib import Path
from PySide6.QtCore import Qt, QProcess, QTimer
from PySide6.QtGui import QBrush, QColor, QIcon, QKeySequence
from PySide6.QtWidgets import (
QAbstractItemView, QApplication, QDialog, QDialogButtonBox, QFormLayout,
QHBoxLayout, QHeaderView, QKeySequenceEdit, QLabel, QLineEdit,
QListWidget, QListWidgetItem, QMainWindow, QMessageBox, QPlainTextEdit,
QPushButton, QTableWidget, QTableWidgetItem, QVBoxLayout, QWidget,
)
# ---- Paths and constants --------------------------------------------------
CONFIG_FILE = Path(
os.environ.get("XDG_CONFIG_HOME", Path.home() / ".config")
) / "kjump" / "apps.json"
DESKTOP_DIRS = [
Path("/usr/share/applications"),
Path("/usr/local/share/applications"),
Path.home() / ".local/share/applications",
Path.home() / ".local/share/flatpak/exports/share/applications",
Path("/var/lib/flatpak/exports/share/applications"),
]
# Bump in lockstep with kjumpd.py and kjump.py — single-file scripts, no
# shared module to centralise it (see CLAUDE.md conventions).
__version__ = "0.1.0"
DAEMON_BUS = "org.kjump.Daemon"
DAEMON_PATH = "/Daemon"
DAEMON_IFACE = "org.kjump.Daemon"
# The Qt6 qdbus CLI has different names per distro: Fedora/Debian ship it as
# `qdbus-qt6`, Arch's qt6-tools ships it as `qdbus6`, and some setups only have
# a generic `qdbus`. Resolve once to whichever exists so Save & Apply and
# Pick-from-window work everywhere.
def resolve_qdbus(which=shutil.which):
"""Pick the Qt6 qdbus binary by name. Falls back to "qdbus-qt6" (so a
missing-binary error still names something installable) if none are found.
`which` is injectable for unit tests."""
for name in ("qdbus-qt6", "qdbus6", "qdbus"):
if which(name):
return name
return "qdbus-qt6"
QDBUS = resolve_qdbus()
# ---- apps.json IO ---------------------------------------------------------
def load_apps():
if not CONFIG_FILE.exists():
return []
return json.loads(CONFIG_FILE.read_text()).get("apps", [])
def save_apps(apps):
"""Atomic write: into .tmp, then replace."""
CONFIG_FILE.parent.mkdir(parents=True, exist_ok=True)
tmp = CONFIG_FILE.with_suffix(".json.tmp")
tmp.write_text(json.dumps({"apps": apps}, indent=2) + "\n")
tmp.replace(CONFIG_FILE)
def reload_daemon():
"""Tell kjumpd to re-read config. Returns (ok, message)."""
result = subprocess.run(
[QDBUS, DAEMON_BUS, DAEMON_PATH, f"{DAEMON_IFACE}.Reload"],
capture_output=True, text=True,
)
if result.returncode == 0:
return True, ""
return False, (result.stderr or result.stdout).strip()
def daemon_running():
"""Return True if kjumpd is reachable on the session bus."""
result = subprocess.run(
[QDBUS, DAEMON_BUS, DAEMON_PATH,
"org.freedesktop.DBus.Peer.Ping"],
capture_output=True, timeout=2,
)
return result.returncode == 0
_FALLBACK_ICON = "application-x-executable"
def get_icon(name):
"""Resolve a .desktop Icon= value to a QIcon, with a generic fallback."""
if not name:
return QIcon.fromTheme(_FALLBACK_ICON)
if os.path.isabs(name):
icon = QIcon(name)
return icon if not icon.isNull() else QIcon.fromTheme(_FALLBACK_ICON)
icon = QIcon.fromTheme(name)
return icon if not icon.isNull() else QIcon.fromTheme(_FALLBACK_ICON)
def parse_window_info(text):
"""Parse the multi-line key:value output of queryWindowInfo into a dict."""
info = {}
for line in text.splitlines():
if ":" in line:
k, v = line.split(":", 1)
info[k.strip()] = v.strip()
return info
# ---- .desktop database parsing -------------------------------------------
def _clean_exec(line):
"""Drop the %f/%F/%u/%U/etc. field codes that .desktop files use."""
try:
tokens = shlex.split(line)
except ValueError:
return [line]
return [t for t in tokens if not (len(t) == 2 and t.startswith("%"))]
def _parse_desktop(path):
cp = ConfigParser(interpolation=None, strict=False)
try:
cp.read(path, encoding="utf-8")
except Exception:
return None
if not cp.has_section("Desktop Entry"):
return None
s = cp["Desktop Entry"]
if s.get("Type", "").strip() != "Application":
return None
if s.get("NoDisplay", "false").lower() == "true":
return None
if s.get("Hidden", "false").lower() == "true":
return None
name = s.get("Name", "").strip() or path.stem
command = _clean_exec(s.get("Exec", ""))
if not command:
return None
wmclass = s.get("StartupWMClass", "").strip()
icon = s.get("Icon", "").strip()
return {"name": name, "command": command, "wmclass": wmclass,
"desktop_id": path.stem, "icon": icon}
def load_desktop_apps():
"""Return sorted list of {name, command, wmclass, desktop_id}."""
by_id = {}
for d in DESKTOP_DIRS:
if not d.exists():
continue
for f in d.glob("*.desktop"):
entry = _parse_desktop(f)
if entry and entry["desktop_id"] not in by_id:
by_id[entry["desktop_id"]] = entry
return sorted(by_id.values(), key=lambda x: x["name"].lower())
# ---- Helpers -------------------------------------------------------------
def shortcut_int_to_text(n):
"""0 -> '(none)'; otherwise human-readable like 'Meta+T'."""
return QKeySequence(n).toString() if n else "(none)"
def keyseq_to_int(seq):
"""QKeySequence -> Qt-encoded int (just the first chord, or 0 if empty)."""
if seq.count() == 0:
return 0
return seq[0].toCombined()
def make_id(name, existing_ids):
"""Make a unique, slugified id from name. 'Firefox' -> 'firefox'."""
base = re.sub(r"[^a-z0-9]+", "-", name.lower()).strip("-") or "app"
if base not in existing_ids:
return base
i = 2
while f"{base}-{i}" in existing_ids:
i += 1
return f"{base}-{i}"
# ---- Edit dialog ---------------------------------------------------------
class EditDialog(QDialog):
"""Edit one app: name, command, resourceClasses, shortcut."""
def __init__(self, app, parent=None):
super().__init__(parent)
self.setWindowTitle("Edit app")
self.resize(520, 380)
self._app = dict(app) # working copy
form = QFormLayout()
self.name_edit = QLineEdit(app.get("name", ""))
form.addRow("Name:", self.name_edit)
self.command_edit = QLineEdit(" ".join(shlex.quote(c) for c in app.get("command", [])))
self.command_edit.setPlaceholderText("e.g. firefox, or 'foot -e tmux'")
form.addRow("Command:", self.command_edit)
self.classes_edit = QPlainTextEdit("\n".join(app.get("resourceClasses", [])))
self.classes_edit.setPlaceholderText(
"One window class per line. Click 'Pick from window…' to grab "
"the class from a running window."
)
# Stack the textarea and the picker button vertically.
classes_box = QWidget()
cl = QVBoxLayout(classes_box)
cl.setContentsMargins(0, 0, 0, 0)
cl.addWidget(self.classes_edit)
self._pick_btn = QPushButton("Pick from window…")
self._pick_btn.setToolTip(
"Ask KWin to let you click on a running window. Its resourceClass "
"and resourceName will be appended to the list above."
)
self._pick_btn.clicked.connect(self._on_pick_window)
self._pick_proc = None # QProcess instance while a pick is in flight
btn_row = QHBoxLayout()
btn_row.addWidget(self._pick_btn)
btn_row.addStretch()
cl.addLayout(btn_row)
form.addRow("Window classes:", classes_box)
self.shortcut_edit = QKeySequenceEdit(QKeySequence(app.get("shortcut", 0)))
# Limit to single chord — multi-step Emacs-style shortcuts aren't
# supported by kglobalaccel anyway.
self.shortcut_edit.setMaximumSequenceLength(1)
clear_btn = QPushButton("Clear")
clear_btn.clicked.connect(self.shortcut_edit.clear)
sc_row = QHBoxLayout()
sc_row.addWidget(self.shortcut_edit, 1)
sc_row.addWidget(clear_btn)
form.addRow("Shortcut:", sc_row)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
buttons.accepted.connect(self._on_ok)
buttons.rejected.connect(self.reject)
v = QVBoxLayout(self)
v.addLayout(form)
v.addWidget(buttons)
def _on_pick_window(self):
# Already in flight? Don't start a second one.
if self._pick_proc is not None and self._pick_proc.state() != QProcess.ProcessState.NotRunning:
return
self._pick_btn.setEnabled(False)
self._pick_btn.setText("Click any window…")
self._pick_proc = QProcess(self)
self._pick_proc.finished.connect(self._on_pick_done)
# QProcess runs async — Qt's event loop keeps running, so the dialog
# stays alive and the user can click any window (KWin's queryWindowInfo
# cursor captures it globally).
self._pick_proc.start(
QDBUS,
["org.kde.KWin", "/KWin", "org.kde.KWin.queryWindowInfo"],
)
def _on_pick_done(self, exit_code, _exit_status):
self._pick_btn.setEnabled(True)
self._pick_btn.setText("Pick from window…")
if exit_code != 0 or self._pick_proc is None:
self._pick_proc = None
return
text = bytes(self._pick_proc.readAllStandardOutput()).decode(
"utf-8", errors="replace"
)
self._pick_proc = None
info = parse_window_info(text)
candidates = []
for key in ("resourceClass", "resourceName"):
v = info.get(key, "")
if v and v not in candidates:
candidates.append(v)
if not candidates:
return
existing = {
line.strip()
for line in self.classes_edit.toPlainText().splitlines()
if line.strip()
}
new = [c for c in candidates if c not in existing]
if not new:
return
body = self.classes_edit.toPlainText().rstrip()
if body:
body += "\n"
body += "\n".join(new)
self.classes_edit.setPlainText(body)
def _on_ok(self):
name = self.name_edit.text().strip()
if not name:
QMessageBox.warning(self, "kjump", "Name is required.")
return
try:
command = shlex.split(self.command_edit.text())
except ValueError as e:
QMessageBox.warning(self, "kjump", f"Bad command line: {e}")
return
if not command:
QMessageBox.warning(self, "kjump", "Command is required.")
return
classes = [
line.strip()
for line in self.classes_edit.toPlainText().splitlines()
if line.strip()
]
if not classes:
QMessageBox.warning(self, "kjump",
"At least one window class is required.")
return
self._app["name"] = name
self._app["command"] = command
self._app["resourceClasses"] = classes
self._app["shortcut"] = keyseq_to_int(self.shortcut_edit.keySequence())
self.accept()
def app(self):
return self._app
# ---- Desktop picker dialog ----------------------------------------------
class DesktopPicker(QDialog):
"""Choose one app from the .desktop database, with a filter."""
def __init__(self, parent=None):
super().__init__(parent)
self.setWindowTitle("Add app — pick from installed applications")
self.resize(480, 520)
self._all = load_desktop_apps()
self._chosen = None
v = QVBoxLayout(self)
self.filter_edit = QLineEdit()
self.filter_edit.setPlaceholderText("Filter…")
self.filter_edit.textChanged.connect(self._refilter)
v.addWidget(self.filter_edit)
self.list = QListWidget()
self.list.itemDoubleClicked.connect(lambda _: self._on_ok())
v.addWidget(self.list, 1)
buttons = QDialogButtonBox(
QDialogButtonBox.StandardButton.Ok | QDialogButtonBox.StandardButton.Cancel
)
buttons.accepted.connect(self._on_ok)
buttons.rejected.connect(self.reject)
v.addWidget(buttons)
self._refilter("")
def _refilter(self, text):
text = text.lower()
self.list.clear()
for entry in self._all:
if text and text not in entry["name"].lower():
continue
label = entry["name"]
if entry["wmclass"]:
label += f" ({entry['wmclass']})"
self.list.addItem(QListWidgetItem(get_icon(entry["icon"]), label))
if self.list.count() and not self.list.currentItem():
self.list.setCurrentRow(0)
def _on_ok(self):
row = self.list.currentRow()
if row < 0:
return
# map back from filtered list to the actual entry
text = self.filter_edit.text().lower()
visible = [e for e in self._all if not text or text in e["name"].lower()]
self._chosen = visible[row]
self.accept()
def chosen(self):
return self._chosen
# ---- Main window --------------------------------------------------------
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle("kjump configuration")
self.resize(720, 520)
self.apps = load_apps()
# Build a lookup so old apps.json entries (no "icon" field) can still
# show an icon: match by app["id"] -> .desktop file with the same stem.
self._desktop_by_id = {e["desktop_id"]: e for e in load_desktop_apps()}
self._dirty = False
self._build_ui()
self._refresh_table()
self._refresh_status()
def _build_ui(self):
central = QWidget()
self.setCentralWidget(central)
v = QVBoxLayout(central)
# Daemon status banner across the top.
self.status_banner = QLabel("")
self.status_banner.setContentsMargins(6, 4, 6, 4)
v.addWidget(self.status_banner)
self.table = QTableWidget(0, 3)
self.table.setHorizontalHeaderLabels(["Name", "Shortcut", "Command"])
self.table.horizontalHeader().setSectionResizeMode(
2, QHeaderView.ResizeMode.Stretch
)
self.table.setSelectionBehavior(
QAbstractItemView.SelectionBehavior.SelectRows
)
self.table.setSelectionMode(
QAbstractItemView.SelectionMode.SingleSelection
)
self.table.setEditTriggers(
QAbstractItemView.EditTrigger.NoEditTriggers
)
self.table.doubleClicked.connect(self._on_edit)
v.addWidget(self.table, 1)
h = QHBoxLayout()
for label, slot in [
("Add…", self._on_add),
("Edit…", self._on_edit),
("Remove", self._on_remove),
]:
b = QPushButton(label)
b.clicked.connect(slot)
h.addWidget(b)
h.addStretch()
save = QPushButton("Save && Apply")
save.setDefault(True)
save.clicked.connect(self._on_save)
h.addWidget(save)
v.addLayout(h)
def _app_icon(self, app):
"""Resolve an icon for one app — prefer app['icon'], else look up
a .desktop entry whose filename stem matches app['id']."""
icon_name = app.get("icon")
if not icon_name:
entry = self._desktop_by_id.get(app.get("id", ""))
if entry:
icon_name = entry.get("icon", "")
return get_icon(icon_name)
def _conflict_map(self):
"""{shortcut_int: [app_id, ...]} for shortcuts shared by 2+ kjump apps."""
owners = {}
for app in self.apps:
s = int(app.get("shortcut", 0))
if s:
owners.setdefault(s, []).append(app["id"])
return {s: ids for s, ids in owners.items() if len(ids) > 1}
def _refresh_table(self):
conflicts = self._conflict_map()
red = QBrush(QColor("#c0392b"))
# Display sorted by name (case-insensitive); the underlying
# self.apps list keeps user/insertion order so apps.json on disk
# doesn't churn just because the GUI sorts differently.
sorted_apps = sorted(
self.apps, key=lambda a: a.get("name", "").lower()
)
self.table.setRowCount(len(sorted_apps))
for row, app in enumerate(sorted_apps):
shortcut = int(app.get("shortcut", 0))
cells = [
app.get("name", ""),
shortcut_int_to_text(shortcut),
" ".join(app.get("command", [])),
]
for col, val in enumerate(cells):
item = QTableWidgetItem(val)
item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable)
if col == 0:
item.setIcon(self._app_icon(app))
# Stash the app id on column 0 so action handlers can
# find the right entry in self.apps regardless of sort.
item.setData(Qt.ItemDataRole.UserRole, app["id"])
if col == 1 and shortcut in conflicts:
others = [x for x in conflicts[shortcut] if x != app["id"]]
item.setForeground(red)
item.setToolTip(f"Conflicts with: {', '.join(others)}")
self.table.setItem(row, col, item)
def _mark_dirty(self):
if self._dirty:
return
self._dirty = True
self.setWindowTitle("kjump configuration *")
def _mark_clean(self):
self._dirty = False
self.setWindowTitle("kjump configuration")
def _refresh_status(self):
if daemon_running():
self.status_banner.setText("Daemon: running ✓")
self.status_banner.setStyleSheet(
"background:#27ae60; color:white; border-radius:3px;"
)
else:
self.status_banner.setText(
"Daemon: not running — start it with "
"<code>systemctl --user start kjumpd</code>"
)
self.status_banner.setStyleSheet(
"background:#c0392b; color:white; border-radius:3px;"
)
def _select_by_id(self, app_id):
"""Select the row whose UserRole id matches app_id (post-sort)."""
for row in range(self.table.rowCount()):
item = self.table.item(row, 0)
if item and item.data(Qt.ItemDataRole.UserRole) == app_id:
self.table.selectRow(row)
return
def _selected_index(self):
"""Index into self.apps for the currently selected row, or -1.
Looks up by app id stashed in the row's UserRole so it survives
the display being sorted differently from self.apps' order."""
rows = self.table.selectionModel().selectedRows()
if not rows:
return -1
item = self.table.item(rows[0].row(), 0)
if item is None:
return -1
aid = item.data(Qt.ItemDataRole.UserRole)
for i, a in enumerate(self.apps):
if a["id"] == aid:
return i
return -1
# -- actions --
def _on_add(self):
picker = DesktopPicker(self)
if picker.exec() != QDialog.DialogCode.Accepted:
return
chosen = picker.chosen()
existing_ids = {a["id"] for a in self.apps}
# Seed window classes with every plausible hint. Different apps
# report different things as resourceClass on Wayland vs X11; the
# user can prune in the Edit dialog if any are wrong.
# - StartupWMClass (when the .desktop sets it)
# - the .desktop file id, e.g. "org.mozilla.firefox" — this is
# the Wayland app_id for many native-Wayland apps and is what
# KWin reports as resourceClass for them
# - the exec basename (e.g. "firefox") — matches X11/XWayland
classes = []
for cand in (chosen.get("wmclass", ""), chosen.get("desktop_id", "")):
if cand and cand not in classes:
classes.append(cand)
if chosen["command"]:
exec_basename = Path(chosen["command"][0]).name
if exec_basename and exec_basename not in classes:
classes.append(exec_basename)
new_app = {
"id": make_id(chosen["desktop_id"], existing_ids),
"name": chosen["name"],
"command": chosen["command"],
"resourceClasses": classes,
"shortcut": 0,
"icon": chosen.get("icon", ""),
}
# Open Edit so user can confirm/tweak (especially window classes
# if StartupWMClass was missing) and pick a shortcut.
dlg = EditDialog(new_app, self)
if dlg.exec() != QDialog.DialogCode.Accepted:
return
new_app = dlg.app()
self.apps.append(new_app)
self._mark_dirty()
self._refresh_table()
self._select_by_id(new_app["id"])
def _on_edit(self):
idx = self._selected_index()
if idx < 0:
return
before = dict(self.apps[idx])
dlg = EditDialog(self.apps[idx], self)
if dlg.exec() != QDialog.DialogCode.Accepted:
return
after = dlg.app()
self.apps[idx] = after
if before != after:
self._mark_dirty()
self._refresh_table()
self._select_by_id(after["id"])
def _on_remove(self):
idx = self._selected_index()
if idx < 0:
return
name = self.apps[idx].get("name", "?")
reply = QMessageBox.question(
self, "kjump",
f"Remove {name!r}?",
)
if reply != QMessageBox.StandardButton.Yes:
return
del self.apps[idx]
self._mark_dirty()
self._refresh_table()
def _on_save(self):
# Warn (but don't block) if there are conflicting shortcuts within kjump.
conflicts = self._conflict_map()
if conflicts:
descs = []
for s, ids in conflicts.items():
descs.append(f" {shortcut_int_to_text(s)}: {', '.join(ids)}")
reply = QMessageBox.warning(
self, "kjump",
"Two or more apps share the same shortcut:\n\n"
+ "\n".join(descs)
+ "\n\nOnly one will fire when pressed. Save anyway?",
QMessageBox.StandardButton.Save | QMessageBox.StandardButton.Cancel,
)
if reply != QMessageBox.StandardButton.Save:
return
try:
save_apps(self.apps)
except OSError as e:
QMessageBox.critical(self, "kjump", f"Could not save: {e}")
return
self._mark_clean()
ok, err = reload_daemon()
self._refresh_status()
if ok:
self.statusBar().showMessage("Saved and reloaded.", 4000)
else:
self.statusBar().showMessage("Saved (daemon unreachable).", 4000)
QMessageBox.warning(
self, "kjump",
f"apps.json saved, but couldn't reach the daemon. "
f"Is kjumpd running?\n\n{err}"
)
def closeEvent(self, event):
if not self._dirty:
event.accept()
return
reply = QMessageBox.question(
self, "kjump",
"You have unsaved changes. Save before closing?",
QMessageBox.StandardButton.Save
| QMessageBox.StandardButton.Discard
| QMessageBox.StandardButton.Cancel,
)
if reply == QMessageBox.StandardButton.Save:
self._on_save()
# If save bailed (conflict cancel, IO error), stay open.
if self._dirty:
event.ignore()
return
event.accept()
elif reply == QMessageBox.StandardButton.Discard:
event.accept()
else:
event.ignore()
# ---- Entry point --------------------------------------------------------
def main():
# Answer --version before spinning up Qt, so it works without a display.
if "--version" in sys.argv or "-V" in sys.argv:
print(f"kjump-config {__version__}")
sys.exit(0)
app = QApplication(sys.argv)
app.setApplicationName("kjump-config")
win = MainWindow()
win.show()
sys.exit(app.exec())
if __name__ == "__main__":
main()