示例#1
0
 def button_press(self, x, y, button):
     if not self.connect():
         return False
     try:
         status = self.client.status()
         if button == 3:
             if not status:
                 self.client.play()
             else:
                 self.client.pause()
         elif button == 4:
             self.client.previous()
         elif button == 5:
             self.client.next()
         elif button == 8:
             if status:
                 self.client.setvol(
                     max(int(status['volume']) - self.inc, 0)
                 )
         elif button == 9:
             if status:
                 self.client.setvol(
                     min(int(status['volume']) + self.inc, 100)
                 )
     except Exception:
         logger.exception('Mpd error on click')
示例#2
0
    def _get_status(self):
        playing = self.msg_nc

        try:
            self.status = self.client.status()
            self.song = self.client.currentsong()
            if self.status['state'] != 'stop':
                text = self.do_format(self.fmt_playing)

                if (self.do_color_progress and
                        self.status and
                        self.status.get('time')):
                    elapsed, total = self.status['time'].split(':')
                    percent = float(elapsed) / float(total)
                    progress = int(percent * len(text))
                    playing = '<span color="%s">%s</span>%s' % (
                        utils.hex(self.foreground_progress),
                        pangocffi.markup_escape_text(text[:progress]),
                        pangocffi.markup_escape_text(text[progress:])
                    )
                else:
                    playing = pangocffi.markup_escape_text(text)
            else:
                playing = self.do_format(self.fmt_stopped)

        except Exception:
            logger.exception('Mpd error on update')

        return playing
示例#3
0
    def poll(self):
        was_connected = self.connected

        if not self.connected:
            if self.reconnect:
                while not self.stop and not self.connect(quiet=True):
                    time.sleep(self.reconnect_interval)
            else:
                return

        if self.stop:
            return

        if was_connected:
            try:
                self.client.send_idle()
                self.client.fetch_idle()
            except mpd.ConnectionError:
                self.client.disconnect()
                self.connected = False
                return self.msg_nc
            except Exception:
                logger.exception('Error communicating with mpd')
                self.client.disconnect()
                return

        return self._get_status()
示例#4
0
    def __init__(self, name="prompt", **config):
        base._TextBox.__init__(self, "", bar.CALCULATED, **config)
        self.add_defaults(Prompt.defaults)
        self.name = name
        self.active = False
        self.completer = None
        # Define key handlers (action to do when hit an specific key)
        self.keyhandlers = {
            xkeysyms.keysyms['Tab']: self._trigger_complete,
            xkeysyms.keysyms['BackSpace']: self._delete_char(),
            xkeysyms.keysyms['Delete']: self._delete_char(False),
            xkeysyms.keysyms['KP_Delete']: self._delete_char(False),
            xkeysyms.keysyms['Escape']: self._unfocus,
            xkeysyms.keysyms['Return']: self._send_cmd,
            xkeysyms.keysyms['KP_Enter']: self._send_cmd,
            xkeysyms.keysyms['Up']: self._get_prev_cmd,
            xkeysyms.keysyms['KP_Up']: self._get_prev_cmd,
            xkeysyms.keysyms['Down']: self._get_next_cmd,
            xkeysyms.keysyms['KP_Down']: self._get_next_cmd,
            xkeysyms.keysyms['Left']: self._move_cursor(),
            xkeysyms.keysyms['KP_Left']: self._move_cursor(),
            xkeysyms.keysyms['Right']: self._move_cursor("right"),
            xkeysyms.keysyms['KP_Right']: self._move_cursor("right"),
        }
        printables = [int(hex(x), 16) for x in range(127)]
        printables = {x: self._write_char for x in printables if
                      chr(x) in string.printable}
        self.keyhandlers.update(printables)
        if self.bell_style == "visual":
            self.original_background = self.background
        # If history record is on, get saved history or create history record
        if self.record_history:
            self.history_path = os.path.join(utils.get_cache_dir(),
                                             'prompt_history')
            if os.path.exists(self.history_path):
                with open(self.history_path, 'rb') as f:
                    try:
                        self.history = pickle.load(f)
                        if self.ignore_dups_history:
                            self._dedup_history()
                    except:  # noqa: E722
                        # unfortunately, pickle doesn't wrap its errors, so we
                        # can't detect what's a pickle error and what's not.
                        logger.exception("failed to load prompt history")
                        self.history = {x: deque(maxlen=self.max_history)
                                        for x in self.completers}

                    # self.history of size does not match.
                    if len(self.history) != len(self.completers):
                        self.history = {x: deque(maxlen=self.max_history)
                                        for x in self.completers}

                    if self.max_history != \
                       self.history[list(self.history)[0]].maxlen:
                        self.history = {x: deque(self.history[x],
                                                 self.max_history)
                                        for x in self.completers}
            else:
                self.history = {x: deque(maxlen=self.max_history)
                                for x in self.completers}
示例#5
0
 def worker():
     try:
         text = self.poll()
         if self.qtile is not None:
             self.qtile.call_soon_threadsafe(self.update, text)
     except:
         logger.exception("problem polling to update widget %s", self.name)
示例#6
0
文件: qtile.py 项目: cortesi/qtile
def main():
    rename_process()
    q = make_qtile()
    try:
        q.loop()
    except Exception:
        logger.exception('Qtile crashed')
    logger.info('Exiting...')
