Example #1
0
    def process_button_click(self, button_code, modmask, x, y, event) -> None:
        for m in self.mouse_map.get(button_code, []):
            if not m.modmask == modmask:
                continue

            if m.focus == "before":
                self.core.focus_by_click(event)

            if isinstance(m, Click):
                for i in m.commands:
                    if i.check(self):
                        status, val = self.server.call(
                            (i.selectors, i.name, i.args, i.kwargs))
                        if status in (interface.ERROR, interface.EXCEPTION):
                            logger.error(
                                "Mouse command error %s: %s" % (i.name, val)
                            )
            elif isinstance(m, Drag):
                if m.start:
                    i = m.start
                    status, val = self.server.call(
                        (i.selectors, i.name, i.args, i.kwargs))
                    if status in (interface.ERROR, interface.EXCEPTION):
                        logger.error(
                            "Mouse command error %s: %s" % (i.name, val)
                        )
                        continue
                else:
                    val = (0, 0)
                self._drag = (x, y, val[0], val[1], m.commands)
                self.core.grab_pointer()

            if m.focus == "after":
                self.core.focus_by_click(event)
Example #2
0
    def now_playing(self):
        """Return a string with the now playing info (Artist - Song Title)."""
        self.status = self.call_process(["playerctl", "status"]).strip()
        if self.status == "No players found":
            self.status = None
            return ""
        elif self.status == "Playing":
            self.layout.colour = self.play_color
        elif self.status == "Paused":
            self.layout.colour = self.noplay_color
        else:
            self.status = None
            return ""

        now_playing = ""
        try:
            artist = ellipsize(
                self.call_process(["playerctl", "metadata", "artist"]).strip(),
                self.max_artist_len)
            title = ellipsize(
                self.call_process(["playerctl", "metadata", "title"]).strip(),
                self.max_title_len)
            now_playing = artist + " - " + title
        except Exception as e:
            logger.error(str(e))

        return now_playing
Example #3
0
    def poll(self):
        ret_stat = []
        try:
            new_stats = self.get_stats()
            for intf in self.interface:
                down = new_stats[intf]["down"] - self.stats[intf]["down"]
                up = new_stats[intf]["up"] - self.stats[intf]["up"]
                total = new_stats[intf]["total"] - self.stats[intf]["total"]

                down = down / self.update_interval
                up = up / self.update_interval
                total = total / self.update_interval
                down, down_letter = self.convert_b(down)
                up, up_letter = self.convert_b(up)
                total, total_letter = self.convert_b(total)
                down, up, total = self._format(down, down_letter, up,
                                               up_letter, total, total_letter)
                self.stats[intf] = new_stats[intf]
                ret_stat.append(
                    self.format.format(
                        **{
                            "interface": intf,
                            "down": down + down_letter,
                            "up": up + up_letter,
                            "total": total + total_letter,
                        }))

            return " ".join(ret_stat)
        except Exception as excp:
            logger.error("%s: Caught Exception:\n%s", self.__class__.__name__,
                         excp)
Example #4
0
    def poll(self):
        ret_stat = []
        try:
            for intf in self.interface:
                new_stats = self.get_stats()
                down = new_stats[intf]['down'] - \
                    self.stats[intf]['down']
                up = new_stats[intf]['up'] - \
                    self.stats[intf]['up']

                down = down / self.update_interval
                up = up / self.update_interval
                down, down_letter = self.convert_b(down)
                up, up_letter = self.convert_b(up)
                down, up = self._format(down, down_letter, up, up_letter)
                self.stats[intf] = new_stats[intf]
                ret_stat.append(
                    self.format.format(
                        **{
                            'interface': intf,
                            'down': down + down_letter,
                            'up': up + up_letter
                        }))

            return " ".join(ret_stat)
        except Exception as excp:
            logger.error('%s: Caught Exception:\n%s', self.__class__.__name__,
                         excp)
