Example #1
0
def get_redshift_value(module):
    widget = module.widget()
    f = open("/home/checco/log/current_temp.txt", "r")
    stringa = f.readline().strip()
    f.close()
    widget.set("temp", stringa+'K \uf06d')
    core.event.trigger("update", [widget.module.id], redraw_only=True)
Example #2
0
    def __init__(self, config, theme):
        super(Module, self).__init__(config, theme, [])

        self.background = True

        self.__layout = util.format.aslist(
            self.parameter(
                "layout",
                "playerctl.prev, playerctl.song, playerctl.pause, playerctl.next"
            ))

        self.__song = ""
        self.__cmd = "playerctl "
        self.__format = self.parameter("format", "{artist} - {title}")

        widget_map = {}
        for widget_name in self.__layout:
            widget = self.add_widget(name=widget_name)
            if widget_name == "playerctl.prev":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "previous",
                }
                widget.set("state", "prev")
            elif widget_name == "playerctl.pause":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "play-pause",
                }
            elif widget_name == "playerctl.next":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "next",
                }
                widget.set("state", "next")
            elif widget_name == "playerctl.song":
                widget_map[widget] = [{
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "play-pause",
                }, {
                    "button": core.input.WHEEL_UP,
                    "cmd": self.__cmd + "next",
                }, {
                    "button": core.input.WHEEL_DOWN,
                    "cmd": self.__cmd + "previous",
                }]
            else:
                raise KeyError(
                    "The playerctl module does not have a {widget_name!r} widget"
                    .format(widget_name=widget_name))

        for widget, callback_options in widget_map.items():
            if isinstance(callback_options, dict):
                core.input.register(widget, **callback_options)
Example #3
0
    def __init__(self, config, theme):
        super().__init__(config, theme, [])
        self._percpu = util.format.asbool(self.parameter("percpu", False))

        for idx, cpu_perc in enumerate(self.cpu_utilization()):
            widget = self.add_widget(name="cpu#{}".format(idx),
                                     full_text=self.utilization)
            widget.set("utilization", cpu_perc)
            widget.set("theme.minwidth", self._format.format(100.0 - 10e-20))

        core.input.register(self,
                            button=core.input.LEFT_MOUSE,
                            cmd="gnome-system-monitor")
Example #4
0
    def update(self):
        widget = self.widget()
        res = util.cli.execute("dnf updateinfo", ignore_errors=True)

        security = 0
        bugfixes = 0
        enhancements = 0
        other = 0
        for line in res.split("\n"):
            if not line.startswith(" "):
                continue
            elif "ecurity" in line:
                for s in line.split():
                    if s.isdigit():
                        security += int(s)
            elif "ugfix" in line:
                for s in line.split():
                    if s.isdigit():
                        bugfixes += int(s)
            elif "hancement" in line:
                for s in line.split():
                    if s.isdigit():
                        enhancements += int(s)
            else:
                for s in line.split():
                    if s.isdigit():
                        other += int(s)

        widget.set("security", security)
        widget.set("bugfixes", bugfixes)
        widget.set("enhancements", enhancements)
        widget.set("other", other)
Example #5
0
def get_dnf_info(widget):
    res = util.cli.execute("dnf updateinfo", ignore_errors=True)

    security = 0
    bugfixes = 0
    enhancements = 0
    other = 0
    for line in res.split("\n"):
        if not line.startswith(" "):
            continue
        elif "ecurity" in line:
            for s in line.split():
                if s.isdigit():
                    security += int(s)
        elif "ugfix" in line:
            for s in line.split():
                if s.isdigit():
                    bugfixes += int(s)
        elif "hancement" in line:
            for s in line.split():
                if s.isdigit():
                    enhancements += int(s)
        else:
            for s in line.split():
                if s.isdigit():
                    other += int(s)

    widget.set("security", security)
    widget.set("bugfixes", bugfixes)
    widget.set("enhancements", enhancements)
    widget.set("other", other)

    core.event.trigger("update", [widget.module.id], redraw_only=True)
