-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
hud.py
312 lines (255 loc) · 10.4 KB
/
hud.py
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
#!/usr/bin/env python3
"""
This script displays a window containing given icon and text, a closes it on timeout.
Repository: https://github.com/nwg-piotr/nwg-shell-config
Project site: https://nwg-piotr.github.io/nwg-shell
Author's email: [email protected]
Copyright (c) 2024 Piotr Miller
License: MIT
"""
import argparse
import json
import os
import subprocess
import sys
import gi
gi.require_version('Gtk', '3.0')
try:
gi.require_version('GtkLayerShell', '0.1')
except ValueError:
raise RuntimeError('\n\n' +
'If you haven\'t installed GTK Layer Shell, you need to point Python to the\n' +
'library by setting GI_TYPELIB_PATH and LD_LIBRARY_PATH to <build-dir>/src/.\n' +
'For example you might need to run:\n\n' +
'GI_TYPELIB_PATH=build/src LD_LIBRARY_PATH=build/src python3 ' + ' '.join(sys.argv))
from gi.repository import Gtk, Gdk, GLib, GdkPixbuf, GtkLayerShell
from shutil import copy2
from psutil import process_iter
from nwg_shell_config.tools import get_config_home, load_json, eprint
config_home = get_config_home()
config_dir = os.path.join(config_home, 'nwg-hud')
dir_name = os.path.dirname(__file__)
settings = None
args = None
def handle_keyboard(win, event):
if event.type == Gdk.EventType.KEY_RELEASE:
if event.keyval == Gdk.KEY_Escape:
Gtk.main_quit()
def create_pixbuf(icon_name, icon_size):
# In case a full path was given
if icon_name.startswith("/"):
pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_size(
icon_name, icon_size, icon_size)
else:
icon_theme = Gtk.IconTheme.get_default()
try:
pixbuf = icon_theme.load_icon(icon_name, icon_size, Gtk.IconLookupFlags.FORCE_SIZE)
except:
pixbuf = icon_theme.load_icon("image-missing", icon_size, Gtk.IconLookupFlags.FORCE_SIZE)
return pixbuf
def update_image(image, icon_name, icon_size):
scale = image.get_scale_factor()
icon_size *= scale
pixbuf = create_pixbuf(icon_name, icon_size)
surface = Gdk.cairo_surface_create_from_pixbuf(pixbuf, scale, image.get_window())
image.set_from_surface(surface)
def list_outputs():
outputs_dict = {}
if os.getenv("SWAYSOCK"):
try:
from i3ipc import Connection
except ModuleNotFoundError:
print("'python-i3ipc' package required on sway, terminating")
sys.exit(1)
i3 = Connection()
outputs = i3.get_outputs()
for item in outputs:
outputs_dict[item.name] = {"description": f"{item.make} {item.model} {item.serial}",
"monitor": None}
elif os.getenv('HYPRLAND_INSTANCE_SIGNATURE') is not None:
cmd = "hyprctl -j monitors"
result = subprocess.check_output(cmd, shell=True).decode("utf-8").strip()
outputs = json.loads(result)
for item in outputs:
outputs_dict[item["name"]] = {"description": item["description"],
"monitor": None}
else:
eprint("nwg-hud script only works on sway or Hyprland, terminating")
sys.exit(1)
monitors = []
display = Gdk.Display.get_default()
for i in range(display.get_n_monitors()):
monitor = display.get_monitor(i)
monitors.append(monitor)
for key, monitor in zip(outputs_dict.keys(), monitors):
outputs_dict[key]["monitor"] = monitor
# map monitor descriptions to output names
mon_desc2output_name = {}
for key in outputs_dict:
if "description" in outputs_dict[key]:
mon_desc2output_name[outputs_dict[key]["description"]] = key
return outputs_dict, mon_desc2output_name
def main():
# disallow multiple instances
for proc in process_iter():
if "nwg-hud" in proc.name() and proc.pid != os.getpid():
eprint(f"nwg-hud: running instance found, PID {proc.pid}, terminating")
sys.exit(1)
# initiate config files if not found
if not os.path.isdir(config_dir):
os.mkdir(config_dir)
for filename in ["config.json", "style.css"]:
file_path = os.path.join(config_dir, filename)
if not os.path.isfile(os.path.join(config_dir, filename)):
copy2(os.path.join(dir_name, "hud", filename), file_path)
# load settings
global settings
settings = load_json(os.path.join(config_dir, "config.json"))
parser = argparse.ArgumentParser()
parser.add_argument("-i",
"--icon",
type=str,
default="",
help='Icon name or path')
parser.add_argument("-z",
"--icon_size",
type=int,
default=48,
help="icon size")
parser.add_argument("-m",
"--message",
type=str,
default="HUD message",
help='Message text to display')
parser.add_argument("-t",
"--timeout",
type=int,
default=1000,
help="window Timeout in milliseconds")
parser.add_argument("-ha",
"--horizontal_alignment",
type=str,
default="center",
help="window Horizontal Alignment: 'left' or 'right', 'center' by default")
parser.add_argument("-va",
"--vertical_alignment",
type=str,
default="center",
help="window Vertical Alignment: 'top' or 'bottom', 'center' by default")
parser.add_argument("-r",
"--margin",
type=int,
default=0,
help="window margin in pixels")
parser.add_argument("-o",
"--output",
type=str,
default="",
help="name of the Output to display HUD on")
parser.add_argument("-d",
"--debug",
action="store_true",
help="print debug messages to stderr")
parser.parse_args()
global args
args = parser.parse_args()
# arguments override settings, if given
if args.icon:
settings["icon"] = args.icon
if args.icon_size not in [0, 48]:
settings["icon_size"] = args.icon_size
if args.message:
settings["message"] = args.message
if args.timeout not in [0, 1000]:
try:
settings["timeout"] = int(args.timeout)
except Exception as e:
eprint(e)
if args.horizontal_alignment != "center":
settings["horizontal-alignment"] = args.horizontal_alignment
if args.vertical_alignment != "center":
settings["vertical-alignment"] = args.vertical_alignment
if args.margin:
try:
settings["margin"] = int(args.margin)
except Exception as e:
eprint(e)
if args.output:
settings["output"] = args.output
# make sure we have all values
defaults = {
"icon": "",
"icon-size": 48,
"message": "",
"timeout": 1000,
"horizontal-alignment": "",
"vertical-alignment": "",
"margin": 0,
"output": ""
}
for key in defaults:
if key not in settings:
settings[key] = defaults[key]
window = Gtk.Window.new(Gtk.WindowType.POPUP)
GtkLayerShell.init_for_window(window)
GtkLayerShell.set_layer(window, GtkLayerShell.Layer.TOP)
GtkLayerShell.set_exclusive_zone(window, 0)
GtkLayerShell.set_keyboard_mode(window, GtkLayerShell.KeyboardMode.ON_DEMAND)
GtkLayerShell.set_namespace(window, "nwg-hud")
if settings["vertical-alignment"] == "top":
GtkLayerShell.set_anchor(window, GtkLayerShell.Edge.TOP, 1)
elif settings["vertical-alignment"] == "bottom":
GtkLayerShell.set_anchor(window, GtkLayerShell.Edge.BOTTOM, 1)
if settings["horizontal-alignment"] == "left":
GtkLayerShell.set_anchor(window, GtkLayerShell.Edge.LEFT, 1)
elif settings["horizontal-alignment"] == "right":
GtkLayerShell.set_anchor(window, GtkLayerShell.Edge.RIGHT, 1)
if settings["margin"] > 0:
GtkLayerShell.set_margin(window, GtkLayerShell.Edge.TOP, settings["margin"])
GtkLayerShell.set_margin(window, GtkLayerShell.Edge.BOTTOM, settings["margin"])
GtkLayerShell.set_margin(window, GtkLayerShell.Edge.LEFT, settings["margin"])
GtkLayerShell.set_margin(window, GtkLayerShell.Edge.RIGHT, settings["margin"])
# assign to a monitor if output name or monitor description given
if settings["output"]:
outputs, mon_desc2output_name = list_outputs()
monitor = None
if settings["output"] in outputs and "monitor" in outputs[settings["output"]]:
monitor = outputs[settings["output"]]["monitor"]
elif settings["output"] in mon_desc2output_name:
name = mon_desc2output_name[settings["output"]]
monitor = outputs[name]["monitor"]
else:
eprint(f"Couldn't assign monitor to {settings['output']}")
if monitor:
GtkLayerShell.set_monitor(window, monitor)
window.connect('destroy', Gtk.main_quit)
window.connect("key-release-event", handle_keyboard)
vbox = Gtk.Box.new(Gtk.Orientation.VERTICAL, 0)
vbox.set_property("margin", 0)
window.add(vbox)
hbox = Gtk.Box.new(Gtk.Orientation.HORIZONTAL, 12)
hbox.set_property("margin", 12)
vbox.pack_start(hbox, False, False, 0)
if args.icon:
img = Gtk.Image()
update_image(img, settings["icon"], settings["icon-size"])
hbox.pack_start(img, False, False, 0)
lbl = Gtk.Label()
lbl.set_markup(settings["message"])
hbox.pack_start(lbl, True, True, 0)
# apply styling
screen = Gdk.Screen.get_default()
provider = Gtk.CssProvider()
style_context = Gtk.StyleContext()
style_context.add_provider_for_screen(screen, provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION)
try:
provider.load_from_path(os.path.join(dir_name, "hud", "style.css"))
except Exception as e:
eprint(e)
css = provider.to_string().encode('utf-8')
provider.load_from_data(css)
window.show_all()
GLib.timeout_add(settings["timeout"], Gtk.main_quit)
Gtk.main()
if __name__ == "__main__":
main()