示例#7
0
 def _load_file(self, name):
     try:
         path = os.path.join(BACKLIGHT_DIR, self.backlight_name, name)
         with open(path, 'r') as f:
             return f.read().strip()
     except:
         logger.exception("Failed to read file: %s" % name)
         raise
示例#8
0
 def _load_file(self, name):
     try:
         path = os.path.join(BACKLIGHT_DIR, self.backlight_name, name)
         with open(path, "r") as f:
             return f.read().strip()
     except IOError:
         return False
     except Exception:
         logger.exception("Failed to get %s" % name)
示例#9
0
 def get_wallpapers(self):
     try:
         # get path of all files in the directory
         self.images = list(
             filter(os.path.isfile,
                    map(self.get_path,
                        os.listdir(self.directory))))
     except IOError as e:
         logger.exception("I/O error(%s): %s", e.errno, e.strerror)
示例#10
0
    def _xpoll(self) -> None:
        """Poll the connection and dispatch incoming events"""
        assert self.qtile is not None

        while True:
            try:
                event = self.conn.conn.poll_for_event()
                if not event:
                    break

                if event.__class__ in _IGNORED_EVENTS:
                    continue

                event_type = event.__class__.__name__
                if event_type.endswith("Event"):
                    event_type = event_type[:-5]

                logger.debug(event_type)

                for target in self._get_target_chain(event_type, event):
                    logger.debug("Handling: {event_type}".format(event_type=event_type))
                    ret = target(event)
                    if not ret:
                        break

            # Catch some bad X exceptions. Since X is event based, race
            # conditions can occur almost anywhere in the code. For example, if
            # a window is created and then immediately destroyed (before the
            # event handler is evoked), when the event handler tries to examine
            # the window properties, it will throw a WindowError exception. We
            # can essentially ignore it, since the window is already dead and
            # we've got another event in the queue notifying us to clean it up.
            except (
                xcffib.xproto.WindowError,
                xcffib.xproto.AccessError,
                xcffib.xproto.DrawableError,
                xcffib.xproto.GContextError,
                xcffib.xproto.PixmapError,
                xcffib.render.PictureError,
            ):
                pass
            except Exception:
                error_code = self.conn.conn.has_error()
                if error_code:
                    error_string = xcbq.XCB_CONN_ERRORS[error_code]
                    logger.exception(
                        "Shutting down due to X connection error {error_string} ({error_code})".format(
                            error_string=error_string, error_code=error_code
                        )
                    )
                    self._remove_listener()
                    self.qtile.stop()
                    return
                logger.exception("Got an exception in poll loop")
        self.conn.flush()
示例#11
0
 def get_wallpapers(self):
     try:
         # get path of all files in the directory
         self.images = list(
             filter(
                 os.path.isfile,
                 map(self.get_path, os.listdir(os.path.expanduser(self.directory))),
             )
         )
     except IOError as e:
         logger.exception("I/O error(%s): %s", e.errno, e.strerror)
示例#12
0
文件: battery.py 项目: 20after4/qtile
 def _load_file(self, name):
     try:
         path = os.path.join(BAT_DIR, self.battery_name, name)
         with open(path, 'r') as f:
             return f.read().strip()
     except IOError:
         if name == 'current_now':
             return 0
         return False
     except Exception:
         logger.exception("Failed to get %s" % name)
示例#13
0
 def _load_file(self, name):
     try:
         path = os.path.join(BAT_DIR, self.battery_name, name)
         with open(path, 'r') as f:
             return f.read().strip()
     except IOError:
         if name == 'current_now':
             return 0
         return False
     except Exception:
         logger.exception("Failed to get %s" % name)
示例#14
0
文件: notify.py 项目: stonewell/qtile
 async def service(self):
     if self._service is None:
         try:
             bus = await MessageBus().connect()
             self._service = NotificationService(self)
             bus.export(SERVICE_PATH, self._service)
             await bus.request_name(BUS_NAME)
         except Exception:
             logger.exception('Dbus connection failed')
             self._service = None
     return self._service
示例#15
0
 def unsubscribe(self):
     """unsubscribe all hooks"""
     try:
         hook.unsubscribe.client_focus(self.on_focus_change)
     except utils.QtileError as err:
         logger.exception("Scratchpad failed to unsubscribe on_focus_change"
                          ": %s" % err)
     try:
         hook.unsubscribe.setgroup(self.on_focus_change)
     except utils.QtileError as err:
         logger.exception("Scratchpad failed to unsubscribe on_focus_change"
                          ": %s" % err)
示例#16
0
 def __try_call(self, attr_name, obj=None):
     err1 = 'Class {Class} has no attribute {attr}.'
     err2 = 'attribute "{Class}.{attr}" is not callable.'
     context = obj or self
     try:
         getattr(context, attr_name)()
     except (AttributeError, TypeError) as e:
         if isinstance(e, AttributeError):
             err = err1.format(Class=type(context).__name__, attr=attr_name)
         else:
             err = err2.format(Class=type(context).__name__, attr=attr_name)
         logger.exception(err + " {}".format(e.args[0]))