Example #6
0
    def update(self):
        try:
            self.clear_widgets()
            self.__get_song()

            widget_map = {}
            for widget_name in self.__layout:
                widget = self.add_widget(name=widget_name)
                if widget_name == "spotify.prev":
                    widget_map[widget] = {
                        "button": core.input.LEFT_MOUSE,
                        "cmd": self.__cmd + "Previous",
                    }
                    widget.set("state", "prev")
                elif widget_name == "spotify.pause":
                    widget_map[widget] = {
                        "button": core.input.LEFT_MOUSE,
                        "cmd": self.__cmd + "PlayPause",
                    }
                    playback_status = str(
                        dbus.Interface(
                            dbus.SessionBus().get_object(
                                "org.mpris.MediaPlayer2.spotify",
                                "/org/mpris/MediaPlayer2",
                            ),
                            "org.freedesktop.DBus.Properties",
                        ).Get("org.mpris.MediaPlayer2.Player",
                              "PlaybackStatus"))
                    if playback_status == "Playing":
                        widget.set("state", "playing")
                    else:
                        widget.set("state", "paused")
                elif widget_name == "spotify.next":
                    widget_map[widget] = {
                        "button": core.input.LEFT_MOUSE,
                        "cmd": self.__cmd + "Next",
                    }
                    widget.set("state", "next")
                elif widget_name == "spotify.song":
                    widget.set("state", "song")
                    widget.full_text(self.__song)
                else:
                    raise KeyError(
                        "The spotify module does not have a {widget_name!r} widget"
                        .format(widget_name=widget_name))
            for widget, callback_options in widget_map.items():
                core.input.register(widget, **callback_options)

        except Exception:
            self.__song = ""
Example #7
0
    def capacity(self, widget):
        widget.set("capacity", -1)
        widget.set("ac", False)
        output = "n/a"
        try:
            capacity = int(self.power.get_device_percentage(self.device))
            capacity = capacity if capacity < 100 else 100
            widget.set("capacity", capacity)
            output = "{}%".format(capacity)
            widget.set("theme.minwidth", "100%")
        except Exception as e:
            logging.exception("unable to get battery capacity: {}".format(
                str(e)))

        if self._showremaining:
            try:
                p = self.power  # an alias to make each line of code shorter
                proxy = p.bus.get_object(p.UPOWER_NAME, self.device)
                interface = dbus.Interface(proxy, p.DBUS_PROPERTIES)
                state = int(interface.Get(p.UPOWER_NAME + ".Device", "State"))
                # state: 1 => charging, 2 => discharging, other => don't care
                remain = int(
                    interface.Get(
                        p.UPOWER_NAME + ".Device",
                        ["TimeToFull", "TimeToEmpty"][state - 1],
                    ))
                remain = util.format.duration(remain, compact=True, unit=True)
                output = "{} {}".format(output, remain)
            except IndexError:
                pass
            except Exception as e:
                logging.exception(
                    "unable to get battery remaining time: {}".format(str(e)))

        return output
Example #8
0
def get_pacman_info(widget, path):
    cmd = utility("pacman-updates")
    result = util.cli.execute(cmd, ignore_errors=True)

    count = len(repos) * [0]

    for line in result.splitlines():
        if line.startswith(("http", "rsync")):
            for i in range(len(repos) - 1):
                if "/" + repos[i] + "/" in line:
                    count[i] += 1
                    break
            else:
                result[-1] += 1

    for i in range(len(repos)):
        widget.set(repos[i], count[i])
    core.event.trigger("update", [widget.module.id], redraw_only=True)
Example #9
0
def get_apt_check_info(module):
    widget = module.widget()
    try:
        res = util.cli.execute("aptitude full-upgrade --simulate --assume-yes")
        widget.set("error", None)
    except (RuntimeError, FileNotFoundError) as e:
        widget.set("error", "unable to query APT: {}".format(e))
        return

    to_upgrade = 0
    to_remove = 0
    try:
        to_upgrade, to_remove = parse_result(res)
        widget.set("to_upgrade", to_upgrade)
        widget.set("to_remove", to_remove)
    except Exception as e:
        widget.set("error", "parse error: {}".format(e))

    core.event.trigger("update", [module.id], redraw_only=True)
