diff --git a/generate_icons.py b/generate_icons.py index 27caed93..164fc152 100755 --- a/generate_icons.py +++ b/generate_icons.py @@ -83,7 +83,8 @@ def recolor(tree, add) -> None: ET.register_namespace("","http://www.w3.org/2000/svg") for tp in ("sc", "scbt", "fake", "ds4", "hid", "rpad"): # Read svg and parse it - data = open(f"{CICONS}{tp}-0.svg", "r").read() + with open(f"{CICONS}{tp}-0.svg", "r") as file: + data = file.read() # Create recolored images for key in RECOLORS: tree = ET.fromstring(data) diff --git a/scc/cheader.py b/scc/cheader.py index f84319f1..db488ce9 100644 --- a/scc/cheader.py +++ b/scc/cheader.py @@ -82,108 +82,109 @@ def defines(base, include): fname = os.path.normpath(os.path.abspath(os.path.join(base, include))) parsed.add(fname) - lexer = shlex.shlex(open(fname), posix=True) + with open(fname) as file: + lexer = shlex.shlex(file, posix=True) - lexer.whitespace = ' \t\r' - lexer.commenters = '' - lexer.quotes = '"' + lexer.whitespace = ' \t\r' + lexer.commenters = '' + lexer.quotes = '"' - out = OrderedDict() + out = OrderedDict() - def parse_c_comments(lexer, tok, ntok): - if tok != '/' or ntok != '*': - return False - quotes = lexer.quotes - lexer.quotes = '' - while True: - tok = lexer.get_token() - ntok = lexer.get_token() - if tok == '*' and ntok == '/': - lexer.quotes = quotes - break - else: - lexer.push_token(ntok) - return True - - def parse_cpp_comments(lexer, tok, ntok): - if tok != '/' or ntok != '/': - return False - quotes = lexer.quotes - lexer.quotes = '' - while True: - tok = lexer.get_token() - if tok == '\n': - lexer.quotes = quotes - lexer.push_token(tok) - break - return True - - while True: - tok = lexer.get_token() - if not tok or tok == '': - break - ntok = lexer.get_token() - - if parse_c_comments(lexer, tok, ntok): - continue - if parse_cpp_comments(lexer, tok, ntok): - continue - - if tok != '\n' or ntok != '#': - lexer.push_token(ntok) - continue - - tok = lexer.get_token() - if tok == 'define': - name = lexer.get_token() - expr = '' + def parse_c_comments(lexer, tok, ntok): + if tok != '/' or ntok != '*': + return False + quotes = lexer.quotes + lexer.quotes = '' while True: - tok = lexer.get_token() ntok = lexer.get_token() - - if parse_c_comments(lexer, tok, ntok): - continue - if parse_cpp_comments(lexer, tok, ntok): - continue - lexer.push_token(ntok) - - if not tok or tok == '': + if tok == '*' and ntok == '/': + lexer.quotes = quotes break + else: + lexer.push_token(ntok) + return True + + def parse_cpp_comments(lexer, tok, ntok): + if tok != '/' or ntok != '/': + return False + quotes = lexer.quotes + lexer.quotes = '' + while True: + tok = lexer.get_token() if tok == '\n': + lexer.quotes = quotes lexer.push_token(tok) break + return True - if tok in out: - tok = str(out[tok]) - expr = expr + tok + while True: + tok = lexer.get_token() + if not tok or tok == '': + break + ntok = lexer.get_token() - try: - val = eval_expr(expr) - out[name] = val - except (SyntaxError, TypeError): - pass - elif tok == 'include': + if parse_c_comments(lexer, tok, ntok): + continue + if parse_cpp_comments(lexer, tok, ntok): + continue + + if tok != '\n' or ntok != '#': + lexer.push_token(ntok) + continue tok = lexer.get_token() - if tok == '<': - name = '' + if tok == 'define': + name = lexer.get_token() + expr = '' while True: + tok = lexer.get_token() - if tok == '>': + ntok = lexer.get_token() + + if parse_c_comments(lexer, tok, ntok): + continue + if parse_cpp_comments(lexer, tok, ntok): + continue + lexer.push_token(ntok) + + if not tok or tok == '': + break + if tok == '\n': + lexer.push_token(tok) break - name = name + tok + + if tok in out: + tok = str(out[tok]) + expr = expr + tok + + try: + val = eval_expr(expr) + out[name] = val + except (SyntaxError, TypeError): + pass + elif tok == 'include': + + tok = lexer.get_token() + if tok == '<': + name = '' + while True: + tok = lexer.get_token() + if tok == '>': + break + name = name + tok + else: + name = tok + fname = os.path.normpath(os.path.abspath(os.path.join(base, name))) + if os.path.isfile(fname) and not fname in parsed: + parsed.add(fname) + lexer.push_source(open(fname)) else: - name = tok - fname = os.path.normpath(os.path.abspath(os.path.join(base, name))) - if os.path.isfile(fname) and not fname in parsed: - parsed.add(fname) - lexer.push_source(open(fname)) - else: - lexer.push_token(tok) + lexer.push_token(tok) - return out + return out if __name__ == '__main__': diff --git a/scc/device_monitor.py b/scc/device_monitor.py index 354fa778..14afd7b9 100644 --- a/scc/device_monitor.py +++ b/scc/device_monitor.py @@ -245,7 +245,8 @@ def _find_bt_address(syspath: str) -> str | None: """Recursivelly searchs for "input*" subdirectories until "uniq" file is found. Then, returns address from that file.""" uniq = os.path.join(syspath, "uniq") if os.path.exists(uniq): - return open(uniq, "r").read().strip() + with open(uniq, "r") as file: + return file.read().strip() for name in os.listdir(syspath): if name.startswith("input"): path = os.path.join(syspath, name) diff --git a/scc/foreign/vdf.py b/scc/foreign/vdf.py index f32bbf54..e1c6f7cf 100644 --- a/scc/foreign/vdf.py +++ b/scc/foreign/vdf.py @@ -581,7 +581,8 @@ def load(self, filename): May raise ValueError. """ - data = parse_vdf(open(filename, "r")) + with open(filename, "r") as file: + data = parse_vdf(file) self.load_data(data) diff --git a/scc/gui/app.py b/scc/gui/app.py index 23e93205..7919bcb0 100644 --- a/scc/gui/app.py +++ b/scc/gui/app.py @@ -296,11 +296,13 @@ def check(self): # TODO: Maybe not best place to do this try: # Dynamic modules - rawlist = open("/proc/modules", "r").read().split("\n") + with open("/proc/modules", "r") as file: + rawlist = file.read().split("\n") kernel_mods = [ line.split(" ")[0] for line in rawlist ] # Built-in modules release = platform.uname()[2] - rawlist = open("/lib/modules/%s/modules.builtin" % release, "r").read().split("\n") + with open("/lib/modules/%s/modules.builtin" % release, "r") as file: + rawlist = file.read().split("\n") kernel_mods += [ os.path.split(x)[-1].split(".")[0] for x in rawlist ] except Exception: # Maybe running on BSD or Windows... diff --git a/scc/gui/creg/dialog.py b/scc/gui/creg/dialog.py index 4aa0b506..2e3c25c0 100644 --- a/scc/gui/creg/dialog.py +++ b/scc/gui/creg/dialog.py @@ -131,62 +131,63 @@ def load_sdl_mappings(self): log.exception(e) return False - for line in db.readlines(): - if line.startswith(weird_id): - log.info("Loading mappings for '%s' from gamecontrollerdb", weird_id) - log.debug("Buttons: %s", buttons) - log.debug("Axes: %s", axes) - for token in line.strip().split(","): - if ":" in token: - k, v = token.split(":", 1) - k = SDL_TO_SCC_NAMES.get(k, k) - if v.startswith("b") and hasattr(SCButtons, k.upper()): - try: - keycode = buttons[int(v.strip("b"))] - except IndexError: - log.warning("Skipping unknown gamecontrollerdb button->button mapping: '%s'", v) - continue - button = getattr(SCButtons, k.upper()) - self._mappings[keycode] = button - elif v.startswith("b") and k in SDL_AXES: - try: - keycode = buttons[int(v.strip("b"))] - except IndexError: - log.warning("Skipping unknown gamecontrollerdb button->axis mapping: '%s'", v) - continue - log.info("Adding button -> axis mapping for %s", k) - self._mappings[keycode] = self._axis_data[SDL_AXES.index(k)] - self._mappings[keycode].min = STICK_PAD_MIN - self._mappings[keycode].max = STICK_PAD_MAX - elif v.startswith("h") and 16 in axes and 17 in axes: - # Special case for evdev hatswitch - if v == "h0.1" and k == "dpup": - self._mappings[16] = self._axis_data[SDL_AXES.index("dpadx")] - self._mappings[17] = self._axis_data[SDL_AXES.index("dpady")] - elif k in SDL_AXES: - try: - code = axes[int(v.strip("a"))] - except IndexError: - log.warning("Skipping unknown gamecontrollerdb axis: '%s'", v) - continue - self._mappings[code] = self._axis_data[SDL_AXES.index(k)] - elif k in SDL_DPAD and v.startswith("b"): - try: - keycode = buttons[int(v.strip("b"))] - except IndexError: - log.warning("Skipping unknown gamecontrollerdb button->dpad mapping: %s", v) - continue - index, positive = SDL_DPAD[k] - data = DPadEmuData(self._axis_data[index], positive) - self._mappings[keycode] = data - elif k == "platform": - # Not interesting - pass - else: - log.warning("Skipping unknown gamecontrollerdb mapping %s:%s", k, v) - return True - else: - log.debug("Mappings for '%s' not found in gamecontrollerdb", weird_id) + with db: + for line in db.readlines(): + if line.startswith(weird_id): + log.info("Loading mappings for '%s' from gamecontrollerdb", weird_id) + log.debug("Buttons: %s", buttons) + log.debug("Axes: %s", axes) + for token in line.strip().split(","): + if ":" in token: + k, v = token.split(":", 1) + k = SDL_TO_SCC_NAMES.get(k, k) + if v.startswith("b") and hasattr(SCButtons, k.upper()): + try: + keycode = buttons[int(v.strip("b"))] + except IndexError: + log.warning("Skipping unknown gamecontrollerdb button->button mapping: '%s'", v) + continue + button = getattr(SCButtons, k.upper()) + self._mappings[keycode] = button + elif v.startswith("b") and k in SDL_AXES: + try: + keycode = buttons[int(v.strip("b"))] + except IndexError: + log.warning("Skipping unknown gamecontrollerdb button->axis mapping: '%s'", v) + continue + log.info("Adding button -> axis mapping for %s", k) + self._mappings[keycode] = self._axis_data[SDL_AXES.index(k)] + self._mappings[keycode].min = STICK_PAD_MIN + self._mappings[keycode].max = STICK_PAD_MAX + elif v.startswith("h") and 16 in axes and 17 in axes: + # Special case for evdev hatswitch + if v == "h0.1" and k == "dpup": + self._mappings[16] = self._axis_data[SDL_AXES.index("dpadx")] + self._mappings[17] = self._axis_data[SDL_AXES.index("dpady")] + elif k in SDL_AXES: + try: + code = axes[int(v.strip("a"))] + except IndexError: + log.warning("Skipping unknown gamecontrollerdb axis: '%s'", v) + continue + self._mappings[code] = self._axis_data[SDL_AXES.index(k)] + elif k in SDL_DPAD and v.startswith("b"): + try: + keycode = buttons[int(v.strip("b"))] + except IndexError: + log.warning("Skipping unknown gamecontrollerdb button->dpad mapping: %s", v) + continue + index, positive = SDL_DPAD[k] + data = DPadEmuData(self._axis_data[index], positive) + self._mappings[keycode] = data + elif k == "platform": + # Not interesting + pass + else: + log.warning("Skipping unknown gamecontrollerdb mapping %s:%s", k, v) + return True + else: + log.debug("Mappings for '%s' not found in gamecontrollerdb", weird_id) return False diff --git a/scc/gui/global_settings.py b/scc/gui/global_settings.py index 6296ff3f..6c083d6d 100644 --- a/scc/gui/global_settings.py +++ b/scc/gui/global_settings.py @@ -669,7 +669,8 @@ def on_cbOSDStyle_changed(self, cb): color_keys = self.app.config['osk_colors'].keys() + self.app.config['osd_colors'].keys() osd_style = cb.get_model().get_value(cb.get_active_iter(), 0) css_file = os.path.join(get_share_path(), "osd-styles", osd_style) - first_line = open(css_file, "r").read().split("\n")[0] + with open(css_file, "r") as file: + first_line = file.read().split("\n")[0] used_colors = None # None means "all" if "Used colors:" in first_line: used_colors = set(first_line.split(":", 1)[1].strip(" */").split(" ")) diff --git a/scc/gui/icon_chooser.py b/scc/gui/icon_chooser.py index 982f3742..387edc1c 100644 --- a/scc/gui/icon_chooser.py +++ b/scc/gui/icon_chooser.py @@ -176,10 +176,11 @@ def find_license(path, name): licensefile = os.path.join(path, "LICENSES") if not os.path.exists(licensefile): return None - for line in open(licensefile, "r").readlines(): - if line.startswith(name): - if "-" in line: - return line.split("-")[-1].strip("\t\r\n ") + with open(licensefile, "r") as file: + for line in file.readlines(): + if line.startswith(name): + if "-" in line: + return line.split("-")[-1].strip("\t\r\n ") return None diff --git a/scc/gui/importexport/dialog.py b/scc/gui/importexport/dialog.py index 847c37d0..e300181b 100644 --- a/scc/gui/importexport/dialog.py +++ b/scc/gui/importexport/dialog.py @@ -34,7 +34,8 @@ def determine_type(filename): or None if type is not supported. """ try: - f = open(filename, 'rb').read(1024) + with open(filename, 'rb') as file: + f = file.read(1024) except Exception as e: # File not readable log.error(traceback.format_exc()) @@ -54,8 +55,8 @@ def determine_type(filename): if f[0:2] == b"\x1f\x8b": # gzip, hopefully tar.gz try: - tar = tarfile.open(filename, "r:gz") - names = [ x.name for x in tar ] + with tarfile.open(filename, "r:gz") as tar: + names = [ x.name for x in tar ] any_profile = any([ x.endswith(".sccprofile") for x in names ]) if any_profile and "profile-name" in names: return "sccprofile.tar.gz" diff --git a/scc/gui/svg_widget.py b/scc/gui/svg_widget.py index c2598e74..96028d0f 100644 --- a/scc/gui/svg_widget.py +++ b/scc/gui/svg_widget.py @@ -55,7 +55,8 @@ def __init__(self, filename, init_hilighted=True): def set_image(self, filename): - self.current_svg = open(filename, "r").read() + with open(filename, "r") as file: + self.current_svg = file.read() self.cache = OrderedDict() self.areas = [] self.parse_image() diff --git a/scc/lib/daemon.py b/scc/lib/daemon.py index 16ef1402..bc36e757 100644 --- a/scc/lib/daemon.py +++ b/scc/lib/daemon.py @@ -87,7 +87,8 @@ def start(self): # Check if PID coresponds to running daemon process and fail if yes try: assert os.path.exists("/proc") # Just in case of BSD... - cmdline = open("/proc/%s/cmdline" % (pid,), "r").read().replace("\x00", " ").strip() + with open("/proc/%s/cmdline" % (pid,), "r") as file: + cmdline = file.read().replace("\x00", " ").strip() if sys.argv[0] in cmdline: raise Exception("already running") except OSError: diff --git a/scc/osd/__init__.py b/scc/osd/__init__.py index 2174abdd..53f91623 100644 --- a/scc/osd/__init__.py +++ b/scc/osd/__init__.py @@ -95,7 +95,8 @@ def _apply_css(config: dict) -> None: colors = OSDCssMagic(colors) try: css_file = os.path.join(get_share_path(), "osd-styles", config["osd_style"]) - css = open(css_file, "r").read() + with open(css_file, "r") as file: + css = file.read() if ((Gtk.get_major_version(), Gtk.get_minor_version()) > (3, 20)): css += OSDWindow.CSS_3_20 OSDWindow.css_provider = Gtk.CssProvider() @@ -111,7 +112,8 @@ def _apply_css(config: dict) -> None: OSDWindow.css_provider = Gtk.CssProvider() css_file = os.path.join(get_share_path(), "osd-styles", "Classic.gtkstyle.css") - css = open(css_file, "r").read() + with open(css_file, "r") as file: + css = file.read() if ((Gtk.get_major_version(), Gtk.get_minor_version()) > (3, 20)): css += OSDWindow.CSS_3_20 OSDWindow.css_provider.load_from_data((css % colors).encode("utf-8")) diff --git a/scc/osd/keyboard.py b/scc/osd/keyboard.py index ed7d94d9..b08d1a17 100644 --- a/scc/osd/keyboard.py +++ b/scc/osd/keyboard.py @@ -100,7 +100,8 @@ def __init__(self, image): self.set_size_request(*SVGEditor.get_size(background)) self.overlay.edit().keep("overlay").commit() self.overlay.hilight({}) - # open("/tmp/a.svg", "w").write(self.overlay.current_svg.encode("utf-8")) + # with open("/tmp/a.svg", "w") as file: + # file.write(self.overlay.current_svg.encode("utf-8")) def hilight(self, hilight, pressed): diff --git a/scc/profile.py b/scc/profile.py index c3896332..cd07c485 100644 --- a/scc/profile.py +++ b/scc/profile.py @@ -47,9 +47,8 @@ def __init__(self, parser): def save(self, filename): """ Saves profile into file. Returns self """ - fileobj = open(filename, "w") - self.save_fileobj(fileobj) - fileobj.close() + with open(filename, "w") as fileobj: + self.save_fileobj(fileobj) return self @@ -85,8 +84,8 @@ def save_fileobj(self, fileobj): def load(self, filename): """ Loads profile from file. Returns self """ - fileobj = open(filename, "r") - self.load_fileobj(fileobj) + with open(filename, "r") as fileobj: + self.load_fileobj(fileobj) self.filename = filename return self diff --git a/update-wiki.py b/update-wiki.py index 48abe4ea..f59c1aaa 100755 --- a/update-wiki.py +++ b/update-wiki.py @@ -11,23 +11,25 @@ def try_run(cmd: str) -> None: def merge(file_from: str, file_to: str, from_: str, to: str) -> None: """Merge lines from line containing 'from_' to line containing 'to' from f1 to f2.""" lines1, inside = [], False - for line in open(file_from): - if from_ in line.strip("\r\n\t "): - inside = True - elif to in line.strip("\r\n\t "): - inside = False - if inside: - lines1.append(line) + with open(file_from) as file: + for line in file: + if from_ in line.strip("\r\n\t "): + inside = True + elif to in line.strip("\r\n\t "): + inside = False + if inside: + lines1.append(line) lines2, inside = [], False - for line in open(file_to): - if from_ in line.strip("\r\n\t "): - inside = True - lines2 += lines1 - elif to in line.strip("\r\n\t "): - inside = False - elif not inside: - lines2.append(line) + with open(file_to) as file: + for line in file: + if from_ in line.strip("\r\n\t "): + inside = True + lines2 += lines1 + elif to in line.strip("\r\n\t "): + inside = False + elif not inside: + lines2.append(line) open(file_to, "w").write("".join(lines2))