Example #5
0
    def __init__(self, **config):
        base.ThreadPoolText.__init__(self, "", **config)
        self.add_defaults(CheckUpdates.defaults)

        # format: "Distro": ("cmd", "number of lines to subtract from output")
        self.cmd_dict = {
            "Arch": ("pacman -Qu", 0),
            "Arch_checkupdates": ("checkupdates", 0),
            "Arch_Sup": ("pacman -Sup", 1),
            "Arch_yay": ("yay -Qu", 0),
            "Debian": ("apt-show-versions -u -b", 0),
            "Ubuntu": ("aptitude search ~U", 0),
            "Fedora": ("dnf list updates", 3),
            "FreeBSD": ("pkg_version -I -l '<'", 0),
            "Mandriva": ("urpmq --auto-select", 0)
        }

        if self.custom_command:
            # Use custom_command
            self.cmd = self.custom_command

        else:
            # Check if distro name is valid.
            try:
                self.cmd = self.cmd_dict[self.distro][0]
                self.custom_command_modify = (
                    lambda x: x - self.cmd_dict[self.distro][1])
            except KeyError:
                distros = sorted(self.cmd_dict.keys())
                logger.error(self.distro + ' is not a valid distro name. ' +
                             'Use one of the list: ' + str(distros) + '.')
                self.cmd = None

        if self.execute:
            self.add_callbacks({'Button1': self.do_execute})
Example #6
0
 def cmd_function(self, function, *args, **kwargs) -> None:
     """Call a function with current object as argument"""
     try:
         function(self, *args, **kwargs)
     except Exception:
         error = traceback.format_exc()
         logger.error('Exception calling "%s":\n%s', function, error)
Example #7
0
def guess_terminal():
    """Try to guess terminal."""
    test_terminals = [
        'roxterm',
        'sakura',
        'hyper',
        'alacritty',
        'terminator',
        'termite',
        'gnome-terminal',
        'konsole',
        'xfce4-terminal',
        'lxterminal',
        'mate-terminal',
        'kitty',
        'yakuake',
        'tilda',
        'guake',
        'eterm',
        'st',
        'urxvt',
        'xterm',
        'x-terminal-emulator',
    ]

    for terminal in test_terminals:
        logger.debug('Guessing terminal: {}'.format(terminal))
        if not which(terminal, os.X_OK):
            continue

        logger.info('Terminal found: {}'.format(terminal))
        return terminal

    logger.error('Default terminal has not been found.')
Example #8
0
    def poll(self):
        try:
            new_int = self.get_stats()
            down = new_int[self.interface]['down'] - \
                self.interfaces[self.interface]['down']
            up = new_int[self.interface]['up'] - \
                self.interfaces[self.interface]['up']

            down = down / self.update_interval
            up = up / self.update_interval
            down, down_letter = self.convert_b(down)
            up, up_letter = self.convert_b(up)

            icon_up = self.icon_up
            icon_down = self.icon_down

            down, up = self._format(down, up)

            str_base = u"%s%s%s %s%s%s"

            self.interfaces = new_int
            return str_base % (icon_down, down, down_letter, icon_up, up,
                               up_letter)
        except Exception:
            logger.error(
                '%s: Probably your wlan device is switched off or otherwise not present in your system.',
                self.__class__.__name__)
Example #9
0
    def __init__(self, **config):
        base.ThreadedPollText.__init__(self, **config)
        self.add_defaults(CheckUpdates.defaults)

        # format: "Distro": ("cmd", "number of lines to subtract from output")
        self.cmd_dict = {
            "Arch": ("pacman -Qu", 0),
            "Arch_checkupdates": ("checkupdates", 0),
            "Arch_Sup": ("pacman -Sup", 1),
            "Debian": ("apt-show-versions -u -b", 0),
            "Ubuntu": ("aptitude search ~U", 0),
            "Fedora": ("dnf list updates", 3),
            "FreeBSD": ("pkg_version -I -l '<'", 0),
            "Mandriva": ("urpmq --auto-select", 0)
        }

        # Check if distro name is valid.
        try:
            self.cmd = self.cmd_dict[self.distro][0].split()
            self.subtr = self.cmd_dict[self.distro][1]
        except KeyError:
            distros = sorted(self.cmd_dict.keys())
            logger.error(self.distro + ' is not a valid distro name. ' +
                         'Use one of the list: ' + str(distros) + '.')
            self.cmd = None
Example #10
0
    def _on_frame(self, _listener, _data):
        now = Timespec.get_monotonic_time()
        wlr_output = self.wlr_output

        if not wlr_output.attach_render():
            logger.error("Could not attach renderer")
            return

        self.renderer.begin(*wlr_output.effective_resolution())
        self.renderer.clear([0, 0, 0, 1])

        if self.wallpaper:
            self.renderer.render_texture(self.wallpaper, self.transform_matrix,
                                         0, 0, 1)

        for window in self._mapped_windows:
            rdata = (
                now,
                window,
                self.x + window.x,
                self.y + window.y,
                window.opacity,
                wlr_output.scale,
            )
            window.surface.for_each_surface(self._render_surface, rdata)

        wlr_output.render_software_cursors()
        self.renderer.end()
        wlr_output.commit()