Example #10
0
    def update(self):
        try:
            self.__get_song()

            if self.__bus_name == "spotifyd":
                bus = self.__bus.get_object(
                    "org.mpris.MediaPlayer2.spotifyd", "/org/mpris/MediaPlayer2"
                )
            else:
                bus = self.__bus.get_object(
                    "org.mpris.MediaPlayer2.spotify", "/org/mpris/MediaPlayer2"
                )

            for widget in self.widgets():
                if widget.name == "spotify.pause":
                    playback_status = str(
                        dbus.Interface(
                            bus,
                            "org.freedesktop.DBus.Properties",
                        ).Get("org.mpris.MediaPlayer2.Player", "PlaybackStatus")
                    )
                    if playback_status == "Playing":
                        widget.set("state", "playing")
                    else:
                        widget.set("state", "paused")
                elif widget.name == "spotify.song":
                    widget.set("state", "song")
                    widget.full_text(self.__song)

        except Exception as e:
            self.__song = ""
Example #11
0
    def update(self):
        try:
            self.__get_song()

            for widget in self.widgets():
                if widget.name == "playerctl.pause":
                    playback_status = str(
                        util.cli.execute(self.__cmd + "status")).strip()
                    if playback_status != "":
                        if playback_status == "Playing":
                            widget.set("state", "playing")
                        else:
                            widget.set("state", "paused")
                elif widget.name == "playerctl.song":
                    widget.set("state", "song")
                    widget.full_text(self.__song)
        except Exception as e:
            logging.exception(e)
            self.__song = ""
Example #12
0
    def update_progress_info(self, widget):
        """Update widget's informations about the copy"""
        if not self.__active:
            return

        # These regex extracts following groups:
        #  1. pid
        #  2. command
        #  3. arguments
        #  4. progress (xx.x formated)
        #  5. quantity (.. unit / .. unit formated)
        #  6. speed
        #  7. time remaining
        extract_nospeed = re.compile(
            r"\[ *(\d*)\] ([a-zA-Z]*) (.*)\n\t(\d*\.*\d*)% \((.*)\)\n.*")
        extract_wtspeed = re.compile(
            r"\[ *(\d*)\] ([a-zA-Z]*) (.*)\n\t(\d*\.*\d*)% \((.*)\) (\d*\.\d .*) remaining (\d*:\d*:\d*)\n.*"
        )

        try:
            raw = util.cli.execute("progress -qW 0.1")
            result = extract_wtspeed.match(raw)

            if not result:
                # Abord speed measures
                raw = util.cli.execute("progress -q")
                result = extract_nospeed.match(raw)

                widget.set("spd", "???.? B/s")
                widget.set("tim", "??:??:??")
            else:
                widget.set("spd", result.group(6))
                widget.set("tim", result.group(7))

            widget.set("pid", int(result.group(1)))
            widget.set("cmd", result.group(2))
            widget.set("arg", result.group(3))
            widget.set("per", float(result.group(4)))
            widget.set("qty", result.group(5))
            return True
        except Exception:
            return False