示例#17
0
    def _get_status(self):
        try:
            self.status = self.client.status()
            self.song = self.client.currentsong()
        except Exception:
            logger.exception('Mpd error on update')
            return self.msg_nc

        if self.status['state'] == 'stop':
            return self.do_format(self.fmt_stopped)
        else:
            return self._status_playing()
示例#18
0
文件: mpd.py 项目: Mic92/qtile-config
    def _get_status(self):
        try:
            self.status = self.client.status()
            self.song = self.client.currentsong()
        except Exception:
            logger.exception('Mpd error on update')
            return self.msg_nc

        if self.status['state'] == 'stop':
            return self.do_format(self.fmt_stopped)
        else:
            return self._status_playing()
示例#19
0
    def poll(self):
        if not self.parse or not self.url:
            return "Invalid config"

        body = self.fetch()

        try:
            text = self.parse(body)
        except Exception:
            logger.exception('got exception polling widget')
            text = "Can't parse"

        return text
示例#20
0
 def _connect(self):
     """Try to connect to the player if it exists"""
     try:
         self.player = self.bus.get_object(self.objname, "/Player")
         self.iface = dbus.Interface(self.player, dbus_interface="org.freedesktop.MediaPlayer")
         # See: http://xmms2.org/wiki/MPRIS for info on signals
         # and what they mean.
         self.iface.connect_to_signal("TrackChange", self.handle_track_change)
         self.iface.connect_to_signal("StatusChange", self.handle_status_change)
         self.connected = True
     except dbus.exceptions.DBusException:
         logger.exception("exception initializing mpris")
         self.connected = False
示例#21
0
def _decode_to_image_surface(bytes_img, width=None, height=None):
    try:
        surf, fmt = cairocffi.pixbuf.decode_to_image_surface(
            bytes_img, width, height)
        return _SurfaceInfo(surf, fmt)
    except TypeError:
        from libqtile.log_utils import logger
        logger.exception(
            "Couldn't load cairo image at specified width and height. "
            "Falling back to image scaling using cairo. "
            "Need cairocffi > v0.8.0")
        surf, fmt = cairocffi.pixbuf.decode_to_image_surface(bytes_img)
        return _SurfaceInfo(surf, fmt)
示例#22
0
文件: launchbar.py 项目: m-col/qtile
    def setup_images(self):
        """Create image structures for each icon files."""
        for img_name, iconfile in self.icons_files.items():
            if iconfile is None:
                logger.warning(
                    'No icon found for application "%s" (%s) switch to text mode',
                    img_name,
                    iconfile,
                )
                # if no icon is found and no default icon was set, we just
                # print the name, based on a textbox.
                textbox = base._TextBox()
                textbox._configure(self.qtile, self.bar)
                textbox.layout = self.drawer.textlayout(
                    textbox.text,
                    self.foreground,
                    self.font,
                    self.fontsize,
                    self.fontshadow,
                    markup=textbox.markup,
                )
                # the name will be displayed
                textbox.text = img_name
                textbox.calculate_length()
                self.icons_widths[img_name] = textbox.width
                self.surfaces[img_name] = textbox
                continue
            else:
                try:
                    img = cairocffi.ImageSurface.create_from_png(iconfile)
                except cairocffi.Error:
                    logger.exception(
                        'Error loading icon for application "%s" (%s)',
                        img_name, iconfile)
                    return

            input_width = img.get_width()
            input_height = img.get_height()

            sp = input_height / (self.bar.height - 4)
            width = int(input_width / sp)

            imgpat = cairocffi.SurfacePattern(img)
            scaler = cairocffi.Matrix()
            scaler.scale(sp, sp)
            scaler.translate(self.padding * -1, -2)
            imgpat.set_matrix(scaler)

            imgpat.set_filter(cairocffi.FILTER_BEST)
            self.surfaces[img_name] = imgpat
            self.icons_widths[img_name] = width
示例#23
0
文件: prompt.py 项目: sux2mfgj/qtile
 def __init__(self, name="prompt", **config):
     base._TextBox.__init__(self, "", bar.CALCULATED, **config)
     self.add_defaults(Prompt.defaults)
     self.name = name
     self.active = False
     self.completer = None
     # Define key handlers (action to do when hit an specific key)
     self.keyhandlers = {
         xkeysyms.keysyms['Tab']: self._trigger_complete,
         xkeysyms.keysyms['BackSpace']: self._delete_char(),
         xkeysyms.keysyms['Delete']: self._delete_char(False),
         xkeysyms.keysyms['KP_Delete']: self._delete_char(False),
         xkeysyms.keysyms['Escape']: self._unfocus,
         xkeysyms.keysyms['Return']: self._send_cmd,
         xkeysyms.keysyms['KP_Enter']: self._send_cmd,
         xkeysyms.keysyms['Up']: self._get_prev_cmd,
         xkeysyms.keysyms['KP_Up']: self._get_prev_cmd,
         xkeysyms.keysyms['Down']: self._get_next_cmd,
         xkeysyms.keysyms['KP_Down']: self._get_next_cmd,
         xkeysyms.keysyms['Left']: self._move_cursor(),
         xkeysyms.keysyms['KP_Left']: self._move_cursor(),
         xkeysyms.keysyms['Right']: self._move_cursor("right"),
         xkeysyms.keysyms['KP_Right']: self._move_cursor("right"),
     }
     printables = [int(hex(x), 16) for x in range(127)]
     printables = {x: self._write_char for x in printables if
                   chr(x) in string.printable}
     self.keyhandlers.update(printables)
     if self.bell_style == "visual":
         self.original_background = self.background
     # If history record is on, get saved history or create history record
     if self.record_history:
         self.history_path = os.path.expanduser('~/.qtile_history')
         if os.path.exists(self.history_path):
             with open(self.history_path, 'rb') as f:
                 try:
                     self.history = pickle.load(f)
                 except:
                     # unfortunately, pickle doesn't wrap its errors, so we
                     # can't detect what's a pickle error and what's not.
                     logger.exception("failed to load prompt history")
                     self.history = {x: deque(maxlen=self.max_history)
                                     for x in self.completers if x}
                 if self.max_history != \
                    self.history[list(self.history)[0]].maxlen:
                     self.history = {x: deque(copy.copy(self.history[x]),
                                              self.max_history)
                                     for x in self.completers if x}
         else:
             self.history = {x: deque(maxlen=self.max_history)
                             for x in self.completers if x}