Example #11
0
    def cmd_hide_show_bar(self, position="all"):
        """Toggle visibility of a given bar

        Parameters
        ==========
        position :
            one of: "top", "bottom", "left", "right", or "all" (default: "all")
        """
        if position in ["top", "bottom", "left", "right"]:
            bar = getattr(self.current_screen, position)
            if bar:
                bar.show(not bar.is_show())
                self.current_group.layout_all()
            else:
                logger.warning(
                    "Not found bar in position '%s' for hide/show." % position)
        elif position == "all":
            screen = self.current_screen
            is_show = None
            for bar in [screen.left, screen.right, screen.top, screen.bottom]:
                if bar:
                    if is_show is None:
                        is_show = not bar.is_show()
                    bar.show(is_show)
            if is_show is not None:
                self.current_group.layout_all()
            else:
                logger.warning("Not found bar for hide/show.")
        else:
            logger.error("Invalid position value:{0:s}".format(position))
Example #12
0
 def __init__(self, **config):
     base.ThreadPoolText.__init__(self, "", **config)
     self.add_defaults(KeyboardKbdd.defaults)
     self.keyboard = self.configured_keyboards[0]
     self.is_kbdd_running = self._check_kbdd()
     if not self.is_kbdd_running:
         logger.error('Please check if kbdd is running')
         self.keyboard = "N/A"
Example #13
0
def _configure_keyboard(device: InputDevice, conf: InputConfig) -> None:
    """Applies ``InputConfig`` rules to a keyboard device"""
    device.keyboard.set_repeat_info(conf.kb_repeat_rate, conf.kb_repeat_delay)
    if isinstance(device.keyboard.data, Keyboard):
        device.keyboard.data.set_keymap(conf.kb_layout, conf.kb_options,
                                        conf.kb_variant)
    else:
        logger.error("Couldn't configure keyboard. Please report this.")
Example #14
0
 def f(self, value):
     if not isinstance(value, int):
         frame = inspect.currentframe()
         stack_trace = traceback.format_stack(frame)
         logger.error("!!!! setting %s to a non-int %s; please report this!", attr, value)
         logger.error(''.join(stack_trace[:-1]))
         value = int(value)
     setattr(self, "_" + attr, value)
Example #15
0
def autostart():
    #    lazy.spawn("/usr/lib/mate-polkit/polkit-mate-authentication-agent-1")
    #    lazy.spawn("pcmanfm -d")
    #    lazy.spawn("feh --bg-scale /home/matteo/Documents/Wallpapers/supraWp.jpg")
    output = subprocess.check_output(
        os.path.expanduser('/home/matteo/.config/qtile/scripts/autostart.sh'),
        shell=True).decode('utf-8')
    logger.error(output)
Example #16
0
def restart_on_randr(ev):
    # TODO only if numbers of screens changed
    num_screens_changed = NUM_SCREENS != get_num_screens()
    from datetime import datetime
    logger.error(
        f"SCREEN change called at {datetime.now()}: {num_screens_changed=}")
    if num_screens_changed:
        imported_qtile.cmd_restart()
Example #17
0
 def __init__(self, **config):
     base.ThreadedPollText.__init__(self, **config)
     self.add_defaults(KeyboardKbdd.defaults)
     self.keyboard = self.configured_keyboards[0]
     self.is_kbdd_running = self._check_kbdd()
     if not self.is_kbdd_running:
         logger.error('Please check if kbdd is running')
         self.keyboard = "N/A"
     self._dbus_init()
Example #18
0
def exec_then_update(qtile, cmd, widget):
    # Call it directly with subprocess.run instead of lazy.spawn to make sure
    # 'cmd' has been completed before update 'widget'
    try:
        subprocess.run(cmd, shell=True, check=True)
        update_widget(qtile, widget)
    except subprocess.CalledProcessError as e:
        logger.error(f'cmd: {e.cmd}, returncode: {e.returncode}')
        update_widget(qtile, widget, f'ERROR CODE: {e.returncode}')
Example #19
0
 def _set_colour(self, index):
     if isinstance(self.colours, list):
         try:
             self.layout.colour = self.colours[index]
         except ValueError:
             self._setColour(index - 1)
     else:
         logger.error('variable "colours" should be a list, to set a\
                         colour for all layouts, use "foreground".')
