Skip to content

Ensure files are always closed #73

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
May 18, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion generate_icons.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
165 changes: 83 additions & 82 deletions scc/cheader.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__':
Expand Down
3 changes: 2 additions & 1 deletion scc/device_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
3 changes: 2 additions & 1 deletion scc/foreign/vdf.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)


Expand Down
6 changes: 4 additions & 2 deletions scc/gui/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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...
Expand Down
113 changes: 57 additions & 56 deletions scc/gui/creg/dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion scc/gui/global_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(" "))
Expand Down
9 changes: 5 additions & 4 deletions scc/gui/icon_chooser.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down
Loading