pingerplot 1.6.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.
pingerplot/xdg.py ADDED
@@ -0,0 +1,198 @@
1
+ """Linux desktop integration through freedesktop.org conventions: alert
2
+ notifications with notify-send, an entry in the applications menu, and
3
+ starting at sign-in (an XDG autostart entry).
4
+
5
+ Windows gets these from tray.py and winplatform.py; Linux has no
6
+ notification-area API Tk can reach without a third-party module, but nearly
7
+ every desktop ships notify-send (libnotify), which speaks the freedesktop
8
+ notification spec to GNOME, KDE Plasma, XFCE, Cinnamon and the rest, and
9
+ every one of them reads .desktop files.
10
+ """
11
+ from __future__ import annotations
12
+
13
+ import logging
14
+ import os
15
+ import shutil
16
+ import subprocess
17
+ import sys
18
+ from pathlib import Path
19
+ from typing import Optional
20
+
21
+ log = logging.getLogger("pingerplot.xdg")
22
+
23
+ IS_LINUX = sys.platform.startswith("linux")
24
+
25
+
26
+ def cache_dir() -> Path:
27
+ return Path(os.environ.get("XDG_CACHE_HOME") or Path.home() / ".cache") / "PingerPlot"
28
+
29
+
30
+ def icon_file(size: int = 128) -> Optional[Path]:
31
+ """The app's icon as a PNG on disk (drawn by appicon), for notifications
32
+ to show; written once to the cache folder. None if it can't be."""
33
+ from . import appicon
34
+ path = cache_dir() / f"pingerplot-{size}.png"
35
+ try:
36
+ if not path.is_file():
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ path.write_bytes(appicon.png_bytes(size))
39
+ return path
40
+ except OSError:
41
+ return None
42
+
43
+
44
+ class Notifier:
45
+ """notify(title, text, on_click=None): a desktop notification. It shows
46
+ and goes; a click does nothing (notify-send can only report one by
47
+ blocking until the notification is dismissed)."""
48
+
49
+ can_click = False
50
+
51
+ def __init__(self, exe: str, icon: Optional[Path] = None) -> None:
52
+ self.exe, self.icon = exe, icon
53
+
54
+ def notify(self, title: str, text: str, on_click=None, sound: bool = False) -> None:
55
+ args = [self.exe, "--app-name=PingerPlot"]
56
+ if self.icon is not None:
57
+ args.append(f"--icon={self.icon}")
58
+ args += ["--", title, text]
59
+ try:
60
+ # Not waited for: a notification daemon that's slow to answer
61
+ # mustn't hold up the window.
62
+ subprocess.Popen(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL,
63
+ stderr=subprocess.DEVNULL, close_fds=True, start_new_session=True)
64
+ except OSError as e:
65
+ log.warning("notify-send failed: %s", e)
66
+
67
+
68
+ def notifier() -> Optional[Notifier]:
69
+ """A Notifier on a Linux desktop with notify-send, else None."""
70
+ if not IS_LINUX:
71
+ return None
72
+ exe = shutil.which("notify-send")
73
+ return Notifier(exe, icon_file()) if exe else None
74
+
75
+
76
+ # --- the applications menu and starting at sign-in ---------------------------------
77
+
78
+ APP_FILE = "pingerplot.desktop"
79
+ WM_CLASS = "PingerPlot" # gui.main() names the Tk root this; StartupWMClass matches it
80
+
81
+
82
+ def data_home() -> Path:
83
+ return Path(os.environ.get("XDG_DATA_HOME") or Path.home() / ".local" / "share")
84
+
85
+
86
+ def config_home() -> Path:
87
+ return Path(os.environ.get("XDG_CONFIG_HOME") or Path.home() / ".config")
88
+
89
+
90
+ def menu_entry_path() -> Path:
91
+ return data_home() / "applications" / APP_FILE
92
+
93
+
94
+ def autostart_path() -> Path:
95
+ return config_home() / "autostart" / APP_FILE
96
+
97
+
98
+ def launch_args() -> list:
99
+ """How a desktop entry starts this copy (it runs in $HOME, so a relative
100
+ path or ``-m`` from a checkout wouldn't): the main.py beside the package
101
+ in a git checkout, else ``python -m pingerplot`` for a pip or pipx
102
+ install, whose interpreter can import it from anywhere."""
103
+ script = Path(__file__).resolve().parent.parent / "main.py"
104
+ if script.is_file():
105
+ return [sys.executable, str(script)]
106
+ return [sys.executable, "-m", "pingerplot"]
107
+
108
+
109
+ def _exec_quote(arg: str) -> str:
110
+ """One argument of a desktop entry's Exec key (Desktop Entry spec,
111
+ "The Exec key"): quoted when it has to be, with the characters that are
112
+ special inside quotes escaped, and % doubled.
113
+
114
+ Two levels: the value is first unescaped as a string (two backslashes
115
+ make one), then as quoting (a backslash before a double quote, backtick,
116
+ dollar sign or backslash). So the quoting's backslashes are doubled once
117
+ more: a literal $ inside quotes is two backslashes and the $ in the file,
118
+ a literal backslash four. Writing only the quoting level left one
119
+ backslash before the $, which a reader takes as an unknown string
120
+ escape."""
121
+ arg = arg.replace("%", "%%")
122
+ if arg and not any(c in arg for c in ' \t\n"\'\\><~|&;$*?#()`'):
123
+ return arg
124
+ quoted = '"' + "".join("\\" + c if c in '"`$\\' else c for c in arg) + '"'
125
+ return quoted.replace("\\", "\\\\")
126
+
127
+
128
+ def exec_line(extra=()) -> str:
129
+ return " ".join(_exec_quote(str(a)) for a in [*launch_args(), *extra])
130
+
131
+
132
+ def _entry(extra=(), autostart: bool = False) -> str:
133
+ icon = icon_file(256)
134
+ lines = ["[Desktop Entry]", "Type=Application", "Name=PingerPlot",
135
+ "GenericName=Network path monitor",
136
+ "Comment=Continuous traceroute: per-hop loss, latency, jitter and MOS over time",
137
+ f"Exec={exec_line(extra)}", "Terminal=false",
138
+ "Categories=Network;Monitor;Utility;",
139
+ "Keywords=traceroute;ping;mtr;latency;packet loss;jitter;",
140
+ f"StartupWMClass={WM_CLASS}"]
141
+ if icon is not None:
142
+ lines.append(f"Icon={icon}")
143
+ if autostart:
144
+ lines.append("X-GNOME-Autostart-enabled=true")
145
+ return "\n".join(lines) + "\n"
146
+
147
+
148
+ def _write(path: Path, text: str) -> bool:
149
+ try:
150
+ path.parent.mkdir(parents=True, exist_ok=True)
151
+ if not (path.is_file() and path.read_text(encoding="utf-8") == text):
152
+ path.write_text(text, encoding="utf-8")
153
+ return True
154
+ except OSError as e:
155
+ log.warning("couldn't write %s: %s", path, e)
156
+ return False
157
+
158
+
159
+ def _remove(path: Path) -> bool:
160
+ try:
161
+ path.unlink(missing_ok=True)
162
+ return True
163
+ except OSError as e:
164
+ log.warning("couldn't remove %s: %s", path, e)
165
+ return False
166
+
167
+
168
+ def menu_entry_enabled() -> bool:
169
+ return IS_LINUX and menu_entry_path().is_file()
170
+
171
+
172
+ def set_menu_entry(enabled: bool) -> bool:
173
+ if not IS_LINUX:
174
+ return False
175
+ return _write(menu_entry_path(), _entry()) if enabled else _remove(menu_entry_path())
176
+
177
+
178
+ def autostart_enabled() -> bool:
179
+ return IS_LINUX and autostart_path().is_file()
180
+
181
+
182
+ def set_autostart(enabled: bool) -> bool:
183
+ """Start minimized at sign-in, resuming the last targets (--minimized,
184
+ as Windows' Run entry), or stop doing so."""
185
+ if not IS_LINUX:
186
+ return False
187
+ if enabled:
188
+ return _write(autostart_path(), _entry(["--minimized"], autostart=True))
189
+ return _remove(autostart_path())
190
+
191
+
192
+ def refresh_entries() -> None:
193
+ """Point existing entries at this copy, if it has moved (a new checkout
194
+ folder, a different virtualenv)."""
195
+ if menu_entry_enabled():
196
+ set_menu_entry(True)
197
+ if autostart_enabled():
198
+ set_autostart(True)