Example #20
0
 def poll(self):
     try:
         essid, quality = get_status(self.interface)
         return "{} {}/70".format(essid, quality)
     except EnvironmentError:
         logger.error(
             '%s: Probably your wlan device is switched off or '
             ' otherwise not present in your system.',
             self.__class__.__name__)
Example #21
0
 def cmd_restart(self):
     """Restart qtile"""
     try:
         self.config.load()
     except Exception as error:
         logger.error("Preventing restart because of a configuration error: {}".format(error))
         send_notification("Configuration error", str(error.__context__))
         return
     self.restart()
Example #22
0
def get_theme(filename):
    path = os.path.expanduser(filename)
    if os.path.exists(path):
        try:
            return runpy.run_path(path)
        except Exception as e:
            logger.error("Couldn't load {}".format(path))
            logger.error(e)
            return default_theme
Example #23
0
 def keyboard(self, keyboard):
     command = ['setxkbmap']
     command.extend(keyboard.split(" "))
     try:
         self.call_process(command)
     except CalledProcessError as e:
         logger.error('Can not change the keyboard layout: {0}'.format(e))
     except OSError as e:
         logger.error('Please, check that setxkbmap is available: {0}'.format(e))
Example #24
0
 def _set_colour(self, index):
     if isinstance(self.colours, list):
         try:
             self.layout.colour = self.colours[index]
         except IndexError:
             self._set_colour(index - 1)
     else:
         logger.error('variable "colours" should be a list, to set a\
                         colour for all layouts, use "foreground".')
Example #25
0
 def keyboard(self, keyboard):
     command = ['setxkbmap']
     command.extend(keyboard.split(" "))
     try:
         self.call_process(command)
     except CalledProcessError as e:
         logger.error('Can not change the keyboard layout: {0}'.format(e))
     except OSError as e:
         logger.error('Please, check that setxkbmap is available: {0}'.format(e))
Example #26
0
    def current_keyboard_layout_group(self) -> str:
        """Return the current keyboard layout group

        Examples: 'us', 'ru', 'sk'.  In case of error returns 'unknown'.
        """
        try:
            return self.call_process(['xkb-switch', '-p']).rstrip()
        except CalledProcessError as e:
            logger.error("Can't get the keyboard layout (%s)", e)
        return 'unknown'
Example #27
0
 def set_keyboard(self, layout: str, options: Optional[str]) -> None:
     command = ["setxkbmap"]
     command.extend(layout.split(" "))
     if options:
         command.extend(["-option", options])
     try:
         check_output(command)
     except CalledProcessError as e:
         logger.error("Can not change the keyboard layout: {0}".format(e))
     except OSError as e:
         logger.error("Please, check that setxkbmap is available: {0}".format(e))
Example #28
0
 def raise_for_dependencies(self) -> None:
     """
     Raises NoDependencyFoundError if at least one dependency was not
     found
     """
     try:
         self.call_process(['xkb-switch', '-v'])
     except FileNotFoundError as e:
         err_msg = "Please, check that xkb-switch is available (%s)"
         logger.error(err_msg, e)
         raise NoDependencyFoundError(err_msg % e) from None
Example #29
0
File: bar.py Project: Bauthe/qtile
    def _configure_widget(self, widget):
        configured = True
        try:
            widget._configure(self.qtile, self)
        except Exception as e:
            logger.error("{} widget crashed during _configure with "
                         "error: {}".format(widget.__class__.__name__,
                                            repr(e)))
            self.crashed_widgets.append(widget)
            configured = False

        return configured
Example #30
0
    def _check_kbdd(self):
        try:
            running_list = self.call_process(["ps", "axw"])
        except FileNotFoundError:
            logger.error("'ps' is not installed. Cannot check if kbdd is running.")
            return False

        if re.search("kbdd", running_list):
            self.keyboard = self.configured_keyboards[0]
            return True

        logger.error("kbdd is not running.")
        return False
Example #31
0
File: base.py Project: lkjell/qtile
 def button_press(self, x, y, button):
     name = "Button{0}".format(button)
     if name in self.mouse_callbacks:
         cmd = self.mouse_callbacks[name]
         if isinstance(cmd, LazyCall):
             if cmd.check(self.qtile):
                 status, val = self.qtile.server.call(
                     (cmd.selectors, cmd.name, cmd.args, cmd.kwargs))
                 if status in (interface.ERROR, interface.EXCEPTION):
                     logger.error("Mouse callback command error %s: %s" %
                                  (cmd.name, val))
         else:
             cmd()
