flake8: initial fix

Signed-off-by: Filipe Laíns <lains@archlinux.org>
This commit is contained in:
Filipe Laíns 2020-07-02 14:35:04 +01:00 committed by Filipe Laíns
parent de5514aa23
commit 627185079f
35 changed files with 397 additions and 401 deletions

View File

@ -36,9 +36,8 @@ def init_paths():
sys.path[0].encode(sys.getfilesystemencoding()) sys.path[0].encode(sys.getfilesystemencoding())
except UnicodeError: except UnicodeError:
sys.stderr.write( sys.stderr.write('ERROR: Solaar cannot recognize encoding of filesystem path, '
'ERROR: Solaar cannot recognize encoding of filesystem path, this may happen because non UTF-8 characters in the pathname.\n' 'this may happen because non UTF-8 characters in the pathname.\n')
)
sys.exit(1) sys.exit(1)
prefix = _path.normpath(_path.join(_path.realpath(decoded_path), '..')) prefix = _path.normpath(_path.join(_path.realpath(decoded_path), '..'))

View File

@ -20,6 +20,15 @@
from __future__ import absolute_import, division, print_function, unicode_literals from __future__ import absolute_import, division, print_function, unicode_literals
from hidapi.udev import close, enumerate, get_manufacturer, get_product, get_serial, monitor_glib, open, open_path, read, write from hidapi.udev import close # noqa: F401
from hidapi.udev import enumerate # noqa: F401
from hidapi.udev import get_manufacturer # noqa: F401
from hidapi.udev import get_product # noqa: F401
from hidapi.udev import get_serial # noqa: F401
from hidapi.udev import monitor_glib # noqa: F401
from hidapi.udev import open # noqa: F401
from hidapi.udev import open_path # noqa: F401
from hidapi.udev import read # noqa: F401
from hidapi.udev import write # noqa: F401
__version__ = '0.9' __version__ = '0.9'

View File

@ -45,15 +45,15 @@ start_time = time.time()
strhex = lambda d: hexlify(d).decode('ascii').upper() strhex = lambda d: hexlify(d).decode('ascii').upper()
try: try:
unicode unicode # noqa: F821
# this is certanly Python 2 # this is certanly Python 2
is_string = lambda d: isinstance(d, unicode) is_string = lambda d: isinstance(d, unicode) # noqa: F821
# no easy way to distinguish between b'' and '' :( # no easy way to distinguish between b'' and '' :(
# or (isinstance(d, str) \ # or (isinstance(d, str) \
# and not any((chr(k) in d for k in range(0x00, 0x1F))) \ # and not any((chr(k) in d for k in range(0x00, 0x1F))) \
# and not any((chr(k) in d for k in range(0x80, 0xFF))) \ # and not any((chr(k) in d for k in range(0x80, 0xFF))) \
# ) # )
except: except Exception:
# this is certanly Python 3 # this is certanly Python 3
# In Py3, unicode and str are equal (the unicode object does not exist) # In Py3, unicode and str are equal (the unicode object does not exist)
is_string = lambda d: isinstance(d, str) is_string = lambda d: isinstance(d, str)
@ -225,7 +225,7 @@ def main():
'.hidconsole-history') '.hidconsole-history')
try: try:
readline.read_history_file(args.history) readline.read_history_file(args.history)
except: except Exception:
# file may not exist yet # file may not exist yet
pass pass

View File

@ -195,7 +195,7 @@ def monitor_glib(callback, *device_filters):
GLib.io_add_watch(m, GLib.PRIORITY_LOW, GLib.IO_IN, GLib.io_add_watch(m, GLib.PRIORITY_LOW, GLib.IO_IN,
_process_udev_event, callback, device_filters) _process_udev_event, callback, device_filters)
# print ("did io_add_watch with priority") # print ("did io_add_watch with priority")
except: except Exception:
GLib.io_add_watch(m, GLib.IO_IN, _process_udev_event, callback, GLib.io_add_watch(m, GLib.IO_IN, _process_udev_event, callback,
device_filters) device_filters)
# print ("did io_add_watch") # print ("did io_add_watch")

View File

@ -33,11 +33,11 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import logging import logging
from . import listener, status from . import listener, status # noqa: F401
from .base import DeviceUnreachable, NoReceiver, NoSuchDevice from .base import DeviceUnreachable, NoReceiver, NoSuchDevice # noqa: F401
from .common import strhex from .common import strhex # noqa: F401
from .hidpp20 import FeatureCallError, FeatureNotSupported from .hidpp20 import FeatureCallError, FeatureNotSupported # noqa: F401
from .receiver import PairedDevice, Receiver from .receiver import PairedDevice, Receiver # noqa: F401
_DEBUG = logging.DEBUG _DEBUG = logging.DEBUG
_log = logging.getLogger(__name__) _log = logging.getLogger(__name__)

View File