示例#24
0
 def from_file(cls, kore: base.Core, path: str):
     "Create a Config() object from the python file located at path."
     try:
         sys.path.insert(0, os.path.dirname(path))
         config = __import__(os.path.basename(path)[:-3])  # noqa: F811
     except Exception:
         import traceback
         from libqtile.log_utils import logger
         logger.exception('Could not import config file %r', path)
         tb = traceback.format_exc()
         raise ConfigError(tb)
     cnf = cls(file_path=path, **vars(config))
     cnf.validate(kore)
     return cnf
示例#25
0
文件: ipc.py 项目: yoshoo90/qtile
    def send(self, msg: Any, is_json=False) -> None:
        assert self.transport is not None

        if is_json:
            send_data = _IPC.pack_json(msg)
        else:
            send_data = _IPC.pack(msg)

        self.transport.write(send_data)

        try:
            self.transport.write_eof()
        except AttributeError:
            logger.exception('Swallowing AttributeError due to asyncio bug!')
示例#26
0
文件: loop.py 项目: yobleck/qtile
 def _handle_exception(
     self,
     loop: asyncio.AbstractEventLoop,
     context: dict,
 ) -> None:
     # message is always present, but we'd prefer the exception if available
     if 'exception' in context:
         exc = context['exception']
         # CancelledErrors happen when we simply cancel the main task during
         # a normal restart procedure
         if not isinstance(exc, asyncio.CancelledError):
             logger.exception(exc)
     else:
         logger.error(f'unhandled error in event loop: {context["msg"]}')
示例#27
0
def get(DISPLAY=None, defaults=None):
    """
    Get the X resources in an X servers resource manager.

    Parameters
    ==========
    DISPLAY : str (optional)
        DISPLAY name to query. This will be taken from the environment if not specified.

    defaults : dict (optional)
        Default values to act as a fallback for missing values or in the event of a
        failed connection.

    Returns
    =======
    resources: dict
        Dictionary containing all (available) X resources. Resources that are specified
        in an Xresources/Xdefaults file as wildcards e.g. '*.color1' have the leading
        '*.' stripped.

    """
    if DISPLAY is None:
        DISPLAY = os.environ.get("DISPLAY")

    if defaults is None:
        resources = {}
    else:
        resources = defaults

    try:
        conn = xcffib.connect(display=DISPLAY)
    except xcffib.ConnectionException as e:
        logger.exception(e)
        return resources

    root = conn.get_setup().roots[0].root
    atom = conn.core.InternAtom(False, 16, 'RESOURCE_MANAGER').reply().atom

    reply = conn.core.GetProperty(False, root, atom, xcffib.xproto.Atom.STRING,
                                  0, (2**32) - 1).reply()
    conn.disconnect()

    resource_string = reply.value.buf().decode("utf-8")
    resource_list = filter(None, resource_string.split('\n'))

    for resource in resource_list:
        key, value = resource.split(':\t')
        resources[key.strip('*.')] = value

    return resources
示例#28
0
文件: start.py 项目: tusqasi/qtile
def start(options):
    try:
        locale.setlocale(locale.LC_ALL, locale.getdefaultlocale())
    except locale.Error:
        pass

    rename_process()
    q = make_qtile(options)
    try:
        q.loop()
    except Exception:
        logger.exception("Qtile crashed")
        exit(1)
    logger.info("Exiting...")
示例#29
0
    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_name = window.name if window and window.name else "?"

        if callable(self.parse_text):
            try:
                window_name = self.parse_text(window_name)
            except:
                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)
示例#30
0
    def __init__(self, **config):
        if NewWidgetBase:
            super().__init__("", **config)
        else:
            super().__init__(**config)

        self.add_defaults(OpenWeatherMap.defaults)
        if not self.api_key:
            logger.exception(
                "OpenWeatherMap: An API key is required. Pass as the `api_key` parameter"
            )
        self.url = f"https://api.openweathermap.org/data/2.5/weather?lat={self.latitude}&lon={self.longitude}&appid={self.api_key}&units={self.units}"
        if not self.icon_font:  # pylint: disable=access-member-before-definition # icon_font created by add_defaults
            self.icon_font = ICON_FONT
        self.markup = True