Example #13
0
    def __create_widgets(self):
        show_temp = util.format.asbool(self.parameter("showtemp", True))
        show_fan = util.format.asbool(self.parameter("showfan", True))
        show_other = util.format.asbool(self.parameter("showother", False))
        include_chip = tuple(
            filter(len, util.format.aslist(self.parameter("chip_include",
                                                          ""))))
        exclude_chip = tuple(
            filter(len, util.format.aslist(self.parameter("chip_exclude",
                                                          ""))))
        include_field = tuple(
            filter(len, util.format.aslist(self.parameter("field_include",
                                                          ""))))
        exclude_field = tuple(
            filter(len, util.format.aslist(self.parameter("field_exclude",
                                                          ""))))
        include_chip_field = tuple(
            filter(
                len,
                util.format.aslist(self.parameter("chip_field_include", ""))))
        exclude_chip_field = tuple(
            filter(
                len,
                util.format.aslist(self.parameter("chip_field_exclude", ""))))

        if util.format.asbool(self.parameter("showcpu", True)):
            widget = self.add_widget(full_text=self.__cpu)
            widget.set("type", "cpu")

        for adapter in self.__data:
            if include_chip or exclude_chip:
                if include_chip:
                    if all([chip not in adapter for chip in include_chip]):
                        continue
                else:
                    if any([chip in adapter for chip in exclude_chip]):
                        continue

            if include_chip_field:
                try:
                    if all([
                            i.split(".")[0] not in adapter
                            for i in include_chip_field
                    ]):
                        continue
                except:
                    pass

            for package in self.__data[adapter]:
                if util.format.asbool(self.parameter("showname", False)):
                    widget = self.add_widget(full_text=package)
                    widget.set("data", self.__data[adapter][package])
                    widget.set("package", package)
                    widget.set("field", "")
                    widget.set("adapter", adapter)
                for field in self.__data[adapter][package]:

                    if include_field or exclude_field:
                        if include_field:
                            if all([
                                    included not in field
                                    for included in include_field
                            ]):
                                continue
                        else:
                            if any([
                                    excluded in field
                                    for excluded in exclude_field
                            ]):
                                continue

                    try:
                        if include_chip_field or exclude_chip_field:
                            if include_chip_field:
                                if all([
                                        i.split(".")[1] not in field
                                        for i in include_chip_field
                                        if i.split(".")[0] in adapter
                                ]):
                                    continue
                            else:
                                if any([
                                        i.split(".")[1] in field
                                        for i in exclude_chip_field
                                        if i.split(".")[0] in adapter
                                ]):
                                    continue
                    except:
                        pass

                    widget = None
                    if "temp" in field and show_temp:
                        # seems to be a temperature
                        widget = self.add_widget()
                        widget.set("type", "temp")
                    if "fan" in field and show_fan:
                        # seems to be a fan
                        widget = self.add_widget()
                        widget.set("type", "fan")
                    elif show_other:
                        # everything else
                        widget = self.add_widget()
                        widget.set("type", "other")
                    if widget:
                        widget.set("package", package)
                        widget.set("field", field)
                        widget.set("adapter", adapter)
Example #14
0
    def update(self):
        widget = self.widget()
        try:
            widget.set("rtt-unreachable", False)
            res = util.cli.execute("ping -n -q -c {} -W {} {}".format(
                widget.get("rtt-probes"),
                widget.get("rtt-timeout"),
                widget.get("address"),
            ))

            for line in res.split("\n"):
                if line.startswith("{} packets transmitted".format(
                        widget.get("rtt-probes"))):
                    m = re.search(r"(\d+)% packet loss", line)

                    widget.set("packet-loss", m.group(1))

                if not line.startswith("rtt"):
                    continue
                m = re.search(
                    r"([0-9\.]+)/([0-9\.]+)/([0-9\.]+)/([0-9\.]+)\s+(\S+)",
                    line)

                widget.set("rtt-min", float(m.group(1)))
                widget.set("rtt-avg", float(m.group(2)))
                widget.set("rtt-max", float(m.group(3)))
                widget.set("rtt-unit", m.group(5))
        except Exception as e:
            widget.set("rtt-unreachable", True)
Example #15
0
def get_redshift_value(module):
    widget = module.widget()
    location = module.parameter("location", "auto")
    lat = module.parameter("lat", None)
    lon = module.parameter("lon", None)

    # Even if location method is set to manual, if we have no lat or lon,
    # fall back to the geoclue2 method.
    if location == "manual" and (lat is None or lon is None):
        location = "geoclue2"

    command = ["redshift", "-p"]
    if location == "manual":
        command.extend(["-l", "{}:{}".format(lat, lon)])
    if location == "geoclue2":
        command.extend(["-l", "geoclue2"])

    try:
        res = util.cli.execute(" ".join(command))
    except Exception:
        res = ""
    widget.set("temp", "n/a")
    widget.set("transition", "")
    widget.set("state", "day")
    for line in res.split("\n"):
        line = line.lower()
        if "temperature" in line:
            widget.set("temp", line.split(" ")[2])
        if "period" in line:
            state = line.split(" ")[1]
            if "day" in state:
                widget.set("state", "day")
            elif "night" in state:
                widget.set("state", "night")
            else:
                widget.set("state", "transition")
                match = re.search(r"(\d+)\.\d+% ([a-z]+)", line)
                widget.set("transition",
                           "({}% {})".format(match.group(1), match.group(2)))
    core.event.trigger("update", [widget.module.id], redraw_only=True)