@ -147,7 +147,7 @@ def close(handle):
handle.close() handle.close()
# _log.info("closed receiver handle %r", handle) # _log.info("closed receiver handle %r", handle)
return True return True
except: except Exception:
# _log.exception("closing receiver handle %r", handle) # _log.exception("closing receiver handle %r", handle)
pass pass
@ -272,7 +272,7 @@ def _skip_incoming(handle, ihandle, notifications_hook):
if data: if data:
if check_message(data): # only process messages that pass check if check_message(data): # only process messages that pass check
report_id = ord(data[:1]) # report_id = ord(data[:1])
if notifications_hook: if notifications_hook:
n = make_notification(ord(data[1:2]), data[2:]) n = make_notification(ord(data[1:2]), data[2:])
if n: if n:
@ -299,13 +299,13 @@ def make_notification(devnumber, data):
address = ord(data[1:2]) address = ord(data[1:2])
if ( if (
# standard HID++ 1.0 notification, SubId may be 0x40 - 0x7F # standard HID++ 1.0 notification, SubId may be 0x40 - 0x7F
(sub_id >= 0x40) or (sub_id >= 0x40) or # noqa: E131
# custom HID++1.0 battery events, where SubId is 0x07/0x0D # custom HID++1.0 battery events, where SubId is 0x07/0x0D
(sub_id in (0x07, 0x0D) and len(data) == 5 and data[4:5] == b'\x00') or (sub_id in (0x07, 0x0D) and len(data) == 5 and data[4:5] == b'\x00') or
# custom HID++1.0 illumination event, where SubId is 0x17 # custom HID++1.0 illumination event, where SubId is 0x17
(sub_id == 0x17 and len(data) == 5) or (sub_id == 0x17 and len(data) == 5) or
# HID++ 2.0 feature notifications have the SoftwareID 0 # HID++ 2.0 feature notifications have the SoftwareID 0
(address & 0x0F == 0x00)): (address & 0x0F == 0x00)): # noqa: E129
return _HIDPP_Notification(devnumber, sub_id, address, data[2:]) return _HIDPP_Notification(devnumber, sub_id, address, data[2:])

View File