示例#31
0
 def poll(self):
     self.gmail = imaplib.IMAP4_SSL("imap.gmail.com")
     self.gmail.login(self.username, self.password)
     answer, raw_data = self.gmail.status(self.email_path, "(MESSAGES UNSEEN)")
     if answer == "OK":
         dec = raw_data[0].decode()
         messages = int(re.search("MESSAGES\s+(\d+)", dec).group(1))
         unseen = int(re.search("UNSEEN\s+(\d+)", dec).group(1))
         if self.status_only_unseen:
             return self.fmt % unseen
         else:
             return self.fmt % (messages, unseen)
     else:
         logger.exception("GmailChecker UNKNOWN error, answer: %s, raw_data: %s", answer, raw_data)
         return "UNKNOWN ERROR"
示例#32
0
文件: hook.py 项目: tinruufu/qtile
def fire(event, *args, **kwargs):
    if event not in subscribe.hooks:
        raise utils.QtileError("Unknown event: %s" % event)
    if event not in SKIPLOG:
        logger.debug("Internal event: %s(%s, %s)", event, args, kwargs)
    for i in subscriptions.get(event, []):
        try:
            if asyncio.iscoroutinefunction(i):
                _fire_async_event(i(*args, **kwargs))
            elif asyncio.iscoroutine(i):
                _fire_async_event(i)
            else:
                i(*args, **kwargs)
        except:  # noqa: E722
            logger.exception("Error in hook %s", event)
示例#33
0
    def setup_images(self):
        """ Create image structures for each icon files. """
        for img_name, iconfile in self.icons_files.items():
            if iconfile is None:
                logger.warning(
                    'No icon found for application "%s" (%s) switch to text mode',
                    img_name, iconfile)
                # if no icon is found and no default icon was set, we just
                # print the name, based on a textbox.
                textbox = base._TextBox()
                textbox._configure(self.qtile, self.bar)
                textbox.layout = self.drawer.textlayout(
                    textbox.text,
                    textbox.foreground,
                    textbox.font,
                    textbox.fontsize,
                    textbox.fontshadow,
                    markup=textbox.markup,
                )
                # the name will be displayed
                textbox.text = img_name
                textbox.calculate_length()
                self.icons_widths[img_name] = textbox.width
                self.surfaces[img_name] = textbox
                continue
            else:
                try:
                    img = cairocffi.ImageSurface.create_from_png(iconfile)
                except cairocffi.Error:
                    logger.exception('Error loading icon for application "%s" (%s)',
                        img_name, iconfile)
                    return

            input_width = img.get_width()
            input_height = img.get_height()

            sp = input_height / (self.bar.height - 4)
            width = int(input_width / sp)

            imgpat = cairocffi.SurfacePattern(img)
            scaler = cairocffi.Matrix()
            scaler.scale(sp, sp)
            scaler.translate(self.padding * -1, -2)
            imgpat.set_matrix(scaler)

            imgpat.set_filter(cairocffi.FILTER_BEST)
            self.surfaces[img_name] = imgpat
            self.icons_widths[img_name] = width
示例#34
0
文件: __init__.py 项目: dyuri/rcfiles
def play_sound(path):
    """
    Play an audio file. This accepts a full path to an audio file. This is mostly a
    snippet from the playsound library.
    """
    playbin = Gst.ElementFactory.make('playbin', 'playbin')
    playbin.props.uri = 'file://' + path

    set_result = playbin.set_state(Gst.State.PLAYING)
    if set_result == Gst.StateChangeReturn.ASYNC:
        bus = playbin.get_bus()
        bus.poll(Gst.MessageType.EOS, Gst.CLOCK_TIME_NONE)
        playbin.set_state(Gst.State.NULL)
    else:
        logger.exception(
            "qtools.play_sound failed with file: {0}".format(path))
示例#35
0
    def poll(self):
        if not self.parse or not self.url:
            return "Invalid config"

        try:
            body = self.fetch()
        except URLError:
            return "No network"

        try:
            text = self.parse(body)
        except Exception:
            logger.exception("got exception polling widget")
            text = "Can't parse"

        return text
示例#36
0
 def _connect(self):
     """Try to connect to the player if it exists"""
     try:
         self.player = self.bus.get_object(self.objname, '/Player')
         self.iface = dbus.Interface(
             self.player, dbus_interface='org.freedesktop.MediaPlayer')
         # See: http://xmms2.org/wiki/MPRIS for info on signals
         # and what they mean.
         self.iface.connect_to_signal("TrackChange",
                                      self.handle_track_change)
         self.iface.connect_to_signal("StatusChange",
                                      self.handle_status_change)
         self.connected = True
     except dbus.exceptions.DBusException:
         logger.exception("exception initializing mpris")
         self.connected = False
