-
Notifications
You must be signed in to change notification settings - Fork 21
/
xborders
executable file
·469 lines (402 loc) · 16 KB
/
xborders
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
#!/bin/python3
import argparse
import json
import os
import subprocess
import sys
import threading
import webbrowser
import cairo
import gi
import requests
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
gi.require_version("Wnck", "3.0")
gi.require_version("GObject", "2.0")
from gi.repository import Gtk, Gdk, Wnck, GObject
VERSION = 3.4
INSIDE = 'inside'
OUTSIDE = 'outside'
CENTER = 'center'
BORDER_MODES = [INSIDE, OUTSIDE, CENTER]
BORDER_MODE = INSIDE
BORDER_RADIUS = 14
BORDER_WIDTH = 4
BORDER_R = 123
BORDER_G = 88
BORDER_B = 220
BORDER_A = 1
SMART_HIDE_BORDER = False
NO_VERSION_NOTIFY = False
OFFSETS = [0, 0, 0, 0]
def set_border_rgba(args):
try:
literal_value = int(args.border_rgba.replace("#", "0x"), 16)
except:
raise ValueError(f"`{args.border_rgba}` is an invalid hexadecimal number!")
if len(args.border_rgba) == 4*2+1:
args.border_red = literal_value >> (3 * 8) & 0xFF
args.border_green = literal_value >> (2 * 8) & 0xFF
args.border_blue = literal_value >> (1 * 8) & 0xFF
args.border_alpha = (literal_value >> (0 * 8) & 0xFF) / 255 # map from 0 to 1
elif len(args.border_rgba) == 3*2+1:
args.border_red = literal_value >> (2 * 8) & 0xFF
args.border_green = literal_value >> (1 * 8) & 0xFF
args.border_blue = literal_value >> (0 * 8) & 0xFF
args.border_alpha = 1.0
else:
raise ValueError(f"`{args.border_rgba}` is an invalid hexadecimal color string.")
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument(
"--config", "-c",
type=str,
help="The path to the config file"
)
parser.add_argument(
"--border-radius",
type=int,
default=14,
help="The border radius, in pixels"
)
parser.add_argument(
"--border-width",
type=int,
default=4,
help="The border width in pixels"
)
parser.add_argument(
"--border-red",
type=int,
default=123,
help="The border's red value, between 0 and 255",
)
parser.add_argument(
"--border-green",
type=int,
default=88,
help="The border's green value, between 0 and 255",
)
parser.add_argument(
"--border-blue",
type=int,
default=220,
help="The border's blue value, between 0 and 255",
)
parser.add_argument(
"--border-alpha",
type=float,
default=1,
help="The border's alpha value, between zero and 1",
)
parser.add_argument(
"--border-rgba",
default=None,
help="The colours of the border in hex format, example: #FF0000FF",
)
parser.add_argument(
"--border-mode",
type=str,
default="outside",
help="Whether to place the border on the outside, inside or in the center of windows. Values are `outside`, `inside`, `center`"
)
parser.add_argument(
"--smart-hide-border",
action='store_true',
help="Don't display a border if the window is alone in the workspace."
)
parser.add_argument(
"--disable-version-warning",
action='store_true',
help="Send a notification if xborders is out of date."
)
parser.add_argument(
"--positive-x-offset",
default=0,
type=int,
help="How much to increase the windows size to the right."
)
parser.add_argument(
"--negative-x-offset",
default=0,
type=int,
help="How much to increase the windows size to the left."
)
parser.add_argument(
"--positive-y-offset",
default=0,
type=int,
help="How much to increase the windows size upwards."
)
parser.add_argument(
"--negative-y-offset",
default=0,
type=int,
help="How much to increase the windows size downwards."
)
parser.add_argument(
"--version",
action="store_true",
help="Print the version of xborders and exit."
)
args = parser.parse_args()
if args.version is True:
print(f"xborders v{VERSION}")
exit(0)
if args.border_rgba is not None:
set_border_rgba(args)
# Extract the literal values
if args.config is not None:
with open(args.config, "r") as f:
raw = f.read().replace("-", "_")
dat = json.loads(raw)
for ident in dat:
if ident == "border_rgba":
args.border_rgba = dat[ident]
set_border_rgba(args)
else:
args.__dict__[ident] = dat[
ident
] # Idea gotten from here: https://stackoverflow.com/a/1325798
global BORDER_RADIUS
global BORDER_WIDTH
global BORDER_MODE
global BORDER_R
global BORDER_G
global BORDER_B
global BORDER_A
global SMART_HIDE_BORDER
global NO_VERSION_NOTIFY
global OFFSETS
BORDER_RADIUS = args.border_radius
BORDER_WIDTH = args.border_width
BORDER_R = args.border_red
BORDER_G = args.border_green
BORDER_B = args.border_blue
BORDER_A = args.border_alpha
NO_VERSION_NOTIFY = args.disable_version_warning
SMART_HIDE_BORDER = args.smart_hide_border
OFFSETS = [
args.positive_x_offset or 0,
args.positive_y_offset or 0,
args.negative_x_offset or 0,
args.negative_y_offset or 0
]
if args.border_mode in BORDER_MODES:
BORDER_MODE = args.border_mode
else:
raise ValueError(
f"Invalid border_mode: '{args.border_mode}'. Valid border_modes are: inside, outside and center.")
return
def get_screen_size(display): # TODO: Multiple monitor size support
mon_geoms = [display.get_monitor(i).get_geometry() for i in range(display.get_n_monitors())]
x0 = min(r.x for r in mon_geoms)
y0 = min(r.y for r in mon_geoms)
x1 = max(r.x + r.width for r in mon_geoms)
y1 = max(r.y + r.height for r in mon_geoms)
return x1 - x0, y1 - y0
def notify_about_version(latest_version: float):
notification_string = f"xborders has an update! [{VERSION} 🡢 {latest_version}]"
completed_process = subprocess.run(
["notify-send", "--app-name=xborder", "--expire-time=5000", notification_string, "--action=How to Update?",
"--action=Ignore Update"],
capture_output=True
)
if completed_process.returncode == 0:
result_string = completed_process.stdout.decode("utf-8")
if result_string == '':
return
result = int(result_string)
if result == 1:
our_location = os.path.dirname(os.path.abspath(__file__))
file = open(our_location + "/.update_ignore.txt", "w")
file.write(str(latest_version))
file.close()
elif result == 0:
webbrowser.open_new_tab("https://github.com/deter0/xborder#updating")
else:
print("something went wrong in notify-send.")
def notify_version():
if NO_VERSION_NOTIFY:
return
try:
our_location = os.path.dirname(os.path.abspath(__file__))
url = "https://raw.githubusercontent.com/deter0/xborder/main/version.txt" # Maybe hardcoding it is a bad idea
request = requests.get(url, allow_redirects=True)
latest_version_string = request.content.decode("utf-8")
latest_version = float(latest_version_string)
if os.path.isfile(our_location + "/.update_ignore.txt"):
ignore_version_file = open(our_location + "/.update_ignore.txt", "r")
ignored_version_string = ignore_version_file.read()
ignored_version = float(ignored_version_string)
if ignored_version == latest_version:
return
if VERSION < latest_version:
threading._start_new_thread(notify_about_version, (latest_version))
except:
subprocess.Popen(["notify-send", "--app-name=xborders", "ERROR: xborders couldn't get latest version!"])
class Highlight(Gtk.Window):
def __init__(self, screen_width, screen_height):
super().__init__(type=Gtk.WindowType.POPUP)
notify_version()
self.wnck_screen = Wnck.Screen.get_default()
self.set_app_paintable(True)
self.screen = self.get_screen()
self.set_visual(self.screen.get_rgba_visual())
# As described here: https://docs.gtk.org/gtk3/method.Window.set_wmclass.html
# Picom blur exclusion would be:
# "role = 'xborder'",
self.set_role("xborder")
# We can still set this for old configurations, we don't want to update and have the user confused as to what
# has happened
self.set_wmclass("xborders", "xborder")
self.resize(screen_width, screen_height)
self.move(0, 0)
self.fullscreen()
self.set_decorated(False)
self.set_skip_taskbar_hint(True)
self.set_skip_pager_hint(True)
self.set_keep_above(True)
self.set_type_hint(Gdk.WindowTypeHint.NOTIFICATION)
self.set_accept_focus(False)
self.set_focus_on_map(False)
self.drawingarea = Gtk.DrawingArea()
self.drawingarea.set_events(Gdk.EventMask.EXPOSURE_MASK)
self.add(self.drawingarea)
self.input_shape_combine_region(cairo.Region())
self.set_keep_above(True)
self.set_title("xborders")
self.show_all()
self.border_path = [0, 0, 0, 0]
# Event connection:
self.connect("draw", self._draw)
self.connect("destroy", Gtk.main_quit)
self.connect('composited-changed', self._composited_changed_event)
self.wnck_screen.connect("active-window-changed", self._active_window_changed_event)
# Call initial events
self._composited_changed_event(None)
self._active_window_changed_event(None, None)
self._geometry_changed_event(None)
# This triggers every time the window composited state changes.
# https://docs.gtk.org/gtk3/signal.Widget.composited-changed.html
def _composited_changed_event(self, _arg):
if self.screen.is_composited():
self.move(0, 0)
else:
self.move(1e6, 1e6)
subprocess.Popen(["notify-send", "--app-name=xborder",
"xborders requires a compositor. Resuming once a compositor is running."])
# Avoid memory leaks
old_window = None
old_signals_to_disconnect = [None, None]
def is_alone_in_workspace(self):
workspace = Wnck.Screen.get_active_workspace(self.wnck_screen)
windows = Wnck.Screen.get_windows(self.wnck_screen)
windows_on_workspace = list(filter(lambda w: w.is_visible_on_workspace(workspace), windows))
return len(windows_on_workspace) == 1
# This event will trigger every active window change, it will queue a border to be drawn and then do nothing.
# See: Signals available for the Wnck.Screen class:
# https://lazka.github.io/pgi-docs/Wnck-3.0/classes/Screen.html#signals Signals available for the Wnck.Window
# class: https://lazka.github.io/pgi-docs/Wnck-3.0/classes/Window.html#signals
def _active_window_changed_event(self, _screen, _previous_active_window):
if self.old_window and len(self.old_signals_to_disconnect) > 0:
for sig_id in self.old_signals_to_disconnect:
GObject.signal_handler_disconnect(self.old_window, sig_id)
self.old_signals_to_disconnect = []
self.old_window = None
active_window = self.wnck_screen.get_active_window()
self.border_path = [0, 0, 0, 0]
if active_window is not None and not (SMART_HIDE_BORDER and self.is_alone_in_workspace()):
# Find if the window has a 'geometry-changed' event connected.
geom_signal_id = GObject.signal_lookup('geometry-changed', active_window)
state_signal_id = GObject.signal_lookup('state-changed', active_window)
geom_has_event_connected = GObject.signal_has_handler_pending(active_window, geom_signal_id, 0, False)
state_has_event_connected = GObject.signal_has_handler_pending(active_window, state_signal_id, 0, False)
# if it doesn't have one.
if not geom_has_event_connected:
# Connect it.
# Has to be done this way in order to not connect an event
# every time the active window changes, thus, drawing unnecesary frames.
sig_id = active_window.connect('geometry-changed', self._geometry_changed_event)
self.old_signals_to_disconnect.append(sig_id)
if not state_has_event_connected:
sig_id = active_window.connect('state-changed', self._state_changed_event)
self.old_signals_to_disconnect.append(sig_id)
self.old_window = active_window
self._calc_border_geometry(active_window)
self.queue_draw()
def _state_changed_event(self, active_window, _changed_mask, new_state):
if new_state & Wnck.WindowState.FULLSCREEN != 0:
self._calc_border_geometry(active_window)
self.queue_draw()
# This is weird, "_window_changed" is not necessarily the active window,
# it is the window which receives the signal of resizing and is not necessarily
# the active window, this means the border will get drawn on other windows.
def _geometry_changed_event(self, _window_changed):
active_window = self.wnck_screen.get_active_window()
if active_window is None or (active_window.get_state() & Wnck.WindowState.FULLSCREEN != 0):
self.border_path = [0, 0, 0, 0]
else:
self._calc_border_geometry(active_window)
self.queue_draw()
def _calc_border_geometry(self, window):
if (window.get_state() & Wnck.WindowState.FULLSCREEN != 0):
self.border_path = [0, 0, 0, 0]
return
# TODO(kay:) Find out why `get_geometry` works better than `get_client_window_geometry` on Gnome but for some windows it doesnt
x, y, w, h = window.get_client_window_geometry()
# Inside
if BORDER_MODE == INSIDE:
x += BORDER_WIDTH / 2
y += BORDER_WIDTH / 2
w -= BORDER_WIDTH
h -= BORDER_WIDTH
# Outside
elif BORDER_MODE == OUTSIDE:
x -= BORDER_WIDTH / 2
y -= BORDER_WIDTH / 2
w += BORDER_WIDTH
h += BORDER_WIDTH
# Offsets
w += OFFSETS[0] or 0
h += OFFSETS[1] or 0
x -= OFFSETS[2] or 0
w += OFFSETS[2] or 0
y -= OFFSETS[3] or 0
h += OFFSETS[3] or 0
# Center
self.border_path = [x, y, w, h]
def _draw(self, _wid, ctx):
ctx.save()
if self.border_path != [0, 0, 0, 0]:
x, y, w, h = self.border_path
if BORDER_WIDTH != 0:
if BORDER_RADIUS > 0:
degrees = 0.017453292519943295 # pi/180
ctx.arc(x + w - BORDER_RADIUS, y + BORDER_RADIUS, BORDER_RADIUS, -90 * degrees, 0 * degrees)
ctx.arc(x + w - BORDER_RADIUS, y + h - BORDER_RADIUS, BORDER_RADIUS, 0 * degrees, 90 * degrees)
ctx.arc(x + BORDER_RADIUS, y + h - BORDER_RADIUS, BORDER_RADIUS, 90 * degrees, 180 * degrees)
ctx.arc(x + BORDER_RADIUS, y + BORDER_RADIUS, BORDER_RADIUS, 180 * degrees, 270 * degrees)
ctx.close_path()
else:
ctx.rectangle(x, y, w, h)
ctx.set_source_rgba(BORDER_R / 255, BORDER_G / 255, BORDER_B / 255, BORDER_A)
ctx.set_line_width(BORDER_WIDTH)
ctx.stroke()
ctx.restore()
def main():
get_args()
root = Gdk.get_default_root_window()
root.get_screen()
screen_width, screen_height = get_screen_size(Gdk.Display.get_default())
Highlight(screen_width, screen_height)
Gtk.main()
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
exit(0)
else:
print(
"xborders: This program is not meant to be imported to other Python modules. Please run xborders as a "
"standalone script!")