Example #16
0
 def update(self):
     try:
         playback_status = str(
             util.cli.execute(self.__cmd + "status 2>&1 || true",
                              shell=True)).strip()
         if playback_status == "No players found":
             playback_status = None
     except Exception as e:
         logging.exception(e)
         playback_status = None
     for widget in self.widgets():
         if playback_status:
             if widget.name == "playerctl.pause":
                 if playback_status == "Playing":
                     widget.set("state", "playing")
                 elif playback_status == "Paused":
                     widget.set("state", "paused")
                 elif playback_status == "Stopped":
                     widget.set("state", "stopped")
                 else:
                     widget.set("state", "")
             elif widget.name == "playerctl.next":
                 widget.set("state", "next")
             elif widget.name == "playerctl.prev":
                 widget.set("state", "prev")
             elif widget.name == "playerctl.song":
                 widget.full_text(self.__get_song())
         else:
             widget.set("state", "")
             widget.full_text(" ")
Example #17
0
    def __init__(self, config, theme):
        super().__init__(config, theme, [])

        self.background = True

        self.__bus_name = self.parameter("bus_name", "spotify")

        self.__layout = util.format.aslist(
            self.parameter(
                "layout", "spotify.song,spotify.prev,spotify.pause,spotify.next",
            )
        )

        self.__bus = dbus.SessionBus()
        self.__song = ""
        self.__pause = ""
        self.__format = self.parameter("format", "{artist} - {title}")

        if self.__bus_name == "spotifyd":
            self.__cmd = "dbus-send --session --type=method_call --dest=org.mpris.MediaPlayer2.spotifyd \
                /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player."
        else:
            self.__cmd = "dbus-send --session --type=method_call --dest=org.mpris.MediaPlayer2.spotify \
                /org/mpris/MediaPlayer2 org.mpris.MediaPlayer2.Player."

        widget_map = {}
        for widget_name in self.__layout:
            widget = self.add_widget(name=widget_name)
            if widget_name == "spotify.prev":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "Previous",
                }
                widget.set("state", "prev")
            elif widget_name == "spotify.pause":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "PlayPause",
                }
            elif widget_name == "spotify.next":
                widget_map[widget] = {
                    "button": core.input.LEFT_MOUSE,
                    "cmd": self.__cmd + "Next",
                }
                widget.set("state", "next")
            elif widget_name == "spotify.song":
                if util.format.asbool(self.parameter("concise_controls", "false")):
                    widget_map[widget] = [
                        {
                            "button": core.input.LEFT_MOUSE,
                            "cmd": self.__cmd + "PlayPause",
                        }, {
                            "button": core.input.WHEEL_UP,
                            "cmd": self.__cmd + "Next",
                        }, {
                            "button": core.input.WHEEL_DOWN,
                            "cmd": self.__cmd + "Previous",
                        }
                    ]
            else:
                raise KeyError(
                    "The spotify module does not have a {widget_name!r} widget".format(
                        widget_name=widget_name
                    )
                )
        # is there any reason the inputs can't be directly registered above?
        for widget, callback_options in widget_map.items():
            if isinstance(callback_options, dict):
                core.input.register(widget, **callback_options)

            elif isinstance(callback_options, list): # used by concise_controls
                for opts in callback_options:
                    core.input.register(widget, **opts)
Example #18
0
    def __init__(self, config, theme):
        super().__init__(config, theme, core.widget.Widget(self.rtt))

        self.background = True

        widget = self.widget()

        widget.set("address", self.parameter("address", "8.8.8.8"))
        widget.set("rtt-probes", self.parameter("probes", 5))
        widget.set("rtt-timeout", self.parameter("timeout", 5.0))
        widget.set("rtt-avg", 0.0)
        widget.set("rtt-unit", "")
        widget.set("packet-loss", 0)