示例#37
0
    def _setup_images(self):
        """
        Loads layout icons.
        """
        for layout_name in self._get_layout_names():
            icon_file_path = self.find_icon_file_path(layout_name)
            if icon_file_path is None:
                logger.warning('No icon found for layout "{}"'.format(layout_name))
                icon_file_path = self.find_icon_file_path("unknown")

            try:
                img = cairocffi.ImageSurface.create_from_png(icon_file_path)
            except (cairocffi.Error, IOError) as e:
                # Icon file is guaranteed to exist at this point.
                # If this exception happens, it means the icon file contains
                # an invalid image or is not readable.
                self.icons_loaded = False
                logger.exception(
                    'Failed to load icon from file "{}", '
                    "error was: {}".format(icon_file_path, e.message)
                )
                return

            input_width = img.get_width()
            input_height = img.get_height()

            sp = input_height / (self.bar.height - 1)

            width = input_width / sp
            if width > self.length:
                self.length = int(width) + self.actual_padding * 2

            imgpat = cairocffi.SurfacePattern(img)

            scaler = cairocffi.Matrix()

            scaler.scale(sp, sp)
            scaler.scale(self.scale, self.scale)
            factor = (1 - 1 / self.scale) / 2
            scaler.translate(-width * factor, -width * factor)
            scaler.translate(self.actual_padding * -1, 0)
            imgpat.set_matrix(scaler)

            imgpat.set_filter(cairocffi.FILTER_BEST)
            self.surfaces[layout_name] = imgpat

        self.icons_loaded = True
示例#38
0
    def _load_file(self, name) -> Optional[Tuple[str, str]]:
        try:
            path = os.path.join(self.BAT_DIR, self.battery, name)
            if 'energy' in name or 'power' in name:
                value_type = 'uW'
            elif 'charge' in name:
                value_type = 'uAh'
            elif 'current' in name:
                value_type = 'uA'
            else:
                value_type = ''

            with open(path, 'r') as f:
                return f.read().strip(), value_type
        except Exception:
            logger.exception("Failed to get %s" % name)
        return None
示例#39
0
    def _load_file(self, name) -> Optional[Tuple[str, str]]:
        try:
            path = os.path.join(self.BAT_DIR, self.battery, name)
            if 'energy' in name or 'power' in name:
                value_type = 'uW'
            elif 'charge' in name:
                value_type = 'uAh'
            elif 'current' in name:
                value_type = 'uA'
            else:
                value_type = ''

            with open(path, 'r') as f:
                return f.read().strip(), value_type
        except Exception:
            logger.exception("Failed to get %s" % name)
        return None
示例#40
0
    def finalize(self):
        try:
            for widget in self.widgets_map.values():
                widget.finalize()

            for layout in self.config.layouts:
                layout.finalize()

            for screen in self.screens:
                for bar in [screen.top, screen.bottom, screen.left, screen.right]:
                    if bar is not None:
                        bar.finalize()
        except:  # noqa: E722
            logger.exception('exception during finalize')
        finally:
            hook.clear()
            self.core.finalize()
示例#41
0
    def poll(self):
        statuses: List[str] = []
        try:
            # pylint: disable=I1101
            ifaces = netifaces.interfaces()
            wifi_ifaces = [iface for iface in ifaces if iface.startswith("wl")]
            eth_ifaces = [iface for iface in ifaces if iface.startswith("en")]

            for iface in wifi_ifaces:
                self.format_wifi(statuses, iface)

            for iface in eth_ifaces:
                self.format_eth(statuses, iface)

            return " ".join(statuses)

        except Exception:
            logger.exception("CustomNetwork is broke!")
示例#42
0
 def poll(self):
     self.gmail = imaplib.IMAP4_SSL('imap.gmail.com')
     self.gmail.login(self.username, self.password)
     answer, raw_data = self.gmail.status(self.email_path,
                                          '(MESSAGES UNSEEN)')
     if answer == "OK":
         dec = raw_data[0].decode()
         messages = int(re.search(r'MESSAGES\s+(\d+)', dec).group(1))
         unseen = int(re.search(r'UNSEEN\s+(\d+)', dec).group(1))
         if (self.status_only_unseen):
             return self.display_fmt.format(unseen)
         else:
             return self.display_fmt.format(messages, unseen)
     else:
         logger.exception(
             'GmailChecker UNKNOWN error, answer: %s, raw_data: %s', answer,
             raw_data)
         return "UNKNOWN ERROR"
示例#43
0
    def __init__(self, name="prompt", **config) -> None:
        base._TextBox.__init__(self, "", bar.CALCULATED, **config)
        self.add_defaults(Prompt.defaults)
        self.name = name
        self.active = False
        self.completer = None  # type: Optional[AbstractCompleter]

        # If history record is on, get saved history or create history record
        if self.record_history:
            self.history_path = os.path.join(utils.get_cache_dir(),
                                             "prompt_history")
            if os.path.exists(self.history_path):
                with open(self.history_path, "rb") as f:
                    try:
                        self.history = pickle.load(f)
                        if self.ignore_dups_history:
                            self._dedup_history()
                    except:  # noqa: E722
                        # unfortunately, pickle doesn't wrap its errors, so we
                        # can't detect what's a pickle error and what's not.
                        logger.exception("failed to load prompt history")
                        self.history = {
                            x: deque(maxlen=self.max_history)
                            for x in self.completers
                        }

                    # self.history of size does not match.
                    if len(self.history) != len(self.completers):
                        self.history = {
                            x: deque(maxlen=self.max_history)
                            for x in self.completers
                        }

                    if self.max_history != self.history[list(
                            self.history)[0]].maxlen:
                        self.history = {
                            x: deque(self.history[x], self.max_history)
                            for x in self.completers
                        }
            else:
                self.history = {
                    x: deque(maxlen=self.max_history)
                    for x in self.completers
                }