Example #32
0
    def _on_new_output(self, _listener, wlr_output: wlrOutput):
        logger.debug("Signal: backend new_output_event")
        if wlr_output.modes != []:
            mode = wlr_output.preferred_mode()
            if mode is None:
                logger.error("New output has no output mode")
                return
            wlr_output.set_mode(mode)
            wlr_output.enable()
            wlr_output.commit()

        self.outputs.append(output.Output(self, wlr_output))
        self.output_layout.add_auto(wlr_output)
Example #33
0
        async def _release(self):
            """
            If the manager has no more callbacks then we need to release the service name
            from dbus and reset _service to None (to force subsequent calls to `register` to
            re-register the name on dbus.)
            """
            reply = await self.bus.release_name(BUS_NAME)

            if reply != ReleaseNameReply.RELEASED:
                logger.error(f"Could not release {BUS_NAME}.")
                return

            self._service = None
Example #34
0
def set_floating(window):
    if is_floating(window.window):
        logger.error('Floating window')
        window.floating = True
        # screen = window.qtile.find_closest_screen(window.x, window.y)

        screen = window.qtile.currentScreen
        group = window.qtile.currentGroup

        window.togroup(group.name)
        width, height = window.getsize()

        dx = max(0, screen.width // 2 - width // 2)
        dy = max(0, screen.height // 2 - height // 2)
        window.tweak_float(x=screen.x, y=screen.y, dx=dx, dy=dy)
Example #35
0
    def keyboard(self):
        """Return the currently used keyboard layout as a string

        Examples: "us", "us dvorak".  In case of error returns "unknown".
        """
        try:
            command = 'setxkbmap -verbose 10'
            setxkbmap_output = self.call_process(command.split(' '))
            keyboard = self.get_keyboard_layout(setxkbmap_output)
            return str(keyboard)
        except CalledProcessError as e:
            logger.error('Can not get the keyboard layout: {0}'.format(e))
        except OSError as e:
            logger.error('Please, check that xset is available: {0}'.format(e))
        return "unknown"
Example #36
0
    def poll(self):
        try:
            essid, quality = get_status(self.interface)
            disconnected = essid is None
            if disconnected:
                return self.disconnected_message

            return self.format.format(
                essid=essid,
                quality=quality,
                percent=(quality / 70)
            )
        except EnvironmentError:
            logger.error(
                '%s: Probably your wlan device is switched off or '
                ' otherwise not present in your system.',
                self.__class__.__name__)
Example #37
0
    def poll(self):
        try:
            new_int = self.get_stats()
            down = new_int[self.interface]['down'] - \
                self.interfaces[self.interface]['down']
            up = new_int[self.interface]['up'] - \
                self.interfaces[self.interface]['up']

            down = down / self.update_interval
            up = up / self.update_interval
            down, down_letter = self.convert_b(down)
            up, up_letter = self.convert_b(up)

            down, up = self._format(down, up)

            str_base = u"%s%s \u2193\u2191 %s%s"

            self.interfaces = new_int
            return str_base % (down, down_letter, up, up_letter)
        except Exception:
            logger.error('%s: Probably your wlan device is switched off or otherwise not present in your system.',
                         self.__class__.__name__)
Example #38
0
    def __init__(self, **config):
        base.ThreadedPollText.__init__(self, **config)
        self.add_defaults(CheckUpdates.defaults)

        # format: "Distro": ("cmd", "number of lines to subtract from output")
        self.cmd_dict = {"Arch": ("pacman -Qu", 0),
                         "Arch_checkupdates": ("checkupdates", 0),
                         "Arch_Sup": ("pacman -Sup", 1),
                         "Debian": ("apt-show-versions -u -b", 0),
                         "Ubuntu": ("aptitude search ~U", 0),
                         "Fedora": ("dnf list updates", 3),
                         "FreeBSD": ("pkg_version -I -l '<'", 0),
                         "Mandriva": ("urpmq --auto-select", 0)
                         }

        # Check if distro name is valid.
        try:
            self.cmd = self.cmd_dict[self.distro][0].split()
            self.subtr = self.cmd_dict[self.distro][1]
        except KeyError:
            distros = sorted(self.cmd_dict.keys())
            logger.error(self.distro + ' is not a valid distro name. ' +
                         'Use one of the list: ' + str(distros) + '.')
            self.cmd = None