@ -22,19 +22,19 @@
from __future__ import absolute_import, division, print_function, unicode_literals from __future__ import absolute_import, division, print_function, unicode_literals
_DRIVER = ('hid-generic', 'generic-usb', 'logitech-djreceiver')
# max_devices is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to 1 # max_devices is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to 1
# may_unpair is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to False # may_unpair is only used for receivers that do not support reading from _R.receiver_info offset 0x03, default to False
## should this last be changed so that may_unpair is used for all receivers? writing to _R.receiver_pairing doesn't seem right ## should this last be changed so that may_unpair is used for all receivers? writing to _R.receiver_pairing doesn't seem right
# re_pairs determines whether a receiver pairs by replacing existing pairings, default to False # re_pairs determines whether a receiver pairs by replacing existing pairings, default to False
## currently only one receiver is so marked - should there be more? ## currently only one receiver is so marked - should there be more?
_DRIVER = ('hid-generic', 'generic-usb', 'logitech-djreceiver')
_unifying_receiver = lambda product_id: { _unifying_receiver = lambda product_id: {
'vendor_id': 0x046d, 'vendor_id': 0x046d,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 2, 'usb_interface': 2,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Unifying Receiver' 'name': 'Unifying Receiver'
} }
@ -42,7 +42,7 @@ _nano_receiver = lambda product_id: {
'vendor_id': 0x046d, 'vendor_id': 0x046d,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 1, 'usb_interface': 1,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Nano Receiver', 'name': 'Nano Receiver',
'may_unpair': False, 'may_unpair': False,
're_pairs': True 're_pairs': True
@ -52,7 +52,7 @@ _nano_receiver_max2 = lambda product_id: {
'vendor_id': 0x046d, 'vendor_id': 0x046d,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 1, 'usb_interface': 1,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Nano Receiver', 'name': 'Nano Receiver',
'max_devices': 2, 'max_devices': 2,
'may_unpair': False, 'may_unpair': False,
@ -63,7 +63,7 @@ _nano_receiver_maxn = lambda product_id, max: {
'vendor_id': 0x046d, 'vendor_id': 0x046d,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 1, 'usb_interface': 1,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Nano Receiver', 'name': 'Nano Receiver',
'max_devices': max, 'max_devices': max,
'may_unpair': False, 'may_unpair': False,
@ -74,7 +74,7 @@ _lenovo_receiver = lambda product_id: {
'vendor_id': 0x17ef, 'vendor_id': 0x17ef,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 1, 'usb_interface': 1,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Nano Receiver' 'name': 'Nano Receiver'
} }
@ -82,7 +82,7 @@ _lightspeed_receiver = lambda product_id: {
'vendor_id': 0x046d, 'vendor_id': 0x046d,
'product_id': product_id, 'product_id': product_id,
'usb_interface': 2, 'usb_interface': 2,
'hid_driver': _DRIVER, 'hid_driver': _DRIVER, # noqa: F821
'name': 'Lightspeed Receiver' 'name': 'Lightspeed Receiver'
} }

View File

@ -26,20 +26,20 @@ from collections import namedtuple
from struct import pack, unpack from struct import pack, unpack
try: try:
unicode unicode # noqa: F821
# if Python2, unicode_literals will mess our first (un)pack() argument # if Python2, unicode_literals will mess our first (un)pack() argument
_pack_str = pack _pack_str = pack
_unpack_str = unpack _unpack_str = unpack
pack = lambda x, *args: _pack_str(str(x), *args) pack = lambda x, *args: _pack_str(str(x), *args)
unpack = lambda x, *args: _unpack_str(str(x), *args) unpack = lambda x, *args: _unpack_str(str(x), *args)
is_string = lambda d: isinstance(d, unicode) or isinstance(d, str) is_string = lambda d: isinstance(d, unicode) or isinstance(d, str) # noqa: F821
# no easy way to distinguish between b'' and '' :( # no easy way to distinguish between b'' and '' :(
# or (isinstance(d, str) \ # or (isinstance(d, str) \
# and not any((chr(k) in d for k in range(0x00, 0x1F))) \ # and not any((chr(k) in d for k in range(0x00, 0x1F))) \
# and not any((chr(k) in d for k in range(0x80, 0xFF))) \ # and not any((chr(k) in d for k in range(0x80, 0xFF))) \
# ) # )
except: except Exception:
# this is certanly Python 3 # this is certanly Python 3
# In Py3, unicode and str are equal (the unicode object does not exist) # In Py3, unicode and str are equal (the unicode object does not exist)
is_string = lambda d: isinstance(d, str) is_string = lambda d: isinstance(d, str)
@ -119,7 +119,8 @@ class NamedInts(object):
self.__dict__ = values self.__dict__ = values
self._values = sorted(list(values.values())) self._values = sorted(list(values.values()))
self._indexed = {int(v): v for v in self._values} self._indexed = {int(v): v for v in self._values}
# assert len(values) == len(self._indexed), "(%d) %r\n=> (%d) %r" % (len(values), values, len(self._indexed), self._indexed) # assert len(values) == len(self._indexed)
# "(%d) %r\n=> (%d) %r" % (len(values), values, len(self._indexed), self._indexed)
self._fallback = None self._fallback = None
@classmethod @classmethod

View File

@ -41,7 +41,8 @@ del getLogger
# #
# <FeaturesSupported.xml sed '/LD_FID_/{s/.*LD_FID_/\t/;s/"[ \t]*Id="/=/;s/" \/>/,/p}' | sort -t= -k2 # <FeaturesSupported.xml sed '/LD_FID_/{s/.*LD_FID_/\t/;s/"[ \t]*Id="/=/;s/" \/>/,/p}' | sort -t= -k2
# additional features names taken from https://github.com/cvuchener/hidpp and https://github.com/Logitech/cpg-docs/tree/master/hidpp20 # additional features names taken from https://github.com/cvuchener/hidpp and
# https://github.com/Logitech/cpg-docs/tree/master/hidpp20
"""Possible features available on a Logitech device. """Possible features available on a Logitech device.
A particular device might not support all these features, and may support other A particular device might not support all these features, and may support other
@ -414,8 +415,8 @@ class KeysArray(object):
remapped = key remapped = key
except Exception: except Exception:
remapped = key remapped = key
remap_key = key # remap_key = key
remap_flag = 0 # remap_flag = 0
remapped_text = special_keys.CONTROL[remapped] remapped_text = special_keys.CONTROL[remapped]
self.keys[index] = _ReprogrammableKeyInfoV4( self.keys[index] = _ReprogrammableKeyInfoV4(
@ -582,10 +583,8 @@ def decipher_voltage(voltage_report):
charge_lvl = CHARGE_LEVEL.critical charge_lvl = CHARGE_LEVEL.critical
if _log.isEnabledFor(_DEBUG): if _log.isEnabledFor(_DEBUG):
_log.debug( _log.debug('device ???, battery voltage %d mV, charging = %s, charge status %d = %s, charge level %s, charge type %s',
'device %d, battery voltage %d mV, charging = %s, charge status %d = %s, charge level %s, charge type %s', voltage, status, (flags & 0x03), charge_sts, charge_lvl, charge_type)
device.number, voltage, status, (flags & 0x03), charge_sts,
charge_lvl, charge_type)
return charge_lvl, status, voltage, charge_sts, charge_type return charge_lvl, status, voltage, charge_sts, charge_type
@ -635,9 +634,8 @@ def get_hi_res_scrolling_info(device):
def get_pointer_speed_info(device): def get_pointer_speed_info(device):
pointer_speed_info = feature_request(device, FEATURE.POINTER_SPEED) pointer_speed_info = feature_request(device, FEATURE.POINTER_SPEED)
if pointer_speed_info: if pointer_speed_info:
pointer_speed_hi, pointer_speed_lo = _unpack('!BB', pointer_speed_hi, pointer_speed_lo = _unpack('!BB', pointer_speed_info[:2])
pointer_speed_info[:2]) # if pointer_speed_lo > 0:
#if pointer_speed_lo > 0:
# pointer_speed_lo = pointer_speed_lo # pointer_speed_lo = pointer_speed_lo
return pointer_speed_hi + pointer_speed_lo / 256 return pointer_speed_hi + pointer_speed_lo / 256

View File

@ -24,10 +24,10 @@ from __future__ import absolute_import, division, print_function, unicode_litera
import gettext as _gettext import gettext as _gettext
try: try:
unicode unicode # noqa: F821
_ = lambda x: _gettext.gettext(x).decode('UTF-8') _ = lambda x: _gettext.gettext(x).decode('UTF-8')
ngettext = lambda *x: _gettext.ngettext(*x).decode('UTF-8') ngettext = lambda *x: _gettext.ngettext(*x).decode('UTF-8')
except: except Exception:
_ = _gettext.gettext _ = _gettext.gettext
ngettext = _gettext.ngettext ngettext = _gettext.ngettext

View File

@ -99,7 +99,7 @@ class _ThreadedHandle(object):
if self._local: if self._local:
try: try:
return self._local.handle return self._local.handle
except: except Exception:
return self._open() return self._open()
__int__ = __index__ __int__ = __index__
@ -193,7 +193,7 @@ class EventsListener(_threading.Thread):
# _log.debug("%s: processing %s", self.receiver, n) # _log.debug("%s: processing %s", self.receiver, n)
try: try:
self._notifications_callback(n) self._notifications_callback(n)
except: except Exception:
_log.exception('processing %s', n) _log.exception('processing %s', n)
# elif self.tick_period: # elif self.tick_period:

View File

@ -589,5 +589,5 @@ class Receiver(object):
_log.exception('open %s', device_info) _log.exception('open %s', device_info)
if e.errno == _errno.EACCES: if e.errno == _errno.EACCES:
raise raise
except: except Exception:
_log.exception('open %s', device_info) _log.exception('open %s', device_info)

View File

@ -23,7 +23,6 @@ import math
from copy import copy as _copy from copy import copy as _copy
from logging import DEBUG as _DEBUG from logging import DEBUG as _DEBUG
from logging import INFO as _INFO
from logging import getLogger from logging import getLogger
from .common import NamedInt as _NamedInt from .common import NamedInt as _NamedInt
@ -220,7 +219,7 @@ class Settings(Setting):
if self._device.online: if self._device.online:
reply_map = {} reply_map = {}
for key, value in self._validator.choices.items(): for key in self._validator.choices:
reply = self._rw.read(self._device, key) reply = self._rw.read(self._device, key)
if reply: if reply:
# keys are ints, because that is what the device uses, # keys are ints, because that is what the device uses,
@ -666,7 +665,7 @@ class BitFieldValidator(object):
r = _bytes2int(reply_bytes[:self.byte_count]) r = _bytes2int(reply_bytes[:self.byte_count])
value = {str(int(k)): False for k in self.options} value = {str(int(k)): False for k in self.options}
m = 1 m = 1
for i in range(8 * self.byte_count): for _ in range(8 * self.byte_count):
if m in self.options: if m in self.options:
value[str(int(m))] = bool(r & m) value[str(int(m))] = bool(r & m)
m <<= 1 m <<= 1

View File

@ -28,7 +28,6 @@ from . import hidpp20 as _hidpp20
from . import special_keys as _special_keys from . import special_keys as _special_keys
from .common import NamedInt as _NamedInt from .common import NamedInt as _NamedInt
from .common import NamedInts as _NamedInts from .common import NamedInts as _NamedInts
from .common import ReprogrammableKeyInfoV4 as _ReprogrammableKeyInfoV4
from .common import bytes2int as _bytes2int from .common import bytes2int as _bytes2int
from .common import int2bytes as _int2bytes from .common import int2bytes as _int2bytes
from .common import unpack as _unpack from .common import unpack as _unpack
@ -449,7 +448,8 @@ def _feature_k375s_fn_swap():
device_kind=(_DK.keyboard, )) device_kind=(_DK.keyboard, ))
# FIXME: This will enable all supported backlight settings, we should allow the users to select which settings they want to enable. # FIXME: This will enable all supported backlight settings,
# we should allow the users to select which settings they want to enable.
def _feature_backlight2(): def _feature_backlight2():
return feature_toggle(_BACKLIGHT[0], return feature_toggle(_BACKLIGHT[0],
_F.BACKLIGHT2, _F.BACKLIGHT2,
@ -733,7 +733,7 @@ def check_feature_settings(device, already_known):
:param featureId: the numeric Feature ID for this setting implementation :param featureId: the numeric Feature ID for this setting implementation
:param featureFn: the function for this setting implementation :param featureFn: the function for this setting implementation
""" """
if not featureId in device.features: if featureId not in device.features:
return return
if any(s.name == name for s in already_known): if any(s.name == name for s in already_known):
return return
@ -749,7 +749,7 @@ def check_feature_settings(device, already_known):
_log.error('check_feature[%s] inconsistent feature %s', featureId, _log.error('check_feature[%s] inconsistent feature %s', featureId,
reason) reason)
for name, featureId, featureFn, _, _ in _SETTINGS_TABLE: for name, featureId, featureFn, __, __ in _SETTINGS_TABLE:
if featureId and featureFn: if featureId and featureFn:
check_feature(name, featureId, featureFn) check_feature(name, featureId, featureFn)
return True return True

View File

@ -194,7 +194,8 @@ CONTROL = _NamedInts(
Fn_Left_Click=0x00B7, # from K400 Plus Fn_Left_Click=0x00B7, # from K400 Plus
# https://docs.google.com/document/u/0/d/1YvXICgSe8BcBAuMr4Xu_TutvAxaa-RnGfyPFWBWzhkc/export?format=docx # https://docs.google.com/document/u/0/d/1YvXICgSe8BcBAuMr4Xu_TutvAxaa-RnGfyPFWBWzhkc/export?format=docx
# Extract to csv. Eliminate extra linefeeds and spaces. # Extract to csv. Eliminate extra linefeeds and spaces.
# awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("/","__",$2); gsub(" -","_Down",$2); gsub(" \\+","_Up",$2); gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < controls.cvs # awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("/","__",$2); gsub(" -","_Down",$2);
# gsub(" \\+","_Up",$2); gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < controls.cvs
Second_Left_Click=0x00B8, # Second_LClick / on K400 Plus Second_Left_Click=0x00B8, # Second_LClick / on K400 Plus
Fn_Second_Left_Click=0x00B9, # Fn_Second_LClick Fn_Second_Left_Click=0x00B9, # Fn_Second_LClick
MultiPlatform_App_Switch=0x00BA, MultiPlatform_App_Switch=0x00BA,
@ -415,7 +416,8 @@ TASK = _NamedInts(
ShowUI=0x0092, ShowUI=0x0092,
# https://docs.google.com/document/d/1Dpx_nWRQAZox_zpZ8SNc9nOkSDE9svjkghOCbzopabc/edit # https://docs.google.com/document/d/1Dpx_nWRQAZox_zpZ8SNc9nOkSDE9svjkghOCbzopabc/edit
# Extract to csv. Eliminate extra linefeeds and spaces. Turn / into __ and space into _ # Extract to csv. Eliminate extra linefeeds and spaces. Turn / into __ and space into _
# awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("_-","_Down",$2); gsub("_\\+","_Up",$2); gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < tasks.csv > tasks.py # awk -F, '/0x/{gsub(" \\+ ","_",$2); gsub("_-","_Down",$2); gsub("_\\+","_Up",$2);
# gsub("[()\"-]","",$2); gsub(" ","_",$2); printf("\t%s=0x%04X,\n", $2, $1)}' < tasks.csv > tasks.py
Switch_Presentation__Switch_Screen=0x0093, # on K400 Plus Switch_Presentation__Switch_Screen=0x0093, # on K400 Plus
Minimize_Window=0x0094, Minimize_Window=0x0094,
Maximize_Window=0x0095, # on K400 Plus Maximize_Window=0x0095, # on K400 Plus

View File

@ -177,7 +177,8 @@ class DeviceStatus(dict):
light_level = self.get(KEYS.LIGHT_LEVEL) light_level = self.get(KEYS.LIGHT_LEVEL)
if light_level is not None: if light_level is not None:
if comma: yield ', ' if comma:
yield ', '
yield _('Lighting: %(level)s lux') % {'level': light_level} yield _('Lighting: %(level)s lux') % {'level': light_level}
return ''.join(i for i in _items()) return ''.join(i for i in _items())
@ -352,7 +353,7 @@ class DeviceStatus(dict):
if battery is not None: if battery is not None:
self[KEYS.BATTERY_LEVEL] = battery self[KEYS.BATTERY_LEVEL] = battery
if self.updated == 0 and active == True: if self.updated == 0 and active is True:
# if the device is active on the very first status notification, # if the device is active on the very first status notification,
# (meaning just when the program started or a new receiver was just # (meaning just when the program started or a new receiver was just
# detected), pop-up a notification about it # detected), pop-up a notification about it

View File

@ -139,11 +139,12 @@ def _find_device(receivers, name):
if len(name) == 1: if len(name) == 1:
try: try:
number = int(name) number = int(name)
except: except Exception:
pass pass
else: else:
assert not (number < 0) assert not (number < 0)
if number > 6: number = None if number > 6:
number = None
for r in receivers: for r in receivers:
if number and number <= r.max_devices: if number and number <= r.max_devices:
@ -168,7 +169,7 @@ def run(cli_args=None, hidraw_path=None):
args = _cli_parser.parse_args() args = _cli_parser.parse_args()
# Python 3 has an undocumented 'feature' that breaks parsing empty args # Python 3 has an undocumented 'feature' that breaks parsing empty args
# http://bugs.python.org/issue16308 # http://bugs.python.org/issue16308
if not 'cmd' in args: if 'cmd' not in args:
_cli_parser.print_usage(_sys.stderr) _cli_parser.print_usage(_sys.stderr)
_sys.stderr.write('%s: error: too few arguments\n' % NAME.lower()) _sys.stderr.write('%s: error: too few arguments\n' % NAME.lower())
_sys.exit(2) _sys.exit(2)
@ -183,11 +184,10 @@ def run(cli_args=None, hidraw_path=None):
from importlib import import_module from importlib import import_module
m = import_module('.' + action, package=__name__) m = import_module('.' + action, package=__name__)
m.run(c, args, _find_receiver, _find_device) m.run(c, args, _find_receiver, _find_device)
except AssertionError as e: except AssertionError:
from traceback import extract_tb from traceback import extract_tb
tb_last = extract_tb(_sys.exc_info()[2])[-1] tb_last = extract_tb(_sys.exc_info()[2])[-1]
_sys.exit('%s: assertion failed: %s line %d' % _sys.exit('%s: assertion failed: %s line %d' % (NAME.lower(), tb_last[0], tb_last[1]))
(NAME.lower(), tb_last[0], tb_last[1])) except Exception:
except Exception as e:
from traceback import format_exc from traceback import format_exc
_sys.exit('%s: error: %s' % (NAME.lower(), format_exc())) _sys.exit('%s: error: %s' % (NAME.lower(), format_exc()))

View File

@ -84,7 +84,7 @@ def run(receivers, args, find_receiver, find_device):
value = args.value value = args.value
try: try:
value = bool(int(value)) value = bool(int(value))
except: except Exception:
if value.lower() in ('true', 'yes', 'on', 't', 'y'): if value.lower() in ('true', 'yes', 'on', 't', 'y'):
value = True value = True
elif value.lower() in ('false', 'no', 'off', 'f', 'n'): elif value.lower() in ('false', 'no', 'off', 'f', 'n'):

View File

@ -19,12 +19,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals from __future__ import absolute_import, division, print_function, unicode_literals
from time import time as _timestamp
from logitech_receiver import base as _base
from logitech_receiver import hidpp10 as _hidpp10 from logitech_receiver import hidpp10 as _hidpp10
from logitech_receiver import notifications as _notifications
from logitech_receiver import status as _status
from logitech_receiver.common import strhex as _strhex from logitech_receiver.common import strhex as _strhex
from solaar.cli.show import _print_receiver from solaar.cli.show import _print_receiver

View File

@ -46,7 +46,7 @@ def _load():
try: try:
with open(_file_path, 'r') as config_file: with open(_file_path, 'r') as config_file:
loaded_configuration = _json_load(config_file) loaded_configuration = _json_load(config_file)
except: except Exception:
_log.error('failed to load from %s', _file_path) _log.error('failed to load from %s', _file_path)
# loaded_configuration.update(_configuration) # loaded_configuration.update(_configuration)
@ -70,7 +70,7 @@ def save():
if not _path.isdir(dirname): if not _path.isdir(dirname):
try: try:
_os.makedirs(dirname) _os.makedirs(dirname)
except: except Exception:
_log.error('failed to create %s', dirname) _log.error('failed to create %s', dirname)
return False return False
@ -87,7 +87,7 @@ def save():
if _log.isEnabledFor(_INFO): if _log.isEnabledFor(_INFO):
_log.info('saved %s to %s', _configuration, _file_path) _log.info('saved %s to %s', _configuration, _file_path)
return True return True
except: except Exception:
_log.error('failed to save to %s', _file_path) _log.error('failed to save to %s', _file_path)

View File

@ -129,7 +129,8 @@ def main():
signal.signal(signal.SIGINT, signal.SIG_DFL) signal.signal(signal.SIGINT, signal.SIG_DFL)
args = _parse_arguments() args = _parse_arguments()
if not args: return if not args:
return
if args.action: if args.action:
# if any argument, run comandline and exit # if any argument, run comandline and exit
return _cli.run(args.action, args.hidraw_path) return _cli.run(args.action, args.hidraw_path)
@ -149,9 +150,8 @@ def main():
_upower.watch(lambda: listener.ping_all(True)) _upower.watch(lambda: listener.ping_all(True))
# main UI event loop # main UI event loop
ui.run_loop(listener.start_all, listener.stop_all, ui.run_loop(listener.start_all, listener.stop_all, args.window != 'only', args.window != 'hide')
args.window != 'only', args.window != 'hide') except Exception:
except Exception as e:
import sys import sys
from traceback import format_exc from traceback import format_exc
sys.exit('%s: error: %s' % (NAME.lower(), format_exc())) sys.exit('%s: error: %s' % (NAME.lower(), format_exc()))

View File

@ -63,9 +63,9 @@ _gettext.textdomain(_LOCALE_DOMAIN)
_gettext.install(_LOCALE_DOMAIN) _gettext.install(_LOCALE_DOMAIN)
try: try:
unicode unicode # noqa: F821
_ = lambda x: _gettext.gettext(x).decode('UTF-8') _ = lambda x: _gettext.gettext(x).decode('UTF-8')
ngettext = lambda *x: _gettext.ngettext(*x).decode('UTF-8') ngettext = lambda *x: _gettext.ngettext(*x).decode('UTF-8')
except: except Exception:
_ = _gettext.gettext _ = _gettext.gettext
ngettext = _gettext.ngettext ngettext = _gettext.ngettext

View File

@ -90,7 +90,7 @@ class ReceiverListener(_listener.EventsListener):
self.receiver.status[ self.receiver.status[
_status.KEYS.NOTIFICATION_FLAGS] = notification_flags _status.KEYS.NOTIFICATION_FLAGS] = notification_flags
self.receiver.notify_devices() self.receiver.notify_devices()
self._status_changed(self.receiver) #, _status.ALERT.NOTIFICATION) self._status_changed(self.receiver) # , _status.ALERT.NOTIFICATION)
def has_stopped(self): def has_stopped(self):
r, self.receiver = self.receiver, None r, self.receiver = self.receiver, None
@ -106,9 +106,9 @@ class ReceiverListener(_listener.EventsListener):
if r: if r:
try: try:
r.close() r.close()
except: except Exception:
_log.exception('closing receiver %s' % r.path) _log.exception('closing receiver %s' % r.path)
self.status_changed_callback(r) #, _status.ALERT.NOTIFICATION) self.status_changed_callback(r) # , _status.ALERT.NOTIFICATION)
# def tick(self, timestamp): # def tick(self, timestamp):
# if not self.tick_period: # if not self.tick_period:
@ -370,10 +370,11 @@ def _process_receiver_event(action, device_info):
# (It would be easier to use pylibacl but adding the pylibacl dependencies # (It would be easier to use pylibacl but adding the pylibacl dependencies
# for this special case is not good.) # for this special case is not good.)
try: try:
import subprocess, re import subprocess
import re
output = subprocess.check_output( output = subprocess.check_output(
['/usr/bin/getfacl', '-p', device_info.path]) ['/usr/bin/getfacl', '-p', device_info.path])
if not re.search(b'user:.+:', output): if not re.search(b'user:.+:', output):
_error_callback('permissions', device_info.path) _error_callback('permissions', device_info.path)
except: except Exception:
_error_callback('permissions', device_info.path) _error_callback('permissions', device_info.path)

View File

@ -65,7 +65,7 @@ class TaskRunner(_Thread):
assert function assert function
try: try:
function(*args, **kwargs) function(*args, **kwargs)
except: except Exception:
_log.exception('calling %s', function) _log.exception('calling %s', function)
if _log.isEnabledFor(_DEBUG): if _log.isEnabledFor(_DEBUG):

View File

@ -47,14 +47,12 @@ def _error_dialog(reason, object):
if reason == 'permissions': if reason == 'permissions':
title = _('Permissions error') title = _('Permissions error')
text = _('Found a Logitech Receiver (%s), but did not have permission to open it.') % object + \ text = (_('Found a Logitech Receiver (%s), but did not have permission to open it.') % object + '\n\n' +
'\n\n' + \ _("If you've just installed Solaar, try removing the receiver and plugging it back in."))
_("If you've just installed Solaar, try removing the receiver and plugging it back in.")
elif reason == 'unpair': elif reason == 'unpair':
title = _('Unpairing failed') title = _('Unpairing failed')
text = _('Failed to unpair %{device} from %{receiver}.').format(device=object.name, receiver=object.receiver.name) + \ text = (_('Failed to unpair %{device} from %{receiver}.').format(device=object.name, receiver=object.receiver.name) +
'\n\n' + \ '\n\n' + _('The receiver returned an error, with no further details.'))
_('The receiver returned an error, with no further details.')
else: else:
raise Exception("ui.error_dialog: don't know how to handle (%s, %s)", raise Exception("ui.error_dialog: don't know how to handle (%s, %s)",
reason, object) reason, object)

View File

@ -61,7 +61,7 @@ def _create():
# gtk3 < ~3.6.4 has incorrect gi bindings # gtk3 < ~3.6.4 has incorrect gi bindings
import logging import logging
logging.exception('failed to fully create the about dialog') logging.exception('failed to fully create the about dialog')
except: except Exception:
# the Gtk3 version may be too old, and the function does not exist # the Gtk3 version may be too old, and the function does not exist
import logging import logging
logging.exception('failed to fully create the about dialog') logging.exception('failed to fully create the about dialog')

View File

@ -109,6 +109,6 @@ def unpair(window, device):
try: try:
del receiver[device_number] del receiver[device_number]
except: except Exception:
# _log.exception("unpairing %s", device) # _log.exception("unpairing %s", device)
error_dialog('unpair', device) error_dialog('unpair', device)

View File

@ -75,7 +75,7 @@ def _write_async_key_value(setting, key, value, sbox):
def _create_toggle_control(setting): def _create_toggle_control(setting):
def _switch_notify(switch, _ignore, s): def _switch_notify(switch, _ignore, s):
if switch.get_sensitive(): if switch.get_sensitive():
_write_async(s, switch.get_active() == True, switch.get_parent()) _write_async(s, switch.get_active() is True, switch.get_parent())
c = Gtk.Switch() c = Gtk.Switch()
c.connect('notify::active', _switch_notify, setting) c.connect('notify::active', _switch_notify, setting)

View File

@ -60,7 +60,7 @@ if available:
_log.info('starting desktop notifications') _log.info('starting desktop notifications')
try: try:
return Notify.init(NAME) return Notify.init(NAME)
except: except Exception:
_log.exception('initializing desktop notifications') _log.exception('initializing desktop notifications')
available = False available = False
return available and Notify.is_initted() return available and Notify.is_initted()
@ -90,8 +90,7 @@ if available:
# we need to use the filename here because the notifications daemon # we need to use the filename here because the notifications daemon
# is an external application that does not know about our icon sets # is an external application that does not know about our icon sets
icon_file = _icons.icon_file(NAME.lower()) if icon is None \ icon_file = _icons.icon_file(NAME.lower()) if icon is None else _icons.icon_file(icon)
else _icons.icon_file(icon)
n.update(NAME, reason, icon_file) n.update(NAME, reason, icon_file)
n.set_urgency(Notify.Urgency.NORMAL) n.set_urgency(Notify.Urgency.NORMAL)
@ -125,8 +124,7 @@ if available:
# we need to use the filename here because the notifications daemon # we need to use the filename here because the notifications daemon
# is an external application that does not know about our icon sets # is an external application that does not know about our icon sets
icon_file = _icons.device_icon_file(dev.name, dev.kind) if icon is None \ icon_file = _icons.device_icon_file(dev.name, dev.kind) if icon is None else _icons.icon_file(icon)
else _icons.icon_file(icon)
n.update(summary, message, icon_file) n.update(summary, message, icon_file)
urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL urgency = Notify.Urgency.LOW if dev.status else Notify.Urgency.NORMAL

View File

@ -184,14 +184,9 @@ def _pairing_succeeded(assistant, receiver, device):
def _check_encrypted(dev): def _check_encrypted(dev):
if assistant.is_drawable(): if assistant.is_drawable():
if device.status.get(_K.LINK_ENCRYPTED) == False: if device.status.get(_K.LINK_ENCRYPTED) is False:
hbox.pack_start( hbox.pack_start(Gtk.Image.new_from_icon_name('security-low', Gtk.IconSize.MENU), False, False, 0)
Gtk.Image.new_from_icon_name('security-low', hbox.pack_start(Gtk.Label(_('The wireless link is not encrypted') + '!'), False, False, 0)
Gtk.IconSize.MENU), False,
False, 0)
hbox.pack_start(
Gtk.Label(_('The wireless link is not encrypted') + '!'),
False, False, 0)
hbox.show_all() hbox.show_all()
else: else:
return True return True

View File

@ -666,8 +666,8 @@ def _update_receiver_panel(receiver, panel, buttons, full=False):
# b._insecure.set_visible(False) # b._insecure.set_visible(False)
buttons._unpair.set_visible(False) buttons._unpair.set_visible(False)
if ( receiver.may_unpair or receiver.re_pairs ) and not is_pairing and \ if (receiver.may_unpair or receiver.re_pairs) and not is_pairing and \
( receiver.remaining_pairings() is None or receiver.remaining_pairings() != 0 ): (receiver.remaining_pairings() is None or receiver.remaining_pairings() != 0):
if not receiver.re_pairs and devices_count >= receiver.max_devices: if not receiver.re_pairs and devices_count >= receiver.max_devices:
paired_devices = tuple(n paired_devices = tuple(n
for n in range(1, receiver.max_devices + 1) for n in range(1, receiver.max_devices + 1)
@ -727,7 +727,7 @@ def _update_device_panel(device, panel, buttons, full=False):
panel._battery._text.set_markup(text) panel._battery._text.set_markup(text)
if is_online: if is_online:
not_secure = device.status.get(_K.LINK_ENCRYPTED) == False not_secure = device.status.get(_K.LINK_ENCRYPTED) is False
if not_secure: if not_secure:
panel._secure._text.set_text(_('not encrypted')) panel._secure._text.set_text(_('not encrypted'))
panel._secure._icon.set_from_icon_name('security-low', panel._secure._icon.set_from_icon_name('security-low',

View File

@ -95,7 +95,7 @@ try:
_log.info( _log.info(
'connected to system dbus, watching for suspend/resume events') 'connected to system dbus, watching for suspend/resume events')
except: except Exception:
# Either: # Either:
# - the dbus library is not available # - the dbus library is not available
# - the system dbus is not running # - the system dbus is not running

View File

@ -9,7 +9,7 @@ except ImportError:
autostart_path = '/etc/xdg/autostart' autostart_path = '/etc/xdg/autostart'
#from solaar import NAME, __version__ # from solaar import NAME, __version__
__version__ = '1.0.2' __version__ = '1.0.2'
NAME = 'Solaar' NAME = 'Solaar'