示例#44
0
    def _configure(self):
        """
        This is the part of init that needs to happen after the event loop is
        fully set up. asyncio is required to listen and respond to backend
        events.
        """
        self._process_screens()
        self.current_screen = self.screens[0]

        # Map and Grab keys
        for key in self.config.keys:
            self.grab_key(key)

        for button in self.config.mouse:
            self.grab_button(button)

        # no_spawn is set when we are restarting; we only want to run the
        # startup hook once.
        if not self.no_spawn:
            hook.fire("startup_once")
        hook.fire("startup")

        if self._state:
            try:
                with open(self._state, 'rb') as f:
                    st = pickle.load(f)
                st.apply(self)
            except:  # noqa: E722
                logger.exception("failed restoring state")
            finally:
                os.remove(self._state)

        self.core.scan()
        if self._state:
            for screen in self.screens:
                screen.group.layout_all()
        self._state = None
        self.update_desktops()
        hook.subscribe.setgroup(self.update_desktops)

        if self.config.reconfigure_screens:
            hook.subscribe.screen_change(self.cmd_reconfigure_screens)

        hook.fire("startup_complete")
示例#45
0
 def _load_icon(self, notif):
     if not notif.app_icon:
         return None
     if notif.app_icon in self._icons:
         return self._icons.get(notif.app_icon)
     try:
         img = images.Img.from_path(notif.app_icon)
         if img.width > img.height:
             img.resize(width=self.icon_size)
         else:
             img.resize(height=self.icon_size)
         surface, _ = images._decode_to_image_surface(
             img.bytes_img, img.width, img.height)
         self._icons[notif.app_icon] = surface, surface.get_height()
     except (FileNotFoundError, images.LoadingError,
             IsADirectoryError) as e:
         logger.exception(e)
         self._icons[notif.app_icon] = None
     return self._icons[notif.app_icon]
示例#46
0
文件: base.py 项目: daineal/qtile
        def on_done(future):
            try:
                result = future.result()
            except Exception:
                logger.exception('poll() raised exceptions, not rescheduling')

            if result is not None:
                try:
                    self.update(result)

                    if self.update_interval is not None:
                        self.timeout_add(self.update_interval, self.timer_setup)
                    else:
                        self.timer_setup()

                except Exception:
                    logger.exception('Failed to reschedule.')
            else:
                logger.warning('poll() returned None, not rescheduling')
示例#47
0
文件: mpd.py 项目: Mic92/qtile-config
 def button_press(self, x, y, button):
     client = mpd.MPDClient()
     try:
         client.connect(host=self.host, port=self.port)
         status = client.status()
         if button == 3:
             if status['state'] == 'pause':
                 client.play()
             else:
                 client.pause()
         elif button == 4:
             client.setvol(min(int(status['volume']) + self.inc, 100))
         elif button == 5:
             client.setvol(max(int(status['volume']) - self.inc, 0))
     except Exception:
         logger.exception('Mpd error on click')
     try:
         client.disconnect()
     except mpd.ConnectionError:
         pass
示例#48
0
    def formatter(self, status, currentsong):
        play_status = self.play_states[status['state']]

        # Dirty hack to prevent keys conflict
        currentsong['fulltime'] = currentsong['time']
        del currentsong['time']

        self.prepare_formatting(status, currentsong)
        status.update(currentsong)

        fmt = self.status_format
        if not isinstance(fmt, str):
            fmt = str(fmt)

        try:
            formatted = fmt.format(play_status=play_status, **status)
            return formatted
        except KeyError as e:
            logger.exception("mpd client did not return status: {}".format(e.args[0]))
            return "ERROR"
示例#49
0
    def poll(self):
        if not self.parse or not self.url:
            return "Invalid config"

        data = self.data
        headers = {"User-agent": self.user_agent}
        if self.json:
            headers['Content-Type'] = 'application/json'

        if data and not isinstance(data, str):
            data = json.dumps(data).encode()

        headers.update(self.headers)
        body = self.fetch(self.url, data, headers, self.json, self.xml)

        try:
            text = self.parse(body)
        except Exception:
            logger.exception('got exception polling widget')
            text = "Can't parse"

        return text
示例#50
0
    def connect(self, quiet=False):
        if self.connected:
            return True

        try:
            self.client.connect(host=self.host, port=self.port)
        except Exception:
            if not quiet:
                logger.exception('Failed to connect to mpd')
            return False

        if self.password:
            try:
                self.client.password(self.password)
            except Exception:
                logger.warning('Authentication failed.  Disconnecting')
                try:
                    self.client.disconnect()
                except Exception:
                    pass

        self.connected = True
        return True
