~ruther/nixos-config

ref: 6904cf1761334d033556f106c82d79b48e6657f4 nixos-config/home/modules/profiles/desktop/qtile/config/tasklist.py -rw-r--r-- 21.2 KiB
6904cf17 — Frantisek Bohacek refactor: modularize the configuration 1 year, 1 day ago
                                                                                
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
# Copyright (c) 2012-2014 roger
# Copyright (c) 2012-2015 Tycho Andersen
# Copyright (c) 2013 dequis
# Copyright (c) 2013 Tao Sauvage
# Copyright (c) 2013 Craig Barnes
# Copyright (c) 2014 Sean Vig
# Copyright (c) 2018 Piotr Przymus
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import re

import cairocffi

try:
    from xdg.IconTheme import getIconPath

    has_xdg = True
except ImportError:
    has_xdg = False

from libqtile import bar, hook, pangocffi
from libqtile.images import Img
from libqtile.log_utils import logger
from libqtile.widget import base


class TaskList(base._Widget, base.PaddingMixin, base.MarginMixin):
    """Displays the icon and name of each window in the current group

    Contrary to WindowTabs this is an interactive widget.  The window that
    currently has focus is highlighted.

    Optional requirements: `pyxdg <https://pypi.org/project/pyxdg/>`__ is needed
    to use theme icons and to display icons on Wayland.
    """

    orientations = base.ORIENTATION_HORIZONTAL
    defaults = [
        ("font", "sans", "Default font"),
        ("fontsize", None, "Font size. Calculated if None."),
        ("foreground", "ffffff", "Foreground colour"),
        ("fontshadow", None, "font shadow color, default is None(no shadow)"),
        ("borderwidth", 2, "Current group border width"),
        ("border", "215578", "Border colour"),
        ("rounded", True, "To round or not to round borders"),
        (
            "highlight_method",
            "border",
            "Method of highlighting (one of 'border' or 'block') "
            "Uses `*_border` color settings",
        ),
        ("urgent_border", "FF0000", "Urgent border color"),
        (
            "urgent_alert_method",
            "border",
            "Method for alerting you of WM urgent " "hints (one of 'border' or 'text')",
        ),
        ("highlight_color", "000000", "The color to highlight with in line mode"),
        (
            "unfocused_border",
            None,
            "Border color for unfocused windows. "
            "Affects only hightlight_method 'border' and 'block'. "
            "Defaults to None, which means no special color.",
        ),
        (
            "max_title_width",
            None,
            "Max size in pixels of task title." "(if set to None, as much as available.)",
        ),
        (
            "title_width_method",
            None,
            "Method to compute the width of task title. (None, 'uniform'.)"
            "Defaults to None, the normal behaviour.",
        ),
        (
            "parse_text",
            None,
            "Function to parse and modify window names. "
            "e.g. function in config that removes excess "
            "strings from window name: "
            "def my_func(text)"
            '    for string in [" - Chromium", " - Firefox"]:'
            '        text = text.replace(string, "")'
            "   return text"
            "then set option parse_text=my_func",
        ),
        ("spacing", None, "Spacing between tasks." "(if set to None, will be equal to margin_x)"),
        (
            "txt_minimized",
            "_ ",
            "Text representation of the minimized window state. " 'e.g., "_ " or "\U0001F5D5 "',
        ),
        (
            "txt_maximized",
            "[] ",
            "Text representation of the maximized window state. " 'e.g., "[] " or "\U0001F5D6 "',
        ),
        (
            "txt_floating",
            "V ",
            "Text representation of the floating window state. " 'e.g., "V " or "\U0001F5D7 "',
        ),
        (
            "markup_normal",
            None,
            "Text markup of the normal window state. Supports pangomarkup with markup=True."
            'e.g., "{}" or "<span underline="low">{}</span>"',
        ),
        (
            "markup_minimized",
            None,
            "Text markup of the minimized window state. Supports pangomarkup with markup=True."
            'e.g., "{}" or "<span underline="low">{}</span>"',
        ),
        (
            "markup_maximized",
            None,
            "Text markup of the maximized window state. Supports pangomarkup with markup=True."
            'e.g., "{}" or "<span underline="low">{}</span>"',
        ),
        (
            "markup_floating",
            None,
            "Text markup of the floating window state. Supports pangomarkup with markup=True."
            'e.g., "{}" or "<span underline="low">{}</span>"',
        ),
        (
            "markup_focused",
            None,
            "Text markup of the focused window state. Supports pangomarkup with markup=True."
            'e.g., "{}" or "<span underline="low">{}</span>"',
        ),
        (
            "icon_size",
            None,
            "Icon size. " "(Calculated if set to None. Icons are hidden if set to 0.)",
        ),
        (
            "theme_mode",
            None,
            "When to use theme icons. `None` = never, `preferred` = use if available, "
            "`fallback` = use if app does not provide icon directly. "
            "`preferred` and `fallback` have identical behaviour on Wayland.",
        ),
        (
            "theme_path",
            None,
            "Path to icon theme to be used by pyxdg for icons. ``None`` will use default icon theme.",
        ),
        (
            "window_name_location",
            False,
            "Whether to show the location of the window in the title.",
        ),
        (
            "window_name_location_offset",
            0,
            "The offset given to the window location",
        ),
    ]

    def __init__(self, **config):
        base._Widget.__init__(self, bar.STRETCH, **config)
        self.add_defaults(TaskList.defaults)
        self.add_defaults(base.PaddingMixin.defaults)
        self.add_defaults(base.MarginMixin.defaults)
        self._icons_cache = {}
        self._box_end_positions = []
        self.markup = False
        self.clicked = None
        if self.spacing is None:
            self.spacing = self.margin_x

        self.add_callbacks({"Button1": self.select_window})

    def box_width(self, text):
        """
        calculate box width for given text.
        If max_title_width is given, the returned width is limited to it.
        """
        if self.markup:
            text = re.sub("<[^<]+?>", "", text)
        width, _ = self.drawer.max_layout_size([text], self.font, self.fontsize)
        width = width + 2 * (self.padding_x + self.borderwidth)
        return width

    def get_taskname(self, window):
        """
        Get display name for given window.
        Depending on its state minimized, maximized and floating
        appropriate characters are prepended.
        """
        state = ""
        markup_str = self.markup_normal

        # Enforce markup and new string format behaviour when
        # at least one markup_* option is used.
        # Mixing non markup and markup may cause problems.
        if (
            self.markup_minimized
            or self.markup_maximized
            or self.markup_floating
            or self.markup_focused
        ):
            enforce_markup = True
        else:
            enforce_markup = False

        if window is None:
            pass
        elif window.minimized:
            state = self.txt_minimized
            markup_str = self.markup_minimized
        elif window.maximized:
            state = self.txt_maximized
            markup_str = self.markup_maximized
        elif window.floating:
            state = self.txt_floating
            markup_str = self.markup_floating
        elif window is window.group.current_window:
            markup_str = self.markup_focused

        window_location = (
            f"[{window.group.windows.index(window) + self.window_name_location_offset}] "
            if self.window_name_location
            else ""
        )
        window_name = window_location + window.name if window and window.name else "?"

        if callable(self.parse_text):
            try:
                window_name = self.parse_text(window_name)
            except:  # noqa: E722
                logger.exception("parse_text function failed:")

        # Emulate default widget behavior if markup_str is None
        if enforce_markup and markup_str is None:
            markup_str = "%s{}" % (state)

        if markup_str is not None:
            self.markup = True
            window_name = pangocffi.markup_escape_text(window_name)
            return markup_str.format(window_name)

        return "%s%s" % (state, window_name)

    @property
    def windows(self):
        if self.qtile.core.name == "x11":
            return [
                w
                for w in self.bar.screen.group.windows
                if w.window.get_wm_type() in ("normal", None)
            ]
        return self.bar.screen.group.windows

    def calc_box_widths(self):
        """
        Calculate box width for each window in current group.
        If the available space is less than overall size of boxes,
        the boxes are shrunk by percentage if greater than average.
        """
        windows = self.windows
        window_count = len(windows)

        # if no windows present for current group just return empty list
        if not window_count:
            return []

        # Determine available and max average width for task name boxes.
        width_total = self.width - 2 * self.margin_x - (window_count - 1) * self.spacing
        width_avg = width_total / window_count

        names = [self.get_taskname(w) for w in windows]

        if self.icon_size == 0:
            icons = len(windows) * [None]
        else:
            icons = [self.get_window_icon(w) for w in windows]

        # Obey title_width_method if specified
        if self.title_width_method == "uniform":
            width_uniform = width_total // window_count
            width_boxes = [width_uniform for w in range(window_count)]
        else:
            # Default behaviour: calculated width for each task according to
            # icon and task name consisting
            # of state abbreviation and window name
            width_boxes = [
                (
                    self.box_width(names[idx])
                    + ((self.icon_size + self.padding_x) if icons[idx] else 0)
                )
                for idx in range(window_count)
            ]

        # Obey max_title_width if specified
        if self.max_title_width:
            width_boxes = [min(w, self.max_title_width) for w in width_boxes]

        width_sum = sum(width_boxes)

        # calculated box width are to wide for available widget space:
        if width_sum > width_total:
            # sum the width of tasks shorter than calculated average
            # and calculate a ratio to shrink boxes greater than width_avg
            width_shorter_sum = sum([w for w in width_boxes if w < width_avg])

            ratio = (width_total - width_shorter_sum) / (width_sum - width_shorter_sum)
            # determine new box widths by shrinking boxes greater than avg
            width_boxes = [(w if w < width_avg else w * ratio) for w in width_boxes]

        return zip(windows, icons, names, width_boxes)

    def _configure(self, qtile, bar):
        base._Widget._configure(self, qtile, bar)

        if not has_xdg and self.theme_mode is not None:
            logger.warning("You must install pyxdg to use theme icons.")
            self.theme_mode = None

        if self.theme_mode and self.theme_mode not in ["preferred", "fallback"]:
            logger.warning(
                "Unexpected theme_mode (%s). Theme icons will be disabled.", self.theme_mode
            )
            self.theme_mode = None

        if qtile.core.name == "wayland" and self.theme_mode is None and self.icon_size != 0:
            # Disable icons
            self.icon_size = 0

        if self.icon_size is None:
            self.icon_size = self.bar.height - 2 * (self.borderwidth + self.margin_y)

        if self.fontsize is None:
            calc = self.bar.height - self.margin_y * 2 - self.borderwidth * 2 - self.padding_y * 2
            self.fontsize = max(calc, 1)
        self.layout = self.drawer.textlayout(
            "", "ffffff", self.font, self.fontsize, self.fontshadow, wrap=False
        )
        self.setup_hooks()

    def update(self, window=None):
        if not window or window in self.windows:
            self.bar.draw()

    def remove_icon_cache(self, window):
        wid = window.wid
        if wid in self._icons_cache:
            self._icons_cache.pop(wid)

    def invalidate_cache(self, window):
        self.remove_icon_cache(window)
        self.update(window)

    def setup_hooks(self):
        hook.subscribe.client_name_updated(self.update)
        hook.subscribe.focus_change(self.update)
        hook.subscribe.float_change(self.update)
        hook.subscribe.client_urgent_hint_changed(self.update)

        hook.subscribe.net_wm_icon_change(self.invalidate_cache)
        hook.subscribe.client_killed(self.remove_icon_cache)

    def drawtext(self, text, textcolor, width):
        if self.markup:
            self.layout.markup = self.markup

        self.layout.text = text

        self.layout.font_family = self.font
        self.layout.font_size = self.fontsize
        self.layout.colour = textcolor
        if width is not None:
            self.layout.width = width

    def drawbox(
        self,
        offset,
        text,
        bordercolor,
        textcolor,
        width=None,
        rounded=False,
        block=False,
        line=False,
        icon=None,
        highlight_color=None,
    ):
        self.drawtext(text, textcolor, width)

        icon_padding = (self.icon_size + self.padding_x) if icon else 0
        padding_x = [self.padding_x + icon_padding, self.padding_x]

        if bordercolor is None:
            # border colour is set to None when we don't want to draw a border at all
            # Rather than dealing with alpha blending issues, we just set border width
            # to 0.
            border_width = 0
            framecolor = self.background or self.bar.background
        else:
            border_width = self.borderwidth
            framecolor = bordercolor

        framed = self.layout.framed(border_width, framecolor, padding_x, self.padding_y)
        if block and bordercolor is not None:
            framed.draw_fill(offset, self.margin_y, rounded)
        elif line:
            pad_y = [
                (self.bar.height - self.layout.height - self.borderwidth) / 2,
                (self.bar.height - self.layout.height + self.borderwidth) / 2,
            ]
            framed = self.layout.framed(border_width, framecolor, padding_x, pad_y, highlight_color)

            framed.drawer.set_source_rgb(framed.border_color)

            opts = [
                offset,
                self.margin_y,
                framed.layout.width + framed.pad_left + framed.pad_right,
                framed.layout.height + framed.pad_top + framed.pad_bottom,
                framed.border_width,
            ]

            if bordercolor != None:
                framed.drawer.set_source_rgb(framed.highlight_color)
                framed.drawer.fillrect(*opts)
                framed.drawer.set_source_rgb(framed.border_color)

            opts = [
                offset,
                0,# framed.height - framed.border_width,
                framed.layout.width + framed.pad_left + framed.pad_right,
                framed.border_width,
                framed.border_width,
            ]

            framed.drawer.fillrect(*opts)
            framed.drawer.ctx.stroke()
            framed.layout.draw(offset + framed.pad_left, 0 + framed.pad_top)
        else:
            framed.draw(offset, self.margin_y, rounded)

        if icon:
            self.draw_icon(icon, offset)

    def get_clicked(self, x, y):
        box_start = self.margin_x
        for box_end, win in zip(self._box_end_positions, self.windows):
            if box_start <= x <= box_end:
                return win
            else:
                box_start = box_end + self.spacing
        # not found any , return None
        return None

    def button_press(self, x, y, button):
        self.clicked = self.get_clicked(x, y)
        base._Widget.button_press(self, x, y, button)

    def select_window(self):
        if self.clicked:
            current_win = self.bar.screen.group.current_window
            window = self.clicked
            if window is not current_win:
                window.group.focus(window, False)
                if window.floating:
                    window.bring_to_front()
            else:
                window.toggle_minimize()

    def _get_class_icon(self, window):
        if not getattr(window, "icons", False):
            return None

        icons = sorted(
            iter(window.icons.items()),
            key=lambda x: abs(self.icon_size - int(x[0].split("x")[0])),
        )
        icon = icons[0]
        width, height = map(int, icon[0].split("x"))

        img = cairocffi.ImageSurface.create_for_data(
            icon[1], cairocffi.FORMAT_ARGB32, width, height
        )

        return img

    def _get_theme_icon(self, window):
        classes = window.get_wm_class()

        if not classes:
            return None

        icon = None

        for cl in classes:
            for app in set([cl, cl.lower()]):
                icon = getIconPath(app, theme=self.theme_path)
                if icon is not None:
                    break
            else:
                continue
            break

        if not icon:
            return None

        img = Img.from_path(icon)

        return img.surface

    def get_window_icon(self, window):
        if not getattr(window, "icons", False) and self.theme_mode is None:
            return None

        cache = self._icons_cache.get(window.wid)
        if cache:
            return cache

        surface = None
        img = None

        if self.qtile.core.name == "x11":
            img = self._get_class_icon(window)

        if self.theme_mode == "preferred" or (self.theme_mode == "fallback" and img is None):
            xdg_img = self._get_theme_icon(window)
            if xdg_img:
                img = xdg_img

        if img is not None:
            surface = cairocffi.SurfacePattern(img)
            height = img.get_height()
            width = img.get_width()
            scaler = cairocffi.Matrix()
            if height != self.icon_size:
                sp = height / self.icon_size
                height = self.icon_size
                width /= sp
                scaler.scale(sp, sp)
            surface.set_matrix(scaler)

        self._icons_cache[window.wid] = surface
        return surface

    def draw_icon(self, surface, offset):
        if not surface:
            return

        x = offset + self.borderwidth + self.padding_x
        y = (self.height - self.icon_size) // 2

        self.drawer.ctx.save()
        self.drawer.ctx.translate(x, y)
        self.drawer.ctx.set_source(surface)
        self.drawer.ctx.paint()
        self.drawer.ctx.restore()

    def draw(self):
        self.drawer.clear(self.background or self.bar.background)
        offset = self.margin_x

        self._box_end_positions = []
        for w, icon, task, bw in self.calc_box_widths():
            self._box_end_positions.append(offset + bw)

            if w.urgent:
                border = self.urgent_border
                text_color = border
            elif w is w.group.current_window:
                border = self.border
                text_color = border
            else:
                border = self.unfocused_border or None
                text_color = self.foreground

            if self.highlight_method == "text":
                border = None
            else:
                text_color = self.foreground

            textwidth = (
                bw - 2 * self.padding_x - ((self.icon_size + self.padding_x) if icon else 0)
            )
            self.drawbox(
                offset,
                task,
                border,
                text_color,
                rounded=self.rounded,
                block=(self.highlight_method == "block"),
                line=(self.highlight_method == "line"),
                width=textwidth,
                highlight_color=self.highlight_color,
                icon=icon,
            )
            offset += bw + self.spacing

        self.drawer.draw(offsetx=self.offset, offsety=self.offsety, width=self.width)
Do not follow this link