示例#51
0
文件: mpd.py 项目: Mic92/qtile-config
    def poll(self):
        if not self.connect():
            return

        if self.first_poll:
            self.first_poll = False
            return self._get_status()

        try:
            self.client.send_idle()
            canRead = select.select([self.client], [], [], 5.0)[0]
            if canRead:
                self.client.fetch_idle()
            else:
                self.client.noidle()
        except mpd.ConnectionError:
            self.connected = False
            return self.msg_nc
        except Exception:
            logger.exception('Error communicating with mpd')
            return

        return self._get_status()
示例#52
0
文件: volume.py 项目: daineal/qtile
    def setup_images(self):
        for img_name in (
            'audio-volume-high',
            'audio-volume-low',
            'audio-volume-medium',
            'audio-volume-muted'
        ):

            try:
                img = cairocffi.ImageSurface.create_from_png(
                    os.path.join(self.theme_path, '%s.png' % img_name)
                )
            except cairocffi.Error:
                self.theme_path = None
                self.length_type = bar.CALCULATED
                logger.exception('Volume switching to text mode')
                return
            input_width = img.get_width()
            input_height = img.get_height()

            sp = input_height / float(self.bar.height - 1)

            width = input_width / sp
            if width > self.length:
                self.length = int(width) + self.actual_padding * 2

            imgpat = cairocffi.SurfacePattern(img)

            scaler = cairocffi.Matrix()

            scaler.scale(sp, sp)
            scaler.translate(self.actual_padding * -1, 0)
            imgpat.set_matrix(scaler)

            imgpat.set_filter(cairocffi.FILTER_BEST)
            self.surfaces[img_name] = imgpat
示例#53
0
 def _wrapper(self, method, *method_args):
     try:
         method(*method_args)
     except:
         logger.exception('got exception from widget timer')
示例#54
0
文件: qtile.py 项目: 20after4/qtile
def make_qtile():
    from argparse import ArgumentParser
    parser = ArgumentParser(
        description='A full-featured, pure-Python tiling window manager.',
        prog='qtile',
    )
    parser.add_argument(
        '--version',
        action='version',
        version=VERSION,
    )
    parser.add_argument(
        "-c", "--config",
        action="store",
        default=None,
        dest="configfile",
        help='Use specified configuration file,'
        ' "default" will load the system default config.'
    )
    parser.add_argument(
        "-s", "--socket",
        action="store",
        default=None,
        dest="socket",
        help='Path to Qtile comms socket.'
    )
    parser.add_argument(
        "-n", "--no-spawn",
        action="store_true",
        default=False,
        dest="no_spawn",
        help='Avoid spawning apps. (Used for restart)'
    )
    parser.add_argument(
        '-l', '--log-level',
        default='WARNING',
        dest='log_level',
        choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
        help='Set qtile log level'
    )
    parser.add_argument(
        '--with-state',
        default=None,
        dest='state',
        help='Pickled QtileState object (typically used only internally)',
    )
    options = parser.parse_args()
    log_level = getattr(logging, options.log_level)
    init_log(log_level=log_level)

    try:
        config = confreader.File(options.configfile, is_restart=options.no_spawn)
    except Exception as e:
        logger.exception('Error while reading config file (%s)', e)
        raise
    # XXX: the import is here becouse we need to call init_log
    # before start importing stuff
    from libqtile import manager
    try:
        return manager.Qtile(
            config,
            fname=options.socket,
            no_spawn=options.no_spawn,
            state=options.state,
        )
    except:
        logger.exception('Qtile crashed during startup')
        raise
示例#55
0
文件: qtile.py 项目: cortesi/qtile
def make_qtile():
    from argparse import ArgumentParser
    parser = ArgumentParser(
        description='A full-featured, pure-Python tiling window manager.',
        prog='qtile',
    )
    parser.add_argument(
        '--version',
        action='version',
        version=VERSION,
    )
    parser.add_argument(
        "-c", "--config",
        action="store",
        default=path.expanduser(path.join(
            getenv('XDG_CONFIG_HOME', '~/.config'), 'qtile', 'config.py')),
        dest="configfile",
        help='Use the specified configuration file',
    )
    parser.add_argument(
        "-s", "--socket",
        action="store",
        default=None,
        dest="socket",
        help='Path to Qtile comms socket.'
    )
    parser.add_argument(
        "-n", "--no-spawn",
        action="store_true",
        default=False,
        dest="no_spawn",
        help='Avoid spawning apps. (Used for restart)'
    )
    parser.add_argument(
        '-l', '--log-level',
        default='WARNING',
        dest='log_level',
        choices=('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'),
        help='Set qtile log level'
    )
    parser.add_argument(
        '--with-state',
        default=None,
        dest='state',
        help='Pickled QtileState object (typically used only internally)',
    )
    options = parser.parse_args()
    log_level = getattr(logging, options.log_level)
    init_log(log_level=log_level)

    try:
        config = confreader.Config.from_file(options.configfile)
    except Exception as e:
        logger.exception('Error while reading config file (%s)', e)
        config = confreader.Config()
        from libqtile.widget import TextBox
        widgets = config.screens[0].bottom.widgets
        widgets.insert(0, TextBox('Config Err!'))
    # XXX: the import is here because we need to call init_log
    # before start importing stuff
    from libqtile import manager
    return manager.Qtile(
        config,
        fname=options.socket,
        no_spawn=options.no_spawn,
        state=options.state,
    )