modernize

This commit is contained in:
Pavol Rusnak 2024-10-07 11:15:03 +02:00
parent 5e15c43ab7
commit 2a13ed0921
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
103 changed files with 822 additions and 906 deletions

View File

@ -22,11 +22,11 @@ class BasicCommandPlugin(SidebandCommandPlugin):
super().stop()
def handle_command(self, arguments, lxm):
response_content = "Hello "+RNS.prettyhexrep(lxm.source_hash)+". "
response_content = f"Hello {RNS.prettyhexrep(lxm.source_hash)}. "
response_content += "This is a response from the basic command example. It doesn't do much, but here is a list of the arguments you included:\n"
for argument in arguments:
response_content += "\n"+str(argument)
response_content += f"\n{argument)}"
# Let the Sideband core send a reply.
self.get_sideband().send_message(

View File

@ -61,7 +61,7 @@ class ComicCommandPlugin(SidebandCommandPlugin):
except Exception as e:
# Send an error message
self.get_sideband().send_message(
"An error occurred while trying to fetch the specified comic:\n\n"+str(e),
f"An error occurred while trying to fetch the specified comic:\n\n{e)}",
lxm.source_hash,
False, # Don't use propagation by default, try direct first
skip_fields = True, # Don't include any additional fields automatically

View File

@ -12,9 +12,9 @@ class BasicServicePlugin(SidebandServicePlugin):
def service_jobs(self):
while self.should_run:
time.sleep(5)
RNS.log("Service ping from "+str(self))
RNS.log(f"Service ping from {self)}")
RNS.log("Jobs stopped running for "+str(self))
RNS.log(f"Jobs stopped running for {self)}")
def start(self):
# Do any initialisation work here

View File

@ -131,7 +131,7 @@ class CameraSource(ViewSource):
self.frame_queue.put(frame)
except Exception as e:
RNS.log("An error occurred while reading frames from the camera: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while reading frames from the camera: {e)}", RNS.LOG_ERROR)
self.release_camera()
@ -195,10 +195,10 @@ class StreamSource(ViewSource):
self.frame_queue.put(frame)
RNS.log(str(self)+" idled", RNS.LOG_DEBUG)
RNS.log(f"{self)} idled", RNS.LOG_DEBUG)
except Exception as e:
RNS.log("An error occurred while reading frames from the stream: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while reading frames from the stream: {e)}", RNS.LOG_ERROR)
self.release_stream()
@ -236,7 +236,7 @@ class FileSource(ViewSource):
self.source_data = image_file.read()
except Exception as e:
RNS.log("Could not read image at \"{self.path}\": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Could not read image at \"{self.path}\": {e)}", RNS.LOG_ERROR)
self.source_data = None
class ViewCommandPlugin(SidebandCommandPlugin):
@ -292,7 +292,7 @@ class ViewCommandPlugin(SidebandCommandPlugin):
else:
response = "Available Sources:\n"
for source in self.sources:
response += "\n - "+str(source)
response += f"\n - {source)}"
self.message_response(response, requestor)
return

View File

@ -100,7 +100,7 @@ def simulate(link_speed=9600, audio_slot_ms=70, codec_rate=1200, method="msgpack
print(f" On-air length : {PACKET_LEN} bytes")
print(f" Packet airtime : {PACKET_AIRTIME}ms")
print( "\n===== Results for "+RNS.prettyspeed(LINK_SPEED)+" Link Speed ===\n")
print( f"\n===== Results for {RNS.prettyspeed(LINK_SPEED)} Link Speed ===\n")
print(f" Final latency : {TOTAL_LATENCY}ms")
print(f" Recording latency : contributes {TARGET_MS}ms")
print(f" Packet transport : contributes {PACKET_LATENCY}ms")

View File

@ -13,13 +13,13 @@ class Codec2Recipe(Recipe):
def include_flags(self, arch):
'''Returns a string with the include folders'''
codec2_includes = join(self.get_build_dir(arch.arch), 'build_android')
return (' -I' + codec2_includes)
return (f" -I{codec2_includes}")
def link_dirs_flags(self, arch):
'''Returns a string with the appropriate `-L<lib directory>` to link
with the libs. This string is usually added to the environment
variable `LDFLAGS`'''
return ' -L' + self.get_build_dir(arch.arch)
return f" -L{self.get_build_dir(arch.arch)}"
# def link_libs_flags(self):
# '''Returns a string with the appropriate `-l<lib>` flags to link with

View File

@ -146,12 +146,12 @@ class Recipe(metaclass=RecipeMeta):
def get_stl_library(self, arch):
return join(
arch.ndk_lib_dir,
'lib{name}.so'.format(name=self.stl_lib_name),
f'lib{self.stl_lib_name}.so',
)
def install_stl_lib(self, arch):
if not self.ctx.has_lib(
arch.arch, 'lib{name}.so'.format(name=self.stl_lib_name)
arch.arch, f'lib{self.stl_lib_name}.so'
):
self.install_libs(arch, self.get_stl_library(arch))
@ -181,7 +181,7 @@ class Recipe(metaclass=RecipeMeta):
if not url:
return
info('Downloading {} from {}'.format(self.name, url))
info(f'Downloading {self.name} from {url}')
if cwd:
target = join(cwd, target)
@ -190,12 +190,11 @@ class Recipe(metaclass=RecipeMeta):
if parsed_url.scheme in ('http', 'https'):
def report_hook(index, blksize, size):
if size <= 0:
progression = '{0} bytes'.format(index * blksize)
progression = f'{index * blksize} bytes'
else:
progression = '{0:.2f}%'.format(
index * blksize * 100. / float(size))
progression = f'{index * blksize * 100.0 / float(size):.2f}%'
if "CI" not in environ:
stdout.write('- Download {}\r'.format(progression))
stdout.write(f'- Download {progression}\r')
stdout.flush()
if exists(target):
@ -214,7 +213,7 @@ class Recipe(metaclass=RecipeMeta):
attempts += 1
if attempts >= 5:
raise
stdout.write('Download failed: {}; retrying in {} second(s)...'.format(e, seconds))
stdout.write(f'Download failed: {e}; retrying in {seconds} second(s)...')
time.sleep(seconds)
seconds *= 2
continue
@ -253,20 +252,20 @@ class Recipe(metaclass=RecipeMeta):
.. versionchanged:: 0.6.0
Add ability to apply patch from any dir via kwarg `build_dir`'''
"""
info("Applying patch {}".format(filename))
info(f"Applying patch {filename}")
build_dir = build_dir if build_dir else self.get_build_dir(arch)
filename = join(self.get_recipe_dir(), filename)
shprint(sh.patch, "-t", "-d", build_dir, "-p1",
"-i", filename, _tail=10)
def copy_file(self, filename, dest):
info("Copy {} to {}".format(filename, dest))
info(f"Copy {filename} to {dest}")
filename = join(self.get_recipe_dir(), filename)
dest = join(self.build_dir, dest)
shutil.copy(filename, dest)
def append_file(self, filename, dest):
info("Append {} to {}".format(filename, dest))
info(f"Append {filename} to {dest}")
filename = join(self.get_recipe_dir(), filename)
dest = join(self.build_dir, dest)
with open(filename, "rb") as fd:
@ -322,7 +321,7 @@ class Recipe(metaclass=RecipeMeta):
'''
dir_name = self.get_dir_name()
return join(self.ctx.build_dir, 'other_builds',
dir_name, '{}__ndk_target_{}'.format(arch, self.ctx.ndk_api))
dir_name, f'{arch}__ndk_target_{self.ctx.ndk_api}')
def get_dir_name(self):
choices = self.check_recipe_choices()
@ -349,24 +348,23 @@ class Recipe(metaclass=RecipeMeta):
# Public Recipe API to be subclassed if needed
def download_if_necessary(self):
info_main('Downloading {}'.format(self.name))
user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower()))
info_main(f'Downloading {self.name}')
user_dir = environ.get(f'P4A_{self.name.lower()}_DIR')
if user_dir is not None:
info('P4A_{}_DIR is set, skipping download for {}'.format(
self.name, self.name))
info(f'P4A_{self.name}_DIR is set, skipping download for {self.name}')
return
self.download()
def download(self):
if self.url is None:
info('Skipping {} download as no URL is set'.format(self.name))
info(f'Skipping {self.name} download as no URL is set')
return
url = self.versioned_url
expected_digests = {}
for alg in set(hashlib.algorithms_guaranteed) | set(('md5', 'sha512', 'blake2b')):
for alg in set(hashlib.algorithms_guaranteed) | {'md5', 'sha512', 'blake2b'}:
expected_digest = getattr(self, alg + 'sum') if hasattr(self, alg + 'sum') else None
ma = match(u'^(.+)#' + alg + u'=([0-9a-f]{32,})$', url)
ma = match('^(.+)#' + alg + '=([0-9a-f]{32,})$', url)
if ma: # fragmented URL?
if expected_digest:
raise ValueError(
@ -383,7 +381,7 @@ class Recipe(metaclass=RecipeMeta):
filename = shprint(sh.basename, url).stdout[:-1].decode('utf-8')
do_download = True
marker_filename = '.mark-{}'.format(filename)
marker_filename = f'.mark-{filename}'
if exists(filename) and isfile(filename):
if not exists(marker_filename):
shprint(sh.rm, filename)
@ -391,10 +389,8 @@ class Recipe(metaclass=RecipeMeta):
for alg, expected_digest in expected_digests.items():
current_digest = algsum(alg, filename)
if current_digest != expected_digest:
debug('* Generated {}sum: {}'.format(alg,
current_digest))
debug('* Expected {}sum: {}'.format(alg,
expected_digest))
debug(f'* Generated {alg}sum: {current_digest}')
debug(f'* Expected {alg}sum: {expected_digest}')
raise ValueError(
('Generated {0}sum does not match expected {0}sum '
'for {1} recipe').format(alg, self.name))
@ -402,7 +398,7 @@ class Recipe(metaclass=RecipeMeta):
# If we got this far, we will download
if do_download:
debug('Downloading {} from {}'.format(self.name, url))
debug(f'Downloading {self.name} from {url}')
shprint(sh.rm, '-f', marker_filename)
self.download_file(self.versioned_url, filename)
@ -412,25 +408,22 @@ class Recipe(metaclass=RecipeMeta):
for alg, expected_digest in expected_digests.items():
current_digest = algsum(alg, filename)
if current_digest != expected_digest:
debug('* Generated {}sum: {}'.format(alg,
current_digest))
debug('* Expected {}sum: {}'.format(alg,
expected_digest))
debug(f'* Generated {alg}sum: {current_digest}')
debug(f'* Expected {alg}sum: {expected_digest}')
raise ValueError(
('Generated {0}sum does not match expected {0}sum '
'for {1} recipe').format(alg, self.name))
else:
info('{} download already cached, skipping'.format(self.name))
info(f'{self.name} download already cached, skipping')
def unpack(self, arch):
info_main('Unpacking {} for {}'.format(self.name, arch))
info_main(f'Unpacking {self.name} for {arch}')
build_dir = self.get_build_container_dir(arch)
user_dir = environ.get('P4A_{}_DIR'.format(self.name.lower()))
user_dir = environ.get(f'P4A_{self.name.lower()}_DIR')
if user_dir is not None:
info('P4A_{}_DIR exists, symlinking instead'.format(
self.name.lower()))
info(f'P4A_{self.name.lower()}_DIR exists, symlinking instead')
if exists(self.get_build_dir(arch)):
return
rmdir(build_dir)
@ -439,12 +432,12 @@ class Recipe(metaclass=RecipeMeta):
return
if self.url is None:
info('Skipping {} unpack as no URL is set'.format(self.name))
info(f'Skipping {self.name} unpack as no URL is set')
return
filename = shprint(
sh.basename, self.versioned_url).stdout[:-1].decode('utf-8')
ma = match(u'^(.+)#[a-z0-9_]{3,}=([0-9a-f]{32,})$', filename)
ma = match('^(.+)#[a-z0-9_]{3,}=([0-9a-f]{32,})$', filename)
if ma: # fragmented URL?
filename = ma.group(1)
@ -493,7 +486,7 @@ class Recipe(metaclass=RecipeMeta):
.format(extraction_filename))
else:
info('{} is already unpacked, skipping'.format(self.name))
info(f'{self.name} is already unpacked, skipping')
def get_recipe_env(self, arch=None, with_flags_in_cc=True):
"""Return the env specialized for the recipe
@ -507,11 +500,11 @@ class Recipe(metaclass=RecipeMeta):
'''Run any pre-build tasks for the Recipe. By default, this checks if
any prebuild_archname methods exist for the archname of the current
architecture, and runs them if so.'''
prebuild = "prebuild_{}".format(arch.arch.replace('-', '_'))
prebuild = f"prebuild_{arch.arch.replace('-', '_')}"
if hasattr(self, prebuild):
getattr(self, prebuild)()
else:
info('{} has no {}, skipping'.format(self.name, prebuild))
info(f'{self.name} has no {prebuild}, skipping')
def is_patched(self, arch):
build_dir = self.get_build_dir(arch.arch)
@ -523,11 +516,10 @@ class Recipe(metaclass=RecipeMeta):
.. versionchanged:: 0.6.0
Add ability to apply patches from any dir via kwarg `build_dir`'''
if self.patches:
info_main('Applying patches for {}[{}]'
.format(self.name, arch.arch))
info_main(f'Applying patches for {self.name}[{arch.arch}]')
if self.is_patched(arch):
info_main('{} already patched, skipping'.format(self.name))
info_main(f'{self.name} already patched, skipping')
return
build_dir = build_dir if build_dir else self.get_build_dir(arch.arch)
@ -559,7 +551,7 @@ class Recipe(metaclass=RecipeMeta):
'''Run any build tasks for the Recipe. By default, this checks if
any build_archname methods exist for the archname of the current
architecture, and runs them if so.'''
build = "build_{}".format(arch.arch)
build = f"build_{arch.arch}"
if hasattr(self, build):
getattr(self, build)()
@ -581,7 +573,7 @@ class Recipe(metaclass=RecipeMeta):
any postbuild_archname methods exist for the archname of the
current architecture, and runs them if so.
'''
postbuild = "postbuild_{}".format(arch.arch)
postbuild = f"postbuild_{arch.arch}"
if hasattr(self, postbuild):
getattr(self, postbuild)()
@ -707,9 +699,9 @@ class Recipe(metaclass=RecipeMeta):
break
else:
raise ValueError('Recipe does not exist: {}'.format(name))
raise ValueError(f'Recipe does not exist: {name}')
mod = import_recipe('pythonforandroid.recipes.{}'.format(name), recipe_file)
mod = import_recipe(f'pythonforandroid.recipes.{name}', recipe_file)
if len(logger.handlers) > 1:
logger.removeHandler(logger.handlers[1])
recipe = mod.recipe
@ -718,7 +710,7 @@ class Recipe(metaclass=RecipeMeta):
return recipe
class IncludedFilesBehaviour(object):
class IncludedFilesBehaviour:
'''Recipe mixin class that will automatically unpack files included in
the recipe directory.'''
src_filename = None
@ -765,8 +757,7 @@ class BootstrapNDKRecipe(Recipe):
env['PYTHON_INCLUDE_ROOT'] = self.ctx.python_recipe.include_root(arch.arch)
env['PYTHON_LINK_ROOT'] = self.ctx.python_recipe.link_root(arch.arch)
env['EXTRA_LDLIBS'] = ' -lpython{}'.format(
self.ctx.python_recipe.link_version)
env['EXTRA_LDLIBS'] = f' -lpython{self.ctx.python_recipe.link_version}'
return env
@ -868,18 +859,18 @@ class PythonRecipe(Recipe):
if site_packages_dir:
build_dir = join(site_packages_dir[0], name)
if exists(build_dir):
info('Deleted {}'.format(build_dir))
info(f'Deleted {build_dir}')
rmdir(build_dir)
@property
def real_hostpython_location(self):
host_name = 'host{}'.format(self.ctx.python_recipe.name)
host_name = f'host{self.ctx.python_recipe.name}'
if host_name == 'hostpython3':
python_recipe = Recipe.get_recipe(host_name, self.ctx)
return python_recipe.python_exe
else:
python_recipe = self.ctx.python_recipe
return 'python{}'.format(python_recipe.version)
return f'python{python_recipe.version}'
@property
def hostpython_location(self):
@ -905,9 +896,7 @@ class PythonRecipe(Recipe):
env["PATH"] = join(self.hostpython_site_dir, "bin") + ":" + env["PATH"]
if not self.call_hostpython_via_targetpython:
env['CFLAGS'] += ' -I{}'.format(
self.ctx.python_recipe.include_root(arch.arch)
)
env['CFLAGS'] += f' -I{self.ctx.python_recipe.include_root(arch.arch)}'
env['LDFLAGS'] += ' -L{} -lpython{}'.format(
self.ctx.python_recipe.link_root(arch.arch),
self.ctx.python_recipe.link_version,
@ -932,7 +921,7 @@ class PythonRecipe(Recipe):
if self.ctx.has_package(name, arch):
info('Python package already exists in site-packages')
return False
info('{} apparently isn\'t already in site-packages'.format(name))
info(f'{name} apparently isn\'t already in site-packages')
return True
def build_arch(self, arch):
@ -951,13 +940,13 @@ class PythonRecipe(Recipe):
if env is None:
env = self.get_recipe_env(arch)
info('Installing {} into site-packages'.format(self.name))
info(f'Installing {self.name} into site-packages')
hostpython = sh.Command(self.hostpython_location)
hpenv = env.copy()
with current_directory(self.get_build_dir(arch.arch)):
shprint(hostpython, 'setup.py', 'install', '-O2',
'--root={}'.format(self.ctx.get_python_install_dir(arch.arch)),
f'--root={self.ctx.get_python_install_dir(arch.arch)}',
'--install-lib=.',
_env=hpenv, *self.setup_extra_args)
@ -978,7 +967,7 @@ class PythonRecipe(Recipe):
env = self.get_hostrecipe_env(arch)
real_hostpython = sh.Command(self.real_hostpython_location)
shprint(real_hostpython, 'setup.py', 'install', '-O2',
'--root={}'.format(dirname(self.real_hostpython_location)),
f'--root={dirname(self.real_hostpython_location)}',
'--install-lib=Lib/site-packages',
_env=env, *self.setup_extra_args)
@ -1030,7 +1019,7 @@ class CompiledComponentsPythonRecipe(PythonRecipe):
self.install_python_package(arch)
def build_compiled_components(self, arch):
info('Building compiled components in {}'.format(self.name))
info(f'Building compiled components in {self.name}')
env = self.get_recipe_env(arch)
hostpython = sh.Command(self.hostpython_location)
@ -1049,7 +1038,7 @@ class CompiledComponentsPythonRecipe(PythonRecipe):
super().install_hostpython_package(arch)
def rebuild_compiled_components(self, arch, env):
info('Rebuilding compiled components in {}'.format(self.name))
info(f'Rebuilding compiled components in {self.name}')
hostpython = sh.Command(self.real_hostpython_location)
shprint(hostpython, 'setup.py', 'clean', '--all', _env=env)
@ -1078,14 +1067,14 @@ class CythonRecipe(PythonRecipe):
self.install_python_package(arch)
def build_cython_components(self, arch):
info('Cythonizing anything necessary in {}'.format(self.name))
info(f'Cythonizing anything necessary in {self.name}')
env = self.get_recipe_env(arch)
with current_directory(self.get_build_dir(arch.arch)):
hostpython = sh.Command(self.ctx.hostpython)
shprint(hostpython, '-c', 'import sys; print(sys.path)', _env=env)
debug('cwd is {}'.format(realpath(curdir)))
debug(f'cwd is {realpath(curdir)}')
info('Trying first build of {} to get cython files: this is '
'expected to fail'.format(self.name))
@ -1095,7 +1084,7 @@ class CythonRecipe(PythonRecipe):
*self.setup_extra_args)
except sh.ErrorReturnCode_1:
print()
info('{} first build failed (as expected)'.format(self.name))
info(f'{self.name} first build failed (as expected)')
manually_cythonise = True
if manually_cythonise:
@ -1125,7 +1114,7 @@ class CythonRecipe(PythonRecipe):
short_filename = filename
if filename.startswith(build_dir):
short_filename = filename[len(build_dir) + 1:]
info(u"Cythonize {}".format(short_filename))
info(f"Cythonize {short_filename}")
cyenv = env.copy()
if 'CYTHONPATH' in cyenv:
cyenv['PYTHONPATH'] = cyenv['CYTHONPATH']
@ -1166,7 +1155,7 @@ class CythonRecipe(PythonRecipe):
# Every recipe uses its own liblink path, object files are
# collected and biglinked later
liblink_path = join(self.get_build_container_dir(arch.arch),
'objects_{}'.format(self.name))
f'objects_{self.name}')
env['LIBLINK_PATH'] = liblink_path
ensure_dir(liblink_path)
@ -1190,9 +1179,7 @@ class PyProjectRecipe(PythonRecipe):
build_opts = join(build_dir, "build-opts.cfg")
with open(build_opts, "w") as file:
file.write("[bdist_wheel]\nplat-name={}".format(
self.get_wheel_platform_tag(arch)
))
file.write(f"[bdist_wheel]\nplat-name={self.get_wheel_platform_tag(arch)}")
file.close()
env["DIST_EXTRA_CONFIG"] = build_opts
@ -1246,7 +1233,7 @@ class PyProjectRecipe(PythonRecipe):
"build",
"--wheel",
"--config-setting",
"builddir={}".format(sub_build_dir),
f"builddir={sub_build_dir}",
] + self.extra_build_args
built_wheels = []
@ -1309,13 +1296,13 @@ class MesonRecipe(PyProjectRecipe):
option_data = ""
build_options = self.get_recipe_meson_options(arch)
for key in build_options.keys():
data_chunk = "[{}]".format(key)
data_chunk = f"[{key}]"
for subkey in build_options[key].keys():
value = build_options[key][subkey]
if isinstance(value, int):
value = str(value)
elif isinstance(value, str):
value = "'{}'".format(value)
value = f"'{value}'"
elif isinstance(value, bool):
value = "true" if value else "false"
elif isinstance(value, list):
@ -1331,17 +1318,17 @@ class MesonRecipe(PyProjectRecipe):
def build_arch(self, arch):
cross_file = join("/tmp", "android.meson.cross")
info("Writing cross file at: {}".format(cross_file))
info(f"Writing cross file at: {cross_file}")
# write cross config file
with open(cross_file, "w") as file:
file.write(self.write_build_options(arch))
file.close()
# set cross file
self.ensure_args('-Csetup-args=--cross-file', '-Csetup-args={}'.format(cross_file))
self.ensure_args('-Csetup-args=--cross-file', f'-Csetup-args={cross_file}')
# ensure ninja and meson
for dep in [
"ninja=={}".format(self.ninja_version),
"meson=={}".format(self.meson_version),
f"ninja=={self.ninja_version}",
f"meson=={self.meson_version}",
]:
if dep not in self.hostpython_prerequisites:
self.hostpython_prerequisites.append(dep)
@ -1388,7 +1375,7 @@ class RustCompiledComponentsRecipe(PyProjectRecipe):
env["PYO3_CROSS_LIB_DIR"] = realpath(glob.glob(join(
realpython_dir, "android-build", "build",
"lib.linux-*-{}/".format(self.python_major_minor_version),
f"lib.linux-*-{self.python_major_minor_version}/",
))[0])
info_main("Ensuring rust build toolchain")
@ -1447,7 +1434,7 @@ class TargetPythonRecipe(Recipe):
copying all the modules and standard library to the right
place.
"""
raise NotImplementedError('{} does not implement create_python_bundle'.format(self))
raise NotImplementedError(f'{self} does not implement create_python_bundle')
def reduce_object_file_names(self, dirn):
"""Recursively renames all files named XXX.cpython-...-linux-gnu.so"

View File

@ -12,7 +12,7 @@ class OpusRecipe(Recipe):
with current_directory(self.get_build_dir(arch.arch)):
env = self.get_recipe_env(arch)
flags = [
'--host=' + arch.command_prefix,
f"--host={arch.command_prefix}",
]
configure = sh.Command('./configure')
shprint(configure, *flags, _env=env)

View File

@ -40,9 +40,9 @@ class FFMpegRecipe(Recipe):
]
build_dir = Recipe.get_recipe(
'openssl', self.ctx).get_build_dir(arch.arch)
cflags += ['-I' + build_dir + '/include/',
cflags += [f"-I{build_dir}/include/",
'-DOPENSSL_API_COMPAT=0x10002000L']
ldflags += ['-L' + build_dir]
ldflags += [f"-L{build_dir}"]
if 'ffpyplayer_codecs' in self.ctx.recipe_build_order:
# Enable GPL
@ -52,22 +52,22 @@ class FFMpegRecipe(Recipe):
flags += ['--enable-libx264']
build_dir = Recipe.get_recipe(
'libx264', self.ctx).get_build_dir(arch.arch)
cflags += ['-I' + build_dir + '/include/']
ldflags += ['-lx264', '-L' + build_dir + '/lib/']
cflags += [f"-I{build_dir}/include/"]
ldflags += ['-lx264', f"-L{build_dir}/lib/"]
# libshine
flags += ['--enable-libshine']
build_dir = Recipe.get_recipe('libshine', self.ctx).get_build_dir(arch.arch)
cflags += ['-I' + build_dir + '/include/']
ldflags += ['-lshine', '-L' + build_dir + '/lib/']
cflags += [f"-I{build_dir}/include/"]
ldflags += ['-lshine', f"-L{build_dir}/lib/"]
ldflags += ['-lm']
# libvpx
flags += ['--enable-libvpx']
build_dir = Recipe.get_recipe(
'libvpx', self.ctx).get_build_dir(arch.arch)
cflags += ['-I' + build_dir + '/include/']
ldflags += ['-lvpx', '-L' + build_dir + '/lib/']
cflags += [f"-I{build_dir}/include/"]
ldflags += ['-lvpx', f"-L{build_dir}/lib/"]
# Enable all codecs:
flags += [
@ -122,12 +122,12 @@ class FFMpegRecipe(Recipe):
flags += [
'--target-os=android',
'--enable-cross-compile',
'--cross-prefix={}-'.format(arch.target),
'--arch={}'.format(arch_flag),
'--strip={}'.format(self.ctx.ndk.llvm_strip),
'--sysroot={}'.format(self.ctx.ndk.sysroot),
f'--cross-prefix={arch.target}-',
f'--arch={arch_flag}',
f'--strip={self.ctx.ndk.llvm_strip}',
f'--sysroot={self.ctx.ndk.sysroot}',
'--enable-neon',
'--prefix={}'.format(realpath('.')),
f"--prefix={realpath('.')}",
]
if arch_flag == 'arm':
@ -137,8 +137,8 @@ class FFMpegRecipe(Recipe):
'-fPIC',
]
env['CFLAGS'] += ' ' + ' '.join(cflags)
env['LDFLAGS'] += ' ' + ' '.join(ldflags)
env['CFLAGS'] += f" {' '.join(cflags)}"
env['LDFLAGS'] += f" {' '.join(ldflags)}"
configure = sh.Command('./configure')
shprint(configure, *flags, _env=env)

View File

@ -37,7 +37,7 @@ class NumpyRecipe(CompiledComponentsPythonRecipe):
return env
def _build_compiled_components(self, arch):
info('Building compiled components in {}'.format(self.name))
info(f'Building compiled components in {self.name}')
env = self.get_recipe_env(arch)
with current_directory(self.get_build_dir(arch.arch)):
@ -49,7 +49,7 @@ class NumpyRecipe(CompiledComponentsPythonRecipe):
env['STRIP'], '{}', ';', _env=env)
def _rebuild_compiled_components(self, arch, env):
info('Rebuilding compiled components in {}'.format(self.name))
info(f'Rebuilding compiled components in {self.name}')
hostpython = sh.Command(self.real_hostpython_location)
shprint(hostpython, 'setup.py', 'clean', '--all', '--force', _env=env)

View File

@ -15,7 +15,7 @@ class OpusFileRecipe(Recipe):
with current_directory(self.get_build_dir(arch.arch)):
env = self.get_recipe_env(arch)
flags = [
"--host=" + arch.command_prefix,
f"--host={arch.command_prefix}",
"--disable-http",
"--disable-examples",
"--disable-doc",

View File

@ -17,9 +17,9 @@ class PyCodec2Recipe(CythonRecipe):
env = super().get_recipe_env(arch, with_flags_in_cc)
codec2_recipe = self.get_recipe('codec2', self.ctx)
env['CFLAGS'] += codec2_recipe.include_flags(arch) +" -l:libcodec2.so"
env['LDFLAGS'] += ' -L{}'.format(self.ctx.get_libs_dir(arch.arch))
env['LDFLAGS'] += ' -L{}'.format(self.ctx.libs_dir)
env['CFLAGS'] += f"{codec2_recipe.include_flags(arch)} -l:libcodec2.so"
env['LDFLAGS'] += f' -L{self.ctx.get_libs_dir(arch.arch)}'
env['LDFLAGS'] += f' -L{self.ctx.libs_dir}'
env['LDFLAGS'] += codec2_recipe.link_dirs_flags(arch)
return env

View File

@ -1,5 +1,5 @@
import os
import glob
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
modules = glob.glob(f"{os.path.dirname(__file__)}/*.py")
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]

View File

@ -222,10 +222,7 @@ def main():
iconsetDir.mkdir()
except Exception as ex:
raise SystemExit(
" ".join((
"[ERROR] Could not create temporary",
f"iconset folder: {iconsetDir}"
))
f"[ERROR] Could not create temporary iconset folder: {iconsetDir}"
)
else:
if False: # cliArgs.delete_tmp_iconset:
@ -303,10 +300,7 @@ def main():
)
else:
print(
" ".join((
"[SUCCESS] An iconset was successfully",
f"generated to {resultingIconset}"
))
f"[SUCCESS] An iconset was successfully generated to {resultingIconset}"
)
raise SystemExit(0)

View File

@ -11,7 +11,7 @@ def get_version() -> str:
os.path.dirname(__file__), "main.py"
)
version_file_data = open(version_file, "rt", encoding="utf-8").read()
version_file_data = open(version_file, encoding="utf-8").read()
version_regex = r"(?<=^__version__ = ['\"])[^'\"]+(?=['\"]$)"
try:
version = re.findall(version_regex, version_file_data, re.M)[0]
@ -24,7 +24,7 @@ def get_variant() -> str:
os.path.dirname(__file__), "main.py"
)
version_file_data = open(version_file, "rt", encoding="utf-8").read()
version_file_data = open(version_file, encoding="utf-8").read()
version_regex = r"(?<=^__variant__ = ['\"])[^'\"]+(?=['\"]$)"
try:
version = re.findall(version_regex, version_file_data, re.M)[0]
@ -60,14 +60,14 @@ package_data = {
]
}
print("Freezing Sideband "+__version__+" "+__variant__)
print(f"Freezing Sideband {__version__} {__variant__}")
if build_appimage:
global_excludes = [".buildozer", "build", "dist"]
# Dependencies are automatically detected, but they might need fine-tuning.
appimage_options = {
"target_name": "Sideband",
"target_version": __version__+" "+__variant__,
"target_version": f"{__version__} {__variant__}",
"include_files": [],
"excludes": [],
"packages": ["kivy"],

View File

@ -5,7 +5,7 @@ def gv() -> str:
os.path.dirname(__file__), "main.py"
)
version_file_data = open(version_file, "rt", encoding="utf-8").read()
version_file_data = open(version_file, encoding="utf-8").read()
version_regex = r"(?<=^__version__ = ['\"])[^'\"]+(?=['\"]$)"
try:
version = re.findall(version_regex, version_file_data, re.M)[0]

View File

@ -14,34 +14,34 @@ from kivymd import fonts_path
fonts = [
{
"name": "Roboto",
"fn_regular": fonts_path + "Roboto-Regular.ttf",
"fn_bold": fonts_path + "Roboto-Bold.ttf",
"fn_italic": fonts_path + "Roboto-Italic.ttf",
"fn_bolditalic": fonts_path + "Roboto-BoldItalic.ttf",
"fn_regular": f"{fonts_path}Roboto-Regular.ttf",
"fn_bold": f"{fonts_path}Roboto-Bold.ttf",
"fn_italic": f"{fonts_path}Roboto-Italic.ttf",
"fn_bolditalic": f"{fonts_path}Roboto-BoldItalic.ttf",
},
{
"name": "RobotoThin",
"fn_regular": fonts_path + "Roboto-Thin.ttf",
"fn_italic": fonts_path + "Roboto-ThinItalic.ttf",
"fn_regular": f"{fonts_path}Roboto-Thin.ttf",
"fn_italic": f"{fonts_path}Roboto-ThinItalic.ttf",
},
{
"name": "RobotoLight",
"fn_regular": fonts_path + "Roboto-Light.ttf",
"fn_italic": fonts_path + "Roboto-LightItalic.ttf",
"fn_regular": f"{fonts_path}Roboto-Light.ttf",
"fn_italic": f"{fonts_path}Roboto-LightItalic.ttf",
},
{
"name": "RobotoMedium",
"fn_regular": fonts_path + "Roboto-Medium.ttf",
"fn_italic": fonts_path + "Roboto-MediumItalic.ttf",
"fn_regular": f"{fonts_path}Roboto-Medium.ttf",
"fn_italic": f"{fonts_path}Roboto-MediumItalic.ttf",
},
{
"name": "RobotoBlack",
"fn_regular": fonts_path + "Roboto-Black.ttf",
"fn_italic": fonts_path + "Roboto-BlackItalic.ttf",
"fn_regular": f"{fonts_path}Roboto-Black.ttf",
"fn_italic": f"{fonts_path}Roboto-BlackItalic.ttf",
},
{
"name": "Icons",
"fn_regular": fonts_path + "materialdesignicons-webfont.ttf",
"fn_regular": f"{fonts_path}materialdesignicons-webfont.ttf",
},
]

View File

@ -182,7 +182,7 @@ class MDApp(BaseApp):
def build(self):
if self.DEBUG:
Logger.info("{}: Debug mode activated".format(self.appname))
Logger.info(f"{self.appname}: Debug mode activated")
self.enable_autoreload()
self.patch_builder()
self.bind_key(32, self.rebuild)
@ -267,7 +267,7 @@ class MDApp(BaseApp):
Builder.load_file(path_to_kv_file)
def rebuild(self, *args, **kwargs):
print("{}: Rebuild the application".format(self.appname))
print(f"{self.appname}: Rebuild the application")
first = kwargs.get("first", False)
try:
if not first:
@ -287,7 +287,7 @@ class MDApp(BaseApp):
except Exception as exc:
import traceback
Logger.exception("{}: Error when building app".format(self.appname))
Logger.exception(f"{self.appname}: Error when building app")
self.set_error(repr(exc), traceback.format_exc())
if not self.DEBUG and self.RAISE_ERROR:
raise
@ -304,7 +304,7 @@ class MDApp(BaseApp):
lbl = Factory.Label(
text_size=(Window.width - 100, None),
size_hint_y=None,
text="{}\n\n{}".format(exc, tb or ""),
text=f"{exc}\n\n{tb or ''}",
)
lbl.bind(texture_size=lbl.setter("size"))
scroll.add_widget(lbl)
@ -338,10 +338,10 @@ class MDApp(BaseApp):
from watchdog.observers import Observer
except ImportError:
Logger.warn(
"{}: Autoreloader is missing watchdog".format(self.appname)
f"{self.appname}: Autoreloader is missing watchdog"
)
return
Logger.info("{}: Autoreloader activated".format(self.appname))
Logger.info(f"{self.appname}: Autoreloader activated")
rootpath = self.get_root_path()
self.w_handler = handler = FileSystemEventHandler()
handler.dispatch = self._reload_from_watchdog
@ -402,16 +402,12 @@ class MDApp(BaseApp):
if monotonic is None:
Logger.exception(
"{}: Cannot use idle detector, monotonic is missing".format(
self.appname
)
f"{self.appname}: Cannot use idle detector, monotonic is missing"
)
self.idle_timer = None
self.idle_timeout = timeout
Logger.info(
"{}: Install idle detector, {} seconds".format(
self.appname, timeout
)
f"{self.appname}: Install idle detector, {timeout} seconds"
)
Clock.schedule_interval(self._check_idle, 1)
self.root.bind(
@ -498,7 +494,7 @@ class MDApp(BaseApp):
module = self._filename_to_module(filename)
if module in sys.modules:
Logger.debug("{}: Module exist, reload it".format(self.appname))
Logger.debug(f"{self.appname}: Module exist, reload it")
Factory.unregister_from_filename(filename)
self._unregister_factory_from_module(module)
reload(sys.modules[module])
@ -528,9 +524,7 @@ class MDApp(BaseApp):
filename = filename[1:]
module = filename[:-3].replace("/", ".")
Logger.debug(
"{}: Translated {} to {}".format(
self.appname, orig_filename, module
)
f"{self.appname}: Translated {orig_filename} to {module}"
)
return module

View File

@ -982,7 +982,7 @@ def create_module_screens() -> None:
path_to_module_screens = os.path.join(path_to_project, "View", "screens.py")
with open(path_to_module_screens, "w", encoding="utf-8") as module_screens:
module_screens.write(
"%s\nscreens = {%s}" % (temp_screens_imports, temp_screens_data)
f"{temp_screens_imports}\nscreens = {{{temp_screens_data}}}"
)

View File

@ -53,9 +53,9 @@ def run_pre_commit():
def replace_in_file(pattern, repl, file):
"""Replace one `pattern` match to `repl` in file `file`."""
file_content = open(file, "rt", encoding="utf-8").read()
file_content = open(file, encoding="utf-8").read()
new_file_content = re.sub(pattern, repl, file_content, 1, re.M)
open(file, "wt", encoding="utf-8").write(new_file_content)
open(file, "w", encoding="utf-8").write(new_file_content)
return not file_content == new_file_content
@ -116,7 +116,7 @@ def move_changelog(
"""Edit unreleased.rst and rename to <version>.rst."""
# Read unreleased changelog
changelog = open(unreleased_file, "rt", encoding="utf-8").read()
changelog = open(unreleased_file, encoding="utf-8").read()
# Edit changelog
changelog = re.sub(
@ -157,7 +157,7 @@ def move_changelog(
)
# Write changelog
open(version_file, "wt", encoding="utf-8").write(changelog)
open(version_file, "w", encoding="utf-8").write(changelog)
# Remove unreleased changelog
os.remove(unreleased_file)
# Update index file
@ -200,7 +200,7 @@ def create_unreleased_changelog(
* Bug fixes and other minor improvements.
"""
# Create unreleased file
open(unreleased_file, "wt", encoding="utf-8").write(changelog)
open(unreleased_file, "w", encoding="utf-8").write(changelog)
# Update index file
success = replace_in_file(
r"(?<=Changelog\n=========\n\n)",
@ -218,7 +218,7 @@ def main():
release = args.command == "release"
version = args.version or "0.0.0"
next_version = args.next_version or (
(version[:-1] + str(int(version[-1]) + 1) + ".dev0")
f"{version[:-1] + str(int(version[-1]) + 1)}.dev0"
if "rc" not in version
else version
)

View File

@ -74,7 +74,7 @@ def unzip_archive(archive_path, dir_path):
def get_icons_list():
# There is js array with icons in file preview.html
with open(temp_preview_path, "r") as f:
with open(temp_preview_path) as f:
preview_file = f.read()
# Find version
version = re_version.findall(preview_file)[0]
@ -101,13 +101,13 @@ def make_icon_definitions(icons):
icon_definitions += f'"{i["name"]}": "\\U{i["hex"].upper()}",\n'
else:
icon_definitions += f'"{i["name"]}": "\\u{i["hex"].upper()}",\n'
icon_definitions += " " * 4 + '"blank": " ",\n' # Add blank icon (space)
icon_definitions += f"{' ' * 4}\"blank\": \" \",\n" # Add blank icon (space)
icon_definitions += "}"
return icon_definitions
def export_icon_definitions(icon_definitions, version):
with open(icon_definitions_path, "r") as f:
with open(icon_definitions_path) as f:
icon_definitions_file = f.read()
# Change md_icons list
new_icon_definitions = re_icon_definitions.sub(

View File

@ -88,7 +88,7 @@ from kivy.properties import BooleanProperty, ObjectProperty
from kivy.uix.widget import Widget
class HoverBehavior(object):
class HoverBehavior:
"""
:Events:
:attr:`on_enter`
@ -136,7 +136,7 @@ class HoverBehavior(object):
self.register_event_type("on_enter")
self.register_event_type("on_leave")
Window.bind(mouse_pos=self.on_mouse_update)
super(HoverBehavior, self).__init__(**kwargs)
super().__init__(**kwargs)
def on_mouse_update(self, *args):
# If the Widget currently has no parent, do nothing

View File

@ -1477,7 +1477,7 @@ class MDIconButton(BaseButton, OldButtonIconMixin, ButtonContentsIcon):
self.line_width = 0.001
Clock.schedule_once(self.set_size)
def set_size(self, interval: Union[int, float]) -> None:
def set_size(self, interval: int | float) -> None:
"""
Sets the icon width/height based on the current `icon_size`
attribute, or the default value if it is zero. The icon size
@ -1637,7 +1637,7 @@ class BaseFloatingBottomButton(MDFloatingActionButton, MDTooltip):
_padding_right = NumericProperty(0)
_bg_color = ColorProperty(None)
def set_size(self, interval: Union[int, float]) -> None:
def set_size(self, interval: int | float) -> None:
self.width = "46dp"
self.height = "46dp"

View File

@ -339,7 +339,6 @@ class TableHeader(ThemableBehavior, ScrollView):
self._col_headings.append(col_heading[0])
if i:
self.ids.header.add_widget(
(
CellHeader(
text=col_heading[0],
sort_action=col_heading[2],
@ -362,7 +361,6 @@ class TableHeader(ThemableBehavior, ScrollView):
width=self.cols_minimum[i],
table_data=self.table_data,
)
)
)
else:
# Sets the text in the first cell.

View File

@ -650,7 +650,7 @@ class MDFileManager(MDRelativeLayout):
return dirs, files
except OSError as e:
print("Filemanager OSError: "+str(e))
print(f"Filemanager OSError: {e)}")
return None, None
def close(self) -> None:

View File

@ -711,7 +711,7 @@ class MDLabel(
self.on_opposite_colors(None, self.opposite_colors)
Clock.schedule_once(self.check_font_styles)
def check_font_styles(self, interval: Union[int, float] = 0) -> bool:
def check_font_styles(self, interval: int | float = 0) -> bool:
if self.font_style not in list(self.theme_cls.font_styles.keys()):
raise ValueError(
f"MDLabel.font_style is set to an invalid option '{self.font_style}'."
@ -828,7 +828,7 @@ class MDLabel(
else:
self.color = color
def on_text_color(self, instance_label, color: Union[list, str]) -> None:
def on_text_color(self, instance_label, color: list | str) -> None:
if self.theme_text_color == "Custom":
if self.theme_cls.theme_style_switch_animation:
Animation(
@ -842,7 +842,7 @@ class MDLabel(
def on_opposite_colors(self, *args) -> None:
self.on_theme_text_color(self, self.theme_text_color)
def on_md_bg_color(self, instance_label, color: Union[list, str]) -> None:
def on_md_bg_color(self, instance_label, color: list | str) -> None:
self.canvas.remove_group("Background_instruction")
self.canvas.before.clear()
with self.canvas.before:

View File

@ -229,10 +229,10 @@ class GradientTab(MDBoxLayout):
else self.color_picker.get_rgb(self.theme_cls.primary_color)
)
else:
r, g, b = [
r, g, b = (
int(value * 255)
for value in self.color_picker.default_color[:-1]
]
)
self.color_picker._rgb = [r, g, b]
(
r_adjacent_color_constant,

View File

@ -678,7 +678,7 @@ class DatePickerInputField(MDTextField):
self.error = True
def input_filter(self, value: str, boolean: bool) -> Union[str, None]:
def input_filter(self, value: str, boolean: bool) -> str | None:
"""Filters the input according to the specified mode."""
if self.is_numeric(value):
@ -1077,7 +1077,7 @@ class MDDatePicker(BaseDialogPicker):
self._update_date_label_text()
def transformation_from_dialog_input_date(
self, interval: Union[int, float]
self, interval: int | float
) -> None:
if not self._try_apply_input():
return
@ -1299,7 +1299,7 @@ class MDDatePicker(BaseDialogPicker):
horizontal = orientation == "portrait" or self._input_date_dialog_open
def date_repr(date):
return date.strftime("%b").capitalize() + " " + str(date.day)
return f"{date.strftime('%b').capitalize()} {date.day)}"
input_dates = self._get_dates_from_fields()
if self.mode == "picker":

View File

@ -243,7 +243,7 @@ class TimeInputTextField(MDTextField):
def insert_text(self, text, from_undo=False):
strip_text = self.text.strip()
current_string = "".join([strip_text, text])
current_string = f"{strip_text}{text}"
if not self.validate_time(current_string):
text = ""
return super().insert_text(text, from_undo=from_undo)

View File

@ -356,7 +356,7 @@ class AutoFormatTelephoneNumber:
elif len(value) == 4:
start = self.text[:-1]
end = self.text[-1]
self.text = "%s) %s" % (start, end)
self.text = f"{start}) {end}"
self._check_cursor()
elif len(value) == 8:
self.text += "-"
@ -364,7 +364,7 @@ class AutoFormatTelephoneNumber:
elif len(value) in [12, 16]:
start = self.text[:-1]
end = self.text[-1]
self.text = "%s-%s" % (start, end)
self.text = f"{start}-{end}"
self._check_cursor()
def _check_cursor(self):

View File

@ -1371,7 +1371,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
Clock.schedule_once(self.update_floating_radius)
Clock.schedule_once(self.check_overflow_cls)
def set_headline_font_style(self, interval: Union[int, float]) -> None:
def set_headline_font_style(self, interval: int | float) -> None:
if self.type_height in ("medium", "large"):
self.ids.label_headline.font_style = {
"medium": "H6",
@ -1470,7 +1470,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
self.overflow_cls.items = self._overflow_menu_items
self.overflow_cls.caller = self.ids.right_actions.children[0]
def check_overflow_cls(self, interval: Union[int, float]) -> None:
def check_overflow_cls(self, interval: int | float) -> None:
"""
If the user does not set the :attr:`overflow_cls` attribute but uses
overflows, the :attr:`overflow_cls` attribute will use the default
@ -1537,7 +1537,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
Called when the value of the :attr:`md_bg_color` attribute changes.
"""
def on_md_bg_color(interval: Union[int, float]):
def on_md_bg_color(interval: int | float):
if self.type == "bottom":
self.md_bg_color = [0, 0, 0, 0]
else:
@ -1554,7 +1554,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
changes.
"""
def on_left_action_items(interval: Union[int, float]):
def on_left_action_items(interval: int | float):
self.update_action_bar(self.ids.left_actions, items_value)
Clock.schedule_once(on_left_action_items)
@ -1567,7 +1567,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
changes.
"""
def on_right_actions(interval: Union[int, float]):
def on_right_actions(interval: int | float):
self.update_action_bar(self.ids.right_actions, items_value)
Clock.schedule_once(on_right_actions)
@ -1599,7 +1599,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
Called when the value of the :attr:`anchor_title` attribute changes.
"""
def on_anchor_title(interval: Union[int, float]):
def on_anchor_title(interval: int | float):
self.ids.label_title.halign = anchor_value
Clock.schedule_once(on_anchor_title)
@ -1610,7 +1610,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
if self.type == "top":
return
def on_mode(interval: Union[int, float]):
def on_mode(interval: int | float):
def set_button_pos(*args):
self.action_button.x = x
self.action_button.y = y - self._rounded_rectangle_height / 2
@ -1685,7 +1685,7 @@ class MDTopAppBar(DeclarativeBehavior, NotchedBox, WindowController):
self.on_type_height(self, self.type_height)
self.update_anchor_title(material_style_value)
def update_floating_radius(self, interval: Union[int, float]) -> None:
def update_floating_radius(self, interval: int | float) -> None:
self.action_button.radius = self.action_button.width / 2
def update_anchor_title(self, material_style_value: str) -> str:

View File

@ -45,4 +45,4 @@ class FpsMonitor(Label):
Clock.schedule_interval(self.update_fps, self.updated_interval)
def update_fps(self, *args):
self._fsp_value = "FPS: %f" % Clock.get_fps()
self._fsp_value = f"FPS: {Clock.get_fps():f}"

View File

@ -11,7 +11,7 @@ parser.add_argument("-c", "--config", action='store', default=None, help="specif
parser.add_argument("-d", "--daemon", action='store_true', default=False, help="run as a daemon, without user interface")
parser.add_argument("--export-settings", action='store', default=None, help="export application settings to file")
parser.add_argument("--import-settings", action='store', default=None, help="import application settings from file")
parser.add_argument("--version", action="version", version="sideband {version}".format(version=__version__))
parser.add_argument("--version", action="version", version=f"sideband {__version__}")
args = parser.parse_args()
sys.argv = [sys.argv[0]]
@ -35,7 +35,7 @@ if args.export_settings:
load_config_only=True,
)
sideband.version_str = "v"+__version__+" "+__variant__
sideband.version_str = f"v{__version__} {__variant__}"
import json
export = sideband.config.copy()
@ -64,7 +64,7 @@ elif args.import_settings:
load_config_only=True,
)
sideband.version_str = "v"+__version__+" "+__variant__
sideband.version_str = f"v{__version__} {__variant__}"
import json
addr_fields = ["lxmf_propagation_node", "last_lxmf_propagation_node", "nn_home_node", "telemetry_collector"]
@ -106,9 +106,9 @@ if not args.daemon:
def trace(self, arg):
pass
def warning(self, arg):
RNS.log("Kivy error: "+str(arg), RNS.LOG_WARNING)
RNS.log(f"Kivy error: {arg)}", RNS.LOG_WARNING)
def critical(self, arg):
RNS.log("Kivy error: "+str(arg), RNS.LOG_ERROR)
RNS.log(f"Kivy error: {arg)}", RNS.LOG_ERROR)
if RNS.vendor.platformutils.get_platform() == "android":
import jnius.reflect
@ -272,7 +272,7 @@ class SidebandApp(MDApp):
else:
self.sideband = SidebandCore(self, config_path=self.config_path, is_client=False, verbose=(args.verbose or __debug_build__))
self.sideband.version_str = "v"+__version__+" "+__variant__
self.sideband.version_str = f"v{__version__} {__variant__}"
self.set_ui_theme()
self.font_config()
@ -318,8 +318,8 @@ class SidebandApp(MDApp):
self.key_ptt_down = False
Window.softinput_mode = "below_target"
self.icon = self.sideband.asset_dir+"/icon.png"
self.notification_icon = self.sideband.asset_dir+"/notification_icon.png"
self.icon = f"{self.sideband.asset_dir}/icon.png"
self.notification_icon = f"{self.sideband.asset_dir}/notification_icon.png"
self.connectivity_updater = None
self.last_map_update = 0
@ -370,7 +370,7 @@ class SidebandApp(MDApp):
def start_service(self):
if RNS.vendor.platformutils.is_android():
RNS.log("Running on Android API level "+str(android_api_version))
RNS.log(f"Running on Android API level {android_api_version)}")
RNS.log("Launching platform-specific service for RNS and LXMF")
if RNS.vendor.platformutils.get_platform() == "android":
@ -442,7 +442,7 @@ class SidebandApp(MDApp):
)
self.hw_error_dialog = MDDialog(
title="Hardware Error",
text="When starting a connected RNode, Reticulum reported the following error:\n\n[i]"+str(description)+"[/i]",
text=f"When starting a connected RNode, Reticulum reported the following error:\n\n[i]{description)}[/i]",
buttons=[ yes_button ],
# elevation=0,
)
@ -479,31 +479,31 @@ class SidebandApp(MDApp):
def font_config(self):
from kivy.core.text import LabelBase, DEFAULT_FONT
fb_path = self.sideband.asset_dir+"/fonts/"
fb_path = f"{self.sideband.asset_dir}/fonts/"
LabelBase.register(name="hebrew",
fn_regular=fb_path+"NotoSansHebrew-Regular.ttf",
fn_bold=fb_path+"NotoSansHebrew-Bold.ttf",)
fn_regular=f"{fb_path}NotoSansHebrew-Regular.ttf",
fn_bold=f"{fb_path}NotoSansHebrew-Bold.ttf",)
LabelBase.register(name="japanese",
fn_regular=fb_path+"NotoSansJP-Regular.ttf")
fn_regular=f"{fb_path}NotoSansJP-Regular.ttf")
LabelBase.register(name="chinese",
fn_regular=fb_path+"NotoSansSC-Regular.ttf")
fn_regular=f"{fb_path}NotoSansSC-Regular.ttf")
LabelBase.register(name="korean",
fn_regular=fb_path+"NotoSansKR-Regular.ttf")
fn_regular=f"{fb_path}NotoSansKR-Regular.ttf")
LabelBase.register(name="emoji",
fn_regular=fb_path+"NotoEmoji-Regular.ttf")
fn_regular=f"{fb_path}NotoEmoji-Regular.ttf")
LabelBase.register(name="defaultinput",
fn_regular=fb_path+"DefaultInput.ttf")
fn_regular=f"{fb_path}DefaultInput.ttf")
LabelBase.register(name="combined",
fn_regular=fb_path+"NotoSans-Regular.ttf",
fn_bold=fb_path+"NotoSans-Bold.ttf",
fn_italic=fb_path+"NotoSans-Italic.ttf",
fn_bolditalic=fb_path+"NotoSans-BoldItalic.ttf")
fn_regular=f"{fb_path}NotoSans-Regular.ttf",
fn_bold=f"{fb_path}NotoSans-Bold.ttf",
fn_italic=f"{fb_path}NotoSans-Italic.ttf",
fn_bolditalic=f"{fb_path}NotoSans-BoldItalic.ttf")
def update_input_language(self):
language = self.sideband.config["input_language"]
@ -512,7 +512,7 @@ class SidebandApp(MDApp):
else:
self.input_font = language
RNS.log("Setting input language to "+str(self.input_font), RNS.LOG_DEBUG)
RNS.log(f"Setting input language to {self.input_font)}", RNS.LOG_DEBUG)
# def modify_input_font(self, ids):
# BIND_CLASSES = ["kivymd.uix.textfield.textfield.MDTextField",]
@ -629,11 +629,11 @@ class SidebandApp(MDApp):
def share_image(self, image, filename):
if RNS.vendor.platformutils.get_platform() == "android":
save_path = self.sideband.exports_dir
file_path = save_path+"/"+filename
file_path = f"{save_path}/{filename}"
try:
if not os.path.isdir(save_path):
RNS.log("Creating directory: "+str(save_path))
RNS.log(f"Creating directory: {save_path)}")
os.makedirs(save_path)
Intent = autoclass("android.content.Intent")
@ -660,7 +660,7 @@ class SidebandApp(MDApp):
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Export Error",
text="The resource could not be exported and shared:\n\n"+str(e),
text=f"The resource could not be exported and shared:\n\n{e)}",
buttons=[ ok_button ],
)
def dl_ok(s):
@ -878,15 +878,15 @@ class SidebandApp(MDApp):
self.ingest_lxm_uri(data)
def ingest_lxm_uri(self, lxm_uri):
RNS.log("Ingesting LXMF paper message from URI: "+str(lxm_uri), RNS.LOG_DEBUG)
RNS.log(f"Ingesting LXMF paper message from URI: {lxm_uri)}", RNS.LOG_DEBUG)
self.sideband.lxm_ingest_uri(lxm_uri)
def build(self):
FONT_PATH = self.sideband.asset_dir+"/fonts"
FONT_PATH = f"{self.sideband.asset_dir}/fonts"
if RNS.vendor.platformutils.is_darwin():
self.icon = self.sideband.asset_dir+"/icon_macos_formed.png"
self.icon = f"{self.sideband.asset_dir}/icon_macos_formed.png"
else:
self.icon = self.sideband.asset_dir+"/icon.png"
self.icon = f"{self.sideband.asset_dir}/icon.png"
self.announces_view = None
@ -949,7 +949,7 @@ class SidebandApp(MDApp):
)
self.hw_error_dialog = MDDialog(
title="Hardware Error",
text="While communicating with an RNode, Reticulum reported the following error:\n\n[i]"+str(description)+"[/i]",
text=f"While communicating with an RNode, Reticulum reported the following error:\n\n[i]{description)}[/i]",
buttons=[ yes_button ],
# elevation=0,
)
@ -1076,12 +1076,12 @@ class SidebandApp(MDApp):
Window.bind(on_request_close=self.close_requested)
if __variant__ != "":
variant_str = " "+__variant__
variant_str = f" {__variant__}"
else:
variant_str = ""
self.root.ids.screen_manager.app = self
self.root.ids.app_version_info.text = "Sideband v"+__version__+variant_str
self.root.ids.app_version_info.text = f"Sideband v{__version__}{variant_str}"
self.root.ids.nav_scrollview.effect_cls = ScrollEffect
Clock.schedule_once(self.start_core, 0.25)
@ -1300,7 +1300,7 @@ class SidebandApp(MDApp):
action = "tap" if RNS.vendor.platformutils.is_android() else "click"
toast(f"Field copied, double-{action} any empty field to paste")
except Exception as e:
RNS.log("An error occurred while handling clipboard action: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while handling clipboard action: {e)}", RNS.LOG_ERROR)
def loader_init(self, sender=None):
if not self.root.ids.screen_manager.has_screen("loader_screen"):
@ -1501,7 +1501,7 @@ class SidebandApp(MDApp):
if not self.outbound_mode_command and not self.outbound_mode_paper:
if self.attach_type != None and self.attach_path != None:
try:
RNS.log("Processing "+str(self.attach_type)+" attachment \""+str(self.attach_path)+"\"", RNS.LOG_DEBUG)
RNS.log(f"Processing {self.attach_type)} attachment \"{self.attach_path)}\"", RNS.LOG_DEBUG)
fbn = os.path.basename(self.attach_path)
if self.attach_type == "file":
@ -1543,7 +1543,7 @@ class SidebandApp(MDApp):
except Exception as e:
self.messages_view.send_error_dialog = MDDialog(
title="Attachment Error",
text="An error occurred while processing the attachment:\n\n[i]"+str(e)+"[/i]",
text=f"An error occurred while processing the attachment:\n\n[i]{e)}[/i]",
buttons=[
MDRectangleFlatButton(
text="OK",
@ -1649,26 +1649,26 @@ class SidebandApp(MDApp):
self.attach_path = path
if RNS.vendor.platformutils.is_android():
toast("Attached \""+str(fbn)+"\"")
toast(f"Attached \"{fbn)}\"")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
ate_dialog = MDDialog(
title="File Attached",
text="The file \""+str(fbn)+"\" was attached, and will be included with the next message sent.",
text=f"The file \"{fbn)}\" was attached, and will be included with the next message sent.",
buttons=[ ok_button ],
)
ok_button.bind(on_release=ate_dialog.dismiss)
ate_dialog.open()
except Exception as e:
RNS.log(f"Error while attaching \"{fbn}\": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while attaching \"{fbn}\": {e)}", RNS.LOG_ERROR)
if RNS.vendor.platformutils.get_platform() == "android":
toast("Could not attach \""+str(fbn)+"\"")
toast(f"Could not attach \"{fbn)}\"")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
ate_dialog = MDDialog(
title="Attachment Error",
text="The specified file could not be attached:\n\n[i]"+str(e)+"[/i]",
text=f"The specified file could not be attached:\n\n[i]{e)}[/i]",
buttons=[ ok_button ],
)
ok_button.bind(on_release=ate_dialog.dismiss)
@ -1791,12 +1791,12 @@ class SidebandApp(MDApp):
return
if audio_field[0] == LXMF.AM_OPUS_OGG:
temp_path = self.sideband.rec_cache+"/msg.ogg"
temp_path = f"{self.sideband.rec_cache}/msg.ogg"
with open(temp_path, "wb") as af:
af.write(self.last_msg_audio)
elif audio_field[0] >= LXMF.AM_CODEC2_700C and audio_field[0] <= LXMF.AM_CODEC2_3200:
temp_path = self.sideband.rec_cache+"/msg.ogg"
temp_path = f"{self.sideband.rec_cache}/msg.ogg"
from sideband.audioproc import samples_to_ogg, decode_codec2, detect_codec2
target_rate = 8000
@ -1805,7 +1805,7 @@ class SidebandApp(MDApp):
if detect_codec2():
if samples_to_ogg(decode_codec2(audio_field[1], audio_field[0]), temp_path, input_rate=8000, output_rate=target_rate):
RNS.log("Wrote OGG file to: "+temp_path, RNS.LOG_DEBUG)
RNS.log(f"Wrote OGG file to: {temp_path}", RNS.LOG_DEBUG)
else:
RNS.log("OGG write failed", RNS.LOG_DEBUG)
else:
@ -1839,7 +1839,7 @@ class SidebandApp(MDApp):
RNS.log("Playback was requested, but no audio data was loaded for playback", RNS.LOG_ERROR)
except Exception as e:
RNS.log("Error while playing message audio:"+str(e))
RNS.log(f"Error while playing message audio:{e)}")
RNS.trace_exception(e)
def message_ptt_down_action(self, sender=None):
@ -1884,7 +1884,7 @@ class SidebandApp(MDApp):
try:
self.msg_audio.stop()
except Exception as e:
RNS.log("An error occurred while stopping recording: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while stopping recording: {e)}", RNS.LOG_ERROR)
RNS.trace_exception(e)
self.sideband.ui_stopped_recording()
@ -1936,9 +1936,9 @@ class SidebandApp(MDApp):
encoded = encode_codec2(samples, self.audio_msg_mode)
ap_duration = time.time() - ap_start
RNS.log("Audio processing complete in "+RNS.prettytime(ap_duration), RNS.LOG_DEBUG)
RNS.log(f"Audio processing complete in {RNS.prettytime(ap_duration)}", RNS.LOG_DEBUG)
export_path = self.sideband.rec_cache+"/recording.enc"
export_path = f"{self.sideband.rec_cache}/recording.enc"
with open(export_path, "wb") as export_file:
export_file.write(encoded)
self.attach_path = export_path
@ -1958,7 +1958,7 @@ class SidebandApp(MDApp):
from sbapp.plyer import audio
self.msg_audio = audio
self.msg_audio._file_path = self.sideband.rec_cache+"/recording.ogg"
self.msg_audio._file_path = f"{self.sideband.rec_cache}/recording.ogg"
def a_rec_action(sender):
if not self.rec_dialog.recording:
@ -1970,7 +1970,7 @@ class SidebandApp(MDApp):
el.theme_text_color="Custom"
el.text_color=mdc("Red","400")
el.icon = "stop-circle"
self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Stop Recording[/size]"
self.rec_dialog.rec_item.text = f"[size={ss)}]Stop Recording[/size]"
def cb(dt):
self.msg_audio.start()
Clock.schedule_once(cb, 0.10)
@ -1979,7 +1979,7 @@ class SidebandApp(MDApp):
self.sideband.ui_stopped_recording()
RNS.log("Stopping recording...") # TODO: Remove
self.rec_dialog.recording = False
self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]"
self.rec_dialog.rec_item.text = f"[size={ss)}]Start Recording[/size]"
el = self.rec_dialog.rec_item.children[0].children[0]
el.icon = "record"
el.text_color = self.theme_cls._get_text_color()
@ -1997,13 +1997,13 @@ class SidebandApp(MDApp):
RNS.log("Playing recording...", RNS.LOG_DEBUG)
self.rec_dialog.playing = True
self.rec_dialog.play_item.children[0].children[0].icon = "stop"
self.rec_dialog.play_item.text = "[size="+str(ss)+"]Stop[/size]"
self.rec_dialog.play_item.text = f"[size={ss)}]Stop[/size]"
self.msg_audio.play()
else:
RNS.log("Stopping playback...", RNS.LOG_DEBUG)
self.rec_dialog.playing = False
self.rec_dialog.play_item.children[0].children[0].icon = "play"
self.rec_dialog.play_item.text = "[size="+str(ss)+"]Play[/size]"
self.rec_dialog.play_item.text = f"[size={ss)}]Play[/size]"
self.msg_audio.stop()
self.msg_rec_a_play = a_play
@ -2012,7 +2012,7 @@ class SidebandApp(MDApp):
RNS.log("Playback finished", RNS.LOG_DEBUG)
self.rec_dialog.playing = False
self.rec_dialog.play_item.children[0].children[0].icon = "play"
self.rec_dialog.play_item.text = "[size="+str(ss)+"]Play[/size]"
self.rec_dialog.play_item.text = f"[size={ss)}]Play[/size]"
self.msg_audio._finished_callback = a_finished
@ -2045,9 +2045,9 @@ class SidebandApp(MDApp):
self.msg_rec_a_save = a_save
cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18))
rec_item = DialogItem(IconLeftWidget(icon="record", on_release=a_rec_action), text="[size="+str(ss)+"]Start Recording[/size]", on_release=a_rec_action)
play_item = DialogItem(IconLeftWidget(icon="play", on_release=a_play), text="[size="+str(ss)+"]Play[/size]", on_release=a_play, disabled=True)
save_item = DialogItem(IconLeftWidget(icon="content-save-move-outline", on_release=a_save), text="[size="+str(ss)+"]Save to message[/size]", on_release=a_save, disabled=True)
rec_item = DialogItem(IconLeftWidget(icon="record", on_release=a_rec_action), text=f"[size={ss)}]Start Recording[/size]", on_release=a_rec_action)
play_item = DialogItem(IconLeftWidget(icon="play", on_release=a_play), text=f"[size={ss)}]Play[/size]", on_release=a_play, disabled=True)
save_item = DialogItem(IconLeftWidget(icon="content-save-move-outline", on_release=a_save), text=f"[size={ss)}]Save to message[/size]", on_release=a_save, disabled=True)
self.rec_dialog = MDDialog(
title="Record Audio",
type="simple",
@ -2076,7 +2076,7 @@ class SidebandApp(MDApp):
self.rec_dialog.play_item.disabled = True
self.rec_dialog.save_item.disabled = True
self.rec_dialog.recording = False
self.rec_dialog.rec_item.text = "[size="+str(ss)+"]Start Recording[/size]"
self.rec_dialog.rec_item.text = f"[size={ss)}]Start Recording[/size]"
self.rec_dialog.rec_item.children[0].children[0].icon = "record"
self.rec_dialog.open()
@ -2125,12 +2125,12 @@ class SidebandApp(MDApp):
ss = int(dp(18))
cancel_button = MDRectangleFlatButton(text="Cancel", font_size=dp(18))
ad_items = [
DialogItem(IconLeftWidget(icon="message-image-outline", on_release=a_img_lb), text="[size="+str(ss)+"]Low-bandwidth Image[/size]", on_release=a_img_lb),
DialogItem(IconLeftWidget(icon="file-image", on_release=a_img_def), text="[size="+str(ss)+"]Medium Image[/size]", on_release=a_img_def),
DialogItem(IconLeftWidget(icon="image-outline", on_release=a_img_hq), text="[size="+str(ss)+"]High-res Image[/size]", on_release=a_img_hq),
DialogItem(IconLeftWidget(icon="account-voice", on_release=a_audio_lb), text="[size="+str(ss)+"]Low-bandwidth Voice[/size]", on_release=a_audio_lb),
DialogItem(IconLeftWidget(icon="microphone-message", on_release=a_audio_hq), text="[size="+str(ss)+"]High-quality Voice[/size]", on_release=a_audio_hq),
DialogItem(IconLeftWidget(icon="file-outline", on_release=a_file), text="[size="+str(ss)+"]File Attachment[/size]", on_release=a_file)]
DialogItem(IconLeftWidget(icon="message-image-outline", on_release=a_img_lb), text=f"[size={ss)}]Low-bandwidth Image[/size]", on_release=a_img_lb),
DialogItem(IconLeftWidget(icon="file-image", on_release=a_img_def), text=f"[size={ss)}]Medium Image[/size]", on_release=a_img_def),
DialogItem(IconLeftWidget(icon="image-outline", on_release=a_img_hq), text=f"[size={ss)}]High-res Image[/size]", on_release=a_img_hq),
DialogItem(IconLeftWidget(icon="account-voice", on_release=a_audio_lb), text=f"[size={ss)}]Low-bandwidth Voice[/size]", on_release=a_audio_lb),
DialogItem(IconLeftWidget(icon="microphone-message", on_release=a_audio_hq), text=f"[size={ss)}]High-quality Voice[/size]", on_release=a_audio_hq),
DialogItem(IconLeftWidget(icon="file-outline", on_release=a_file), text=f"[size={ss)}]File Attachment[/size]", on_release=a_file)]
if RNS.vendor.platformutils.is_windows():
ad_items.pop(3)
@ -2204,7 +2204,7 @@ class SidebandApp(MDApp):
def key_query_action(self, sender):
context_dest = self.messages_view.ids.messages_scrollview.active_conversation
if self.sideband.request_key(context_dest):
keys_str = "Public key information for "+RNS.prettyhexrep(context_dest)+" was requested from the network. Waiting for request to be answered."
keys_str = f"Public key information for {RNS.prettyhexrep(context_dest)} was requested from the network. Waiting for request to be answered."
self.messages_view.ids.nokeys_text.text = keys_str
else:
keys_str = "Could not send request. Check your connectivity and addresses."
@ -2299,7 +2299,7 @@ class SidebandApp(MDApp):
return connectivity_status
except Exception as e:
RNS.log("An error occurred while retrieving connectivity status: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while retrieving connectivity status: {e)}", RNS.LOG_ERROR)
return "Could not retrieve connectivity status"
def connectivity_status(self, sender):
@ -2346,14 +2346,14 @@ class SidebandApp(MDApp):
def dl_yes(s):
try:
lxm_uri = Clipboard.paste()
if not lxm_uri.lower().startswith(LXMF.LXMessage.URI_SCHEMA+"://"):
lxm_uri = LXMF.LXMessage.URI_SCHEMA+"://"+lxm_uri
if not lxm_uri.lower().startswith(f"{LXMF.LXMessage.URI_SCHEMA}://"):
lxm_uri = f"{LXMF.LXMessage.URI_SCHEMA}://{lxm_uri}"
self.ingest_lxm_uri(lxm_uri)
dialog.dismiss()
except Exception as e:
response = "Error ingesting message from URI: "+str(e)
response = f"Error ingesting message from URI: {e)}"
RNS.log(response, RNS.LOG_ERROR)
self.sideband.setstate("lxm_uri_ingest.result", response)
dialog.dismiss()
@ -2372,7 +2372,7 @@ class SidebandApp(MDApp):
self.dialog_open = True
except Exception as e:
RNS.log("Error while creating ingest LXM dialog: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while creating ingest LXM dialog: {e)}", RNS.LOG_ERROR)
def lxmf_sync_action(self, sender):
def cb(dt):
@ -2406,7 +2406,7 @@ class SidebandApp(MDApp):
dialog_content = MsgSync()
dialog = MDDialog(
title="LXMF Sync via "+RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node()),
title=f"LXMF Sync via {RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node())}",
type="custom",
content_cls=dialog_content,
buttons=[ stop_button, close_button ],
@ -2443,7 +2443,7 @@ class SidebandApp(MDApp):
dsp = 0
self.sideband.setstate("app.flags.lxmf_sync_dialog_open", True)
self.message_sync_dialog.title = f"LXMF Sync via "+RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node())
self.message_sync_dialog.title = f"LXMF Sync via {RNS.prettyhexrep(self.sideband.message_router.get_outbound_propagation_node())}"
self.message_sync_dialog.d_content.ids.sync_status.text = self.sideband.get_sync_status()
self.message_sync_dialog.d_content.ids.sync_progress.value = dsp
self.message_sync_dialog.d_content.ids.sync_progress.start()
@ -2484,7 +2484,7 @@ class SidebandApp(MDApp):
new_result = self.sideband.new_conversation(n_address, n_name, n_trusted)
except Exception as e:
RNS.log("Error while creating conversation: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while creating conversation: {e)}", RNS.LOG_ERROR)
if new_result:
dialog.d_content.ids["n_address_field"].error = False
@ -2509,7 +2509,7 @@ class SidebandApp(MDApp):
self.dialog_open = True
except Exception as e:
RNS.log("Error while creating new conversation dialog: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while creating new conversation dialog: {e)}", RNS.LOG_ERROR)
### Information/version screen
######################################
@ -2537,14 +2537,14 @@ class SidebandApp(MDApp):
threading.Thread(target=lj, daemon=True).start()
self.information_screen.ids.information_scrollview.effect_cls = ScrollEffect
self.information_screen.ids.information_logo.icon = self.sideband.asset_dir+"/rns_256.png"
self.information_screen.ids.information_logo.icon = f"{self.sideband.asset_dir}/rns_256.png"
str_comps = " - [b]Reticulum[/b] (MIT License)\n - [b]LXMF[/b] (MIT License)\n - [b]KivyMD[/b] (MIT License)"
str_comps += "\n - [b]Kivy[/b] (MIT License)\n - [b]Codec2[/b] (LGPL License)\n - [b]PyCodec2[/b] (BSD-3 License)"
str_comps += "\n - [b]PyDub[/b] (MIT License)\n - [b]PyOgg[/b] (Public Domain)"
str_comps += "\n - [b]GeoidHeight[/b] (LGPL License)\n - [b]Python[/b] (PSF License)"
str_comps += "\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright (c) 2024 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of "+self.root.ids.app_version_info.text+", so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY"
info = "This is "+self.root.ids.app_version_info.text+", on RNS v"+RNS.__version__+" and LXMF v"+LXMF.__version__+".\n\nHumbly build using the following open components:\n\n"+str_comps
str_comps += f"\n\nGo to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project.\n\nThe Sideband app is Copyright (c) 2024 Mark Qvist / unsigned.io\n\nPermission is granted to freely share and distribute binary copies of {self.root.ids.app_version_info.text}, so long as no payment or compensation is charged for said distribution or sharing.\n\nIf you were charged or paid anything for this copy of Sideband, please report it to [b]license@unsigned.io[/b].\n\nTHIS IS EXPERIMENTAL SOFTWARE - SIDEBAND COMES WITH ABSOLUTELY NO WARRANTY - USE AT YOUR OWN RISK AND RESPONSIBILITY"
info = f"This is {self.root.ids.app_version_info.text}, on RNS v{RNS.__version__} and LXMF v{LXMF.__version__}.\n\nHumbly build using the following open components:\n\n{str_comps}"
self.information_screen.ids.information_info.text = info
self.information_screen.ids.information_info.bind(on_ref_press=link_exec)
@ -2846,7 +2846,7 @@ class SidebandApp(MDApp):
interval_text = RNS.prettytime(interval)
pre = self.settings_screen.ids.settings_lxmf_sync_periodic.text
self.settings_screen.ids.settings_lxmf_sync_periodic.text = "Auto sync every "+interval_text
self.settings_screen.ids.settings_lxmf_sync_periodic.text = f"Auto sync every {interval_text}"
if save:
if (event == None or not hasattr(event, "button") or not event.button) or not "scroll" in event.button:
self.sideband.config["lxmf_sync_interval"] = interval
@ -3201,7 +3201,7 @@ class SidebandApp(MDApp):
all_valid = True
iftypes = ["local", "tcp", "i2p", "rnode", "modem", "serial"]
for iftype in iftypes:
element = self.connectivity_screen.ids["connectivity_"+iftype+"_ifmode"]
element = self.connectivity_screen.ids[f"connectivity_{iftype}_ifmode"]
modes = ["full", "gateway", "access point", "roaming", "boundary"]
value = element.text.lower()
if value in ["", "f"] or value.startswith("fu"):
@ -3356,7 +3356,7 @@ class SidebandApp(MDApp):
dialog.dismiss()
yes_button.bind(on_release=dl_yes)
rpc_string = "rpc_key = "+RNS.hexrep(self.sideband.reticulum.rpc_key, delimit=False)
rpc_string = f"rpc_key = {RNS.hexrep(self.sideband.reticulum.rpc_key, delimit=False)}"
Clipboard.copy(rpc_string)
dialog.open()
@ -3427,7 +3427,7 @@ class SidebandApp(MDApp):
adrs.append(ha)
except Exception as e:
RNS.log("Error while getting repository IP address: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while getting repository IP address: {e)}", RNS.LOG_ERROR)
return None
return adrs
@ -3439,11 +3439,11 @@ class SidebandApp(MDApp):
else:
ipstr = ""
for ip in ips:
ipstr += "http://"+str(ip)+":4444/\n"
ipstr += f"http://{ip)}:4444/\n"
self.reposository_url = ipstr
ms = "" if len(ips) == 1 else "es"
info += "The repository server is running at the following address"+ms+":\n [u][ref=link]"+ipstr+"[/ref][u]"
info += f"The repository server is running at the following address{ms}:\n [u][ref=link]{ipstr}[/ref][u]"
self.repository_screen.ids.repository_info.bind(on_ref_press=self.repository_link_action)
self.repository_screen.ids.repository_enable_button.disabled = True
@ -3487,10 +3487,10 @@ class SidebandApp(MDApp):
apk_version = release["tag_name"]
RNS.log(f"Found version {apk_version} artefact {pkgname} at {apk_url}")
except Exception as e:
self.repository_screen.ids.repository_update.text = f"Downloading release info failed with the error:\n"+str(e)
self.repository_screen.ids.repository_update.text = f"Downloading release info failed with the error:\n{e)}"
return
self.repository_screen.ids.repository_update.text = "Downloading: "+str(apk_url)
self.repository_screen.ids.repository_update.text = f"Downloading: {apk_url)}"
with requests.get(apk_url, stream=True) as response:
with open("./dl_tmp", "wb") as tmp_file:
cs = 32*1024
@ -3498,12 +3498,12 @@ class SidebandApp(MDApp):
for chunk in response.iter_content(chunk_size=cs):
tmp_file.write(chunk)
tds += cs
self.repository_screen.ids.repository_update.text = "Downloaded "+RNS.prettysize(tds)+" of "+str(pkgname)
self.repository_screen.ids.repository_update.text = f"Downloaded {RNS.prettysize(tds)} of {pkgname)}"
os.rename("./dl_tmp", f"./share/pkg/{pkgname}")
self.repository_screen.ids.repository_update.text = f"Added {pkgname} to the repository!"
except Exception as e:
self.repository_screen.ids.repository_update.text = f"Downloading contents failed with the error:\n"+str(e)
self.repository_screen.ids.repository_update.text = f"Downloading contents failed with the error:\n{e)}"
self.repository_screen.ids.repository_update.text = "Starting package download..."
def start_update_job(sender=None):
@ -3996,7 +3996,7 @@ class SidebandApp(MDApp):
yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Import Failed",
text="The read data did not contain a valid config mote. If any data was decoded, you may try to correct it by editing the relevant fields. The reported error was:\n\n"+str(e),
text=f"The read data did not contain a valid config mote. If any data was decoded, you may try to correct it by editing the relevant fields. The reported error was:\n\n{e)}",
buttons=[ yes_button ],
# elevation=0,
)
@ -4550,7 +4550,7 @@ class SidebandApp(MDApp):
yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
text="Your Identity key, in base32 format is as follows:\n\n[b]"+str(base64.b32encode(self.sideband.identity.get_private_key()).decode("utf-8"))+"[/b]",
text=f"Your Identity key, in base32 format is as follows:\n\n[b]{base64.b32encode(self.sideband.identity.get_private_key()).decode('utf-8'))}[/b]",
buttons=[ yes_button ],
# elevation=0,
)
@ -4613,7 +4613,7 @@ class SidebandApp(MDApp):
except Exception as e:
yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(text="[b]The provided Identity key data was not valid[/b]\n\nThe error reported by Reticulum was:\n\n[i]"+str(e)+"[/i]\n\nNo Identity was imported into Sideband.", buttons=[ yes_button ])
dialog = MDDialog(text=f"[b]The provided Identity key data was not valid[/b]\n\nThe error reported by Reticulum was:\n\n[i]{e)}[/i]\n\nNo Identity was imported into Sideband.", buttons=[ yes_button ])
def dl_yes(s):
dialog.dismiss()
yes_button.bind(on_release=dl_yes)
@ -4697,26 +4697,26 @@ class SidebandApp(MDApp):
self.sideband.save_configuration()
if RNS.vendor.platformutils.is_android():
toast("Using \""+str(path)+"\" as plugin directory")
toast(f"Using \"{path)}\" as plugin directory")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
ate_dialog = MDDialog(
title="Directory Set",
text="Using \""+str(path)+"\" as plugin directory",
text=f"Using \"{path)}\" as plugin directory",
buttons=[ ok_button ],
)
ok_button.bind(on_release=ate_dialog.dismiss)
ate_dialog.open()
except Exception as e:
RNS.log(f"Error while setting plugins directory to \"{path}\": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while setting plugins directory to \"{path}\": {e)}", RNS.LOG_ERROR)
if RNS.vendor.platformutils.get_platform() == "android":
toast("Could not set plugins directory to \""+str(path)+"\"")
toast(f"Could not set plugins directory to \"{path)}\"")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
e_dialog = MDDialog(
title="Error",
text="Could not set plugins directory to \""+str(path)+"\"",
text=f"Could not set plugins directory to \"{path)}\"",
buttons=[ ok_button ],
)
ok_button.bind(on_release=e_dialog.dismiss)
@ -4875,7 +4875,7 @@ class SidebandApp(MDApp):
info_str = "There was no new data to send."
else:
title_str = "Unknown Status"
info_str = "The status of the telemetry update is unknown: "+str(result)
info_str = f"The status of the telemetry update is unknown: {result)}"
self.telemetry_info_dialog.title = title_str
self.telemetry_info_dialog.text = info_str
@ -4913,7 +4913,7 @@ class SidebandApp(MDApp):
info_str = "A telemetry request could not be sent."
else:
title_str = "Unknown Status"
info_str = "The status of the telemetry request is unknown: "+str(result)
info_str = f"The status of the telemetry request is unknown: {result)}"
self.telemetry_info_dialog.title = title_str
self.telemetry_info_dialog.text = info_str
@ -4932,21 +4932,21 @@ class SidebandApp(MDApp):
self.sideband.save_configuration()
if RNS.vendor.platformutils.is_android():
toast("Using \""+os.path.basename(path)+"\" as offline map")
toast(f"Using \"{os.path.basename(path)}\" as offline map")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
ate_dialog = MDDialog(
title="Map Set",
text="Using \""+os.path.basename(path)+"\" as offline map",
text=f"Using \"{os.path.basename(path)}\" as offline map",
buttons=[ ok_button ],
)
ok_button.bind(on_release=ate_dialog.dismiss)
ate_dialog.open()
except Exception as e:
RNS.log(f"Error while loading map \"{path}\": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while loading map \"{path}\": {e)}", RNS.LOG_ERROR)
if RNS.vendor.platformutils.get_platform() == "android":
toast("Could not load map \""+os.path.basename(path)+"\"")
toast(f"Could not load map \"{os.path.basename(path)}\"")
else:
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
map_dialog = MDDialog(
@ -5041,7 +5041,7 @@ class SidebandApp(MDApp):
return self.offline_source
except Exception as e:
RNS.log(f"Error while loading map from \"{current_map_path}\": "+str(e))
RNS.log(f"Error while loading map from \"{current_map_path}\": {e)}")
self.sideband.config["map_storage_file"] = None
self.sideband.config["map_use_offline"] = False
self.sideband.config["map_use_online"] = True
@ -5114,7 +5114,7 @@ class SidebandApp(MDApp):
self.map_layer = ml
self.map_update_source(source)
except Exception as e:
RNS.log("Error while switching map layer: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while switching map layer: {e)}", RNS.LOG_ERROR)
map_nav_divisor = 12
map_nav_zoom = 0.25
@ -5479,7 +5479,7 @@ class SidebandApp(MDApp):
return marker
except Exception as e:
RNS.log("Could not create map marker for "+RNS.prettyhexrep(source)+": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Could not create map marker for {RNS.prettyhexrep(source)}: {e)}", RNS.LOG_ERROR)
return None
def map_update_markers(self, sender=None):
@ -5546,17 +5546,17 @@ class SidebandApp(MDApp):
stale_markers.append(marker)
for marker in stale_markers:
RNS.log("Removing stale marker: "+str(marker), RNS.LOG_DEBUG)
RNS.log(f"Removing stale marker: {marker)}", RNS.LOG_DEBUG)
try:
to_remove = self.map_markers[marker]
self.map_screen.ids.map_layout.map.remove_marker(to_remove)
self.map_markers.pop(marker)
changes = True
except Exception as e:
RNS.log("Error while removing map marker: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while removing map marker: {e)}", RNS.LOG_ERROR)
except Exception as e:
RNS.log("Error while updating own map marker: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while updating own map marker: {e)}", RNS.LOG_ERROR)
for telemetry_source in telemetry_entries:
try:
@ -5601,7 +5601,7 @@ class SidebandApp(MDApp):
changes = True
except Exception as e:
RNS.log("Error while updating map entry for "+RNS.prettyhexrep(telemetry_source)+": "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while updating map entry for {RNS.prettyhexrep(telemetry_source)}: {e)}", RNS.LOG_ERROR)
self.last_map_update = time.time()
if changes:
@ -5740,16 +5740,16 @@ Thank you very much for using Free Communications Systems.
info9 = guide_text9
if self.theme_cls.theme_style == "Dark":
info1 = "[color=#"+dark_theme_text_color+"]"+info1+"[/color]"
info2 = "[color=#"+dark_theme_text_color+"]"+info2+"[/color]"
info3 = "[color=#"+dark_theme_text_color+"]"+info3+"[/color]"
info4 = "[color=#"+dark_theme_text_color+"]"+info4+"[/color]"
info5 = "[color=#"+dark_theme_text_color+"]"+info5+"[/color]"
info6 = "[color=#"+dark_theme_text_color+"]"+info6+"[/color]"
info7 = "[color=#"+dark_theme_text_color+"]"+info7+"[/color]"
info8 = "[color=#"+dark_theme_text_color+"]"+info8+"[/color]"
info9 = "[color=#"+dark_theme_text_color+"]"+info9+"[/color]"
info10 = "[color=#"+dark_theme_text_color+"]"+info10+"[/color]"
info1 = f"[color=#{dark_theme_text_color}]{info1}[/color]"
info2 = f"[color=#{dark_theme_text_color}]{info2}[/color]"
info3 = f"[color=#{dark_theme_text_color}]{info3}[/color]"
info4 = f"[color=#{dark_theme_text_color}]{info4}[/color]"
info5 = f"[color=#{dark_theme_text_color}]{info5}[/color]"
info6 = f"[color=#{dark_theme_text_color}]{info6}[/color]"
info7 = f"[color=#{dark_theme_text_color}]{info7}[/color]"
info8 = f"[color=#{dark_theme_text_color}]{info8}[/color]"
info9 = f"[color=#{dark_theme_text_color}]{info9}[/color]"
info10 = f"[color=#{dark_theme_text_color}]{info10}[/color]"
self.guide_screen.ids.guide_info1.text = info1
self.guide_screen.ids.guide_info2.text = info2
self.guide_screen.ids.guide_info3.text = info3
@ -5788,7 +5788,7 @@ Thank you very much for using Free Communications Systems.
info = "The [b]Local Broadcasts[/b] feature will allow you to send and listen for local broadcast transmissions on all connected interfaces.\n\n[b]Local Broadcasts[/b] makes it easy to establish public information exchange with anyone in direct radio range, or even with large areas far away using the [i]Remote Broadcast Repeater[/i] feature.\n\nThese features are not yet implemented in Sideband.\n\nWant it faster? Go to [u][ref=link]https://unsigned.io/donate[/ref][/u] to support the project."
if self.theme_cls.theme_style == "Dark":
info = "[color=#"+dark_theme_text_color+"]"+info+"[/color]"
info = f"[color=#{dark_theme_text_color}]{info}[/color]"
self.broadcasts_screen.ids.broadcasts_info.text = info
self.root.ids.screen_manager.current = "broadcasts_screen"
@ -5830,7 +5830,7 @@ if not args.daemon:
if etype != SystemExit:
import traceback
exception_info = "".join(traceback.TracebackException.from_exception(e).format())
RNS.log(f"An unhandled {str(type(e))} exception occurred: {str(e)}", RNS.LOG_ERROR)
RNS.log(f"An unhandled {type(e))} exception occurred: {e)}", RNS.LOG_ERROR)
RNS.log(exception_info, RNS.LOG_ERROR)
return ExceptionManager.PASS
else:
@ -5847,7 +5847,7 @@ def run():
is_daemon=True
)
sideband.version_str = "v"+__version__+" "+__variant__
sideband.version_str = f"v{__version__} {__variant__}"
sideband.start()
while True:
time.sleep(5)

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
MapView
=======

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
Layer that support point clustering
===================================
@ -265,9 +264,7 @@ class Marker:
self.widget = None
def __repr__(self):
return "<Marker lon={} lat={} source={}>".format(
self.lon, self.lat, self.source
)
return f"<Marker lon={self.lon} lat={self.lat} source={self.source}>"
class SuperCluster:

View File

@ -1,5 +1,3 @@
# coding=utf-8
__all__ = ["Downloader"]
import logging
@ -52,7 +50,7 @@ class Downloader:
self._futures = []
Clock.schedule_interval(self._check_executor, 1 / 60.0)
if not exists(self.cache_dir):
RNS.log("Creating cache dir "+str(self.cache_dir), RNS.LOG_WARNING)
RNS.log(f"Creating cache dir {self.cache_dir)}", RNS.LOG_WARNING)
makedirs(self.cache_dir)
logging.getLogger("urllib3").setLevel(logging.WARNING)
@ -134,7 +132,7 @@ class Downloader:
# Logger.debug("Downloaded {} bytes: {}".format(len(data), uri))
return tile.set_source, (cache_fn,)
except Exception as e:
print("Downloader error: {!r}".format(e))
print(f"Downloader error: {e!r}")
def _check_executor(self, dt):
start = time()

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
Geojson layer
=============

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
MBTiles provider for MapView
============================
@ -87,7 +86,7 @@ class MBTilesMapSource(MapSource):
im = CoreImage(
data,
ext='png',
filename="{}.{}.{}.png".format(tile.zoom, tile.tile_x, tile.tile_y),
filename=f"{tile.zoom}.{tile.tile_x}.{tile.tile_y}.png",
)
if im is None:

View File

@ -1,5 +1,3 @@
# coding=utf-8
__all__ = ["MapSource"]
import hashlib

View File

@ -1,5 +1,3 @@
# coding=utf-8
__all__ = ["Coordinate", "Bbox"]
from collections import namedtuple

View File

@ -1,5 +1,3 @@
# coding=utf-8
__all__ = ["clamp", "haversine", "get_zoom_for_radius"]
from math import asin, cos, pi, radians, sin, sqrt

View File

@ -1,5 +1,3 @@
# coding=utf-8
__all__ = ["MapView", "MapMarker", "MapMarkerPopup", "MapLayer", "MarkerMapLayer"]
import webbrowser
@ -174,7 +172,7 @@ class CustomMapMarker(ButtonBehavior, Image):
else:
self.source = join(dirname(__file__), "icons", "marker_dark.png")
super(CustomMapMarker, self).__init__(**kwargs)
super().__init__(**kwargs)
self.texture_update()
def detach(self):
@ -212,7 +210,7 @@ class MapMarker(ButtonBehavior, Image):
_layer = None
def __init__(self, **kwargs):
super(MapMarker, self).__init__(**kwargs)
super().__init__(**kwargs)
self.texture_update()
def detach(self):
@ -312,7 +310,7 @@ class MarkerMapLayer(MapLayer):
bbox = None
# reposition the markers depending the latitude
markers = sorted(self.markers, key=lambda x: -x.lat)
margin = max((max(marker.size) for marker in markers))
margin = max(max(marker.size) for marker in markers)
bbox = mapview.get_bbox(margin)
for marker in markers:
if bbox.collide(marker.lat, marker.lon):
@ -783,7 +781,7 @@ class MapView(Widget):
# self.animated_diff_scale_at(2.0 - cur_scale, *touch.pos)
self._pause = False
return True
return super(MapView, self).on_touch_up(touch)
return super().on_touch_up(touch)
def on_transform(self, *args):
self._invalid_scale = True

View File

@ -24,7 +24,7 @@ import jinja2
def get_dist_info_for(key, error_if_missing=True):
try:
with open(join(dirname(__file__), 'dist_info.json'), 'r') as fileh:
with open(join(dirname(__file__), 'dist_info.json')) as fileh:
info = json.load(fileh)
value = info[key]
except (OSError, KeyError) as e:
@ -496,7 +496,7 @@ main.py that loads it.''')
)
# Find the SDK directory and target API
with open('project.properties', 'r') as fileh:
with open('project.properties') as fileh:
target = fileh.read().strip()
android_api = target.split('-')[1]
@ -509,7 +509,7 @@ main.py that loads it.''')
str(android_api) + "'"
)
with open('local.properties', 'r') as fileh:
with open('local.properties') as fileh:
sdk_dir = fileh.read().strip()
sdk_dir = sdk_dir[8:]
@ -730,7 +730,7 @@ def get_manifest_orientation(orientations, manifest_orientation=None):
def get_dist_ndk_min_api_level():
# Get the default minsdk, equal to the NDK API that this dist is built against
try:
with open('dist_info.json', 'r') as fileh:
with open('dist_info.json') as fileh:
info = json.load(fileh)
ndk_api = int(info['ndk_api'])
except (OSError, KeyError, ValueError, TypeError):

View File

@ -94,7 +94,7 @@ class Audio:
# private
def _start(self):
raise IOError("JUICE")
raise OSError("JUICE")
raise NotImplementedError()
def _stop(self):

View File

@ -1,4 +1,3 @@
# coding=utf-8
'''
Flash
=====

View File

@ -1,6 +1,3 @@
# coding=utf-8
class SpatialOrientation:
'''Spatial Orientation facade.

View File

@ -1,6 +1,3 @@
# coding=utf-8
class Temperature:
'''Temperature facade.

View File

@ -11,8 +11,8 @@ except (ImportError, AttributeError):
ns = 'org.renpy.android'
if 'PYTHON_SERVICE_ARGUMENT' in environ:
PythonService = autoclass(ns + '.PythonService')
PythonService = autoclass(f"{ns}.PythonService")
activity = PythonService.mService
else:
PythonActivity = autoclass(ns + '.PythonActivity')
PythonActivity = autoclass(f"{ns}.PythonActivity")
activity = PythonActivity.mActivity

View File

@ -72,7 +72,7 @@ class AndroidAudio(Audio):
self._recorder.stop()
self._recorder.release()
except Exception as e:
print("Could not stop recording: "+str(e))
print(f"Could not stop recording: {e)}")
self._recorder = None
@ -81,7 +81,7 @@ class AndroidAudio(Audio):
self._player.stop()
self._player.release()
except Exception as e:
print("Could not stop playback: "+str(e))
print(f"Could not stop playback: {e)}")
self._player = None

View File

@ -17,7 +17,7 @@ class AndroidCall(Call):
intent = Intent(Intent.ACTION_CALL)
tel = kwargs.get('tel')
intent.setData(uri.parse("tel:{}".format(tel)))
intent.setData(uri.parse(f"tel:{tel}"))
activity.startActivity(intent)
def _dialcall(self, **kwargs):

View File

@ -20,7 +20,7 @@ class AndroidCamera(Camera):
android.activity.unbind(on_activity_result=self._on_activity_result)
android.activity.bind(on_activity_result=self._on_activity_result)
intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
uri = Uri.parse('file://' + filename)
uri = Uri.parse(f"file://{filename}")
parcelable = cast('android.os.Parcelable', uri)
intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable)
activity.startActivityForResult(intent, 0x123)
@ -32,7 +32,7 @@ class AndroidCamera(Camera):
android.activity.unbind(on_activity_result=self._on_activity_result)
android.activity.bind(on_activity_result=self._on_activity_result)
intent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
uri = Uri.parse('file://' + filename)
uri = Uri.parse(f"file://{filename}")
parcelable = cast('android.os.Parcelable', uri)
intent.putExtra(MediaStore.EXTRA_OUTPUT, parcelable)

View File

@ -93,8 +93,7 @@ class AndroidFileChooser(FileChooser):
"pptx": "application/vnd.openxmlformats-officedocument." +
"presentationml.presentation",
"xls": "application/vnd.ms-excel",
"xlsx": "application/vnd.openxmlformats-officedocument." +
"spreadsheetml.sheet",
"xlsx": f"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"text": "text/*",
"pdf": "application/pdf",
"zip": "application/zip",

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
Flash
-----

View File

@ -55,8 +55,7 @@ class _LocationListener(PythonJavaClass):
s_status = 'temporarily-unavailable'
elif status == 0x02:
s_status = 'available'
self.root.on_status('provider-status', '{}: {}'.format(
provider, s_status))
self.root.on_status('provider-status', f'{provider}: {s_status}')
class AndroidGPS(GPS):

View File

@ -134,7 +134,7 @@ class SpeechListener(PythonJavaClass):
msg = 'speech_timeout'
if msg and self.error_callback:
self.error_callback('error:' + msg)
self.error_callback(f"error:{msg}")
@java_method('(ILandroid/os/Bundle;)V')
def onEvent(self, event_type, params):

View File

@ -15,7 +15,7 @@ class IOSCall(Call):
def _makecall(self, **kwargs):
tel = kwargs.get('tel')
url = "tel://" + tel
url = f"tel://{tel}"
nsurl = NSURL.alloc().initWithString_(objc_str(url))
UIApplication.sharedApplication().openURL_(nsurl)

View File

@ -1,4 +1,3 @@
# coding=utf-8
"""
Flash
-----

View File

@ -50,8 +50,7 @@ class IosGPS(GPS):
elif status == 4:
provider_status = 'provider-enabled'
s_status = 'authorizedWhenInUse'
self.on_status(provider_status, '{}: {}'.format(
provider, s_status))
self.on_status(provider_status, f'{provider}: {s_status}')
@protocol('CLLocationManagerDelegate')
def locationManager_didUpdateLocations_(self, manager, locations):
@ -60,7 +59,7 @@ class IosGPS(GPS):
description = location.description.UTF8String()
split_description = description.split('<')[-1].split('>')[0].split(',')
lat, lon = [float(coord) for coord in split_description]
lat, lon = (float(coord) for coord in split_description)
acc = float(description.split(' +/- ')[-1].split('m ')[0])
speed = location.speed

View File

@ -18,7 +18,7 @@ class iOSMaps(Maps):
'''
address = quote_plus(address, safe=',')
maps_address = 'http://maps.apple.com/?address=' + address
maps_address = f"http://maps.apple.com/?address={address}"
webbrowser.open(maps_address)
@ -31,8 +31,7 @@ class iOSMaps(Maps):
'''
name = kwargs.get("name", "Selected Location")
maps_address = 'http://maps.apple.com/?ll={},{}&q={}'.format(
latitude, longitude, name)
maps_address = f'http://maps.apple.com/?ll={latitude},{longitude}&q={name}'
webbrowser.open(maps_address)
@ -51,10 +50,10 @@ class iOSMaps(Maps):
longitude = kwargs.get('longitude')
query = quote_plus(query, safe=',')
maps_address = 'http://maps.apple.com/?q=' + query
maps_address = f"http://maps.apple.com/?q={query}"
if latitude is not None and longitude is not None:
maps_address += '&sll={},{}'.format(latitude, longitude)
maps_address += f'&sll={latitude},{longitude}'
webbrowser.open(maps_address)
@ -66,8 +65,7 @@ class iOSMaps(Maps):
saddr = quote_plus(saddr, safe=',')
daddr = quote_plus(daddr, safe=',')
maps_address = 'http://maps.apple.com/?saddr={}&daddr={}'.format(
saddr, daddr)
maps_address = f'http://maps.apple.com/?saddr={saddr}&daddr={daddr}'
webbrowser.open(maps_address)

View File

@ -22,7 +22,7 @@ class LinuxAccelerometer(Accelerometer):
except IndexError:
raise Exception('Could not enable accelerometer!')
with open(pos, "r") as p:
with open(pos) as p:
t = p.read()
coords = re.findall(r"[-]?\d+\.?\d*", t)
# Apparently the acceleration on sysfs goes from -1000 to 1000.

View File

@ -83,7 +83,7 @@ class LinuxCPU(CPU):
else:
present = [present[0]]
cores = ['cpu{}'.format(i) for i in present]
cores = [f'cpu{i}' for i in present]
for core in cores:
indicies = [
# get 'indexN' files from 'cache' folder assuming
@ -97,7 +97,7 @@ class LinuxCPU(CPU):
index_type = join(cpu_path, core, 'cache', index, 'level')
with open(index_type, 'rb') as fle:
cache_level = fle.read().decode('utf-8').strip()
values['L{}'.format(cache_level)] += 1
values[f'L{cache_level}'] += 1
return values
@staticmethod

View File

@ -127,7 +127,7 @@ class ZenityFileChooser(SubprocessFileChooser):
else:
cmdline += [
"--file-filter",
"{name} | {flt}".format(name=f[0], flt=" ".join(f[1:]))
f"{f[0]} | {' '.join(f[1:])}"
]
return cmdline
@ -220,7 +220,7 @@ class YADFileChooser(SubprocessFileChooser):
else:
cmdline += [
"--file-filter",
"{name} | {flt}".format(name=f[0], flt=" ".join(f[1:]))
f"{f[0]} | {' '.join(f[1:])}"
]
return cmdline

View File

@ -23,7 +23,7 @@ class NotifyDesktopPortals(Notification):
"org.freedesktop.portal.Desktop",
"--object-path", "/org/freedesktop/portal/desktop", "--method",
"org.freedesktop.portal.Notification.AddNotification", "",
"{'title': <'" + title + "'>, 'body': <'" + body + "'>}"
f"{{'title': <'{title}'>, 'body': <'{body}'>}}"
], stdout=subprocess.DEVNULL)

View File

@ -28,9 +28,9 @@ class LinuxStoragePath(StoragePath):
if not exists(user_dirs):
return default
with open(user_dirs, "r") as f:
with open(user_dirs) as f:
for line in f.readlines():
if line.startswith("XDG_" + name):
if line.startswith(f"XDG_{name}"):
return line.split('"')[1]
return default
@ -39,7 +39,7 @@ class LinuxStoragePath(StoragePath):
return expanduser('~')
def _get_external_storage_dir(self):
return "/media/" + self._get_home_dir().split("/")[-1]
return f"/media/{self._get_home_dir().split('/')[-1]}"
def _get_root_dir(self):
return "/"

View File

@ -21,14 +21,14 @@ class LinuxUniqueID(UniqueID):
stdout=PIPE, stderr=PIPE
).communicate()[0].decode('utf-8')
output = u''
output = ''
for line in stdout.splitlines():
if 'serial:' not in line:
continue
output = line
break
environ['LANG'] = old_lang or u''
environ['LANG'] = old_lang or ''
result = None
if output:

View File

@ -13,8 +13,7 @@ try:
import wifi
except ModuleNotFoundError as err:
raise ModuleNotFoundError(
"python-wifi not installed. try:" +
"`pip install --user wifi`.") from err
f"python-wifi not installed. try:`pip install --user wifi`.") from err
class NMCLIWifi(Wifi):
@ -170,7 +169,7 @@ class NMCLIWifi(Wifi):
ret_list['signal'] = self.names[name]['SIGNAL']
bars = len(self.names[name]['BARS'])
ret_list['quality'] = '{}/100'.format(bars / 5.0 * 100)
ret_list['quality'] = f'{bars / 5.0 * 100}/100'
ret_list['frequency'] = self.names[name]['FREQ']
ret_list['bitrates'] = self.names[name]['RATE']

View File

@ -18,7 +18,7 @@ class MacOSMaps(Maps):
'''
address = quote_plus(address, safe=',')
maps_address = 'http://maps.apple.com/?address=' + address
maps_address = f"http://maps.apple.com/?address={address}"
process = Popen(
['open', '-a', 'Maps', maps_address],
@ -34,8 +34,7 @@ class MacOSMaps(Maps):
'''
name = kwargs.get("name", "Selected Location")
maps_address = 'http://maps.apple.com/?ll={},{}&q={}'.format(
latitude, longitude, name)
maps_address = f'http://maps.apple.com/?ll={latitude},{longitude}&q={name}'
process = Popen(
['open', '-a', 'Maps', maps_address],
@ -57,10 +56,10 @@ class MacOSMaps(Maps):
longitude = kwargs.get('longitude')
query = quote_plus(query, safe=',')
maps_address = 'http://maps.apple.com/?q=' + query
maps_address = f"http://maps.apple.com/?q={query}"
if latitude is not None and longitude is not None:
maps_address += '&sll={},{}'.format(latitude, longitude)
maps_address += f'&sll={latitude},{longitude}'
process = Popen(
['open', '-a', 'Maps', maps_address],
@ -75,8 +74,7 @@ class MacOSMaps(Maps):
saddr = quote_plus(saddr, safe=',')
daddr = quote_plus(daddr, safe=',')
maps_address = 'http://maps.apple.com/?saddr={}&daddr={}'.format(
saddr, daddr)
maps_address = f'http://maps.apple.com/?saddr={saddr}&daddr={daddr}'
process = Popen(
['open', '-a', 'Maps', maps_address],
stdout=PIPE, stderr=PIPE)

View File

@ -35,7 +35,7 @@ class WindowsEmail(Email):
# WE + startfile are available only on Windows
try:
os.startfile(uri)
except WindowsError:
except OSError:
print("Warning: unable to find a program able to send emails.")

View File

@ -85,9 +85,9 @@ class Win32FileChooser:
filters = ""
for f in self.filters:
if isinstance(f, str):
filters += (f + "\x00") * 2
filters += f'{f}\x00' * 2
else:
filters += f[0] + "\x00" + ";".join(f[1:]) + "\x00"
filters += f"{f[0]}\x00{';'.join(f[1:])}\x00"
args["Filter"] = filters
flags = win32con.OFN_OVERWRITEPROMPT

View File

@ -1,4 +1,3 @@
# -- coding: utf-8 --
'''
Module of Windows API for creating taskbar balloon tip
notification in the taskbar's tray notification area.
@ -87,7 +86,7 @@ class WindowsBalloonTip:
atexit.register(self.__del__)
wnd_class_ex = win_api_defs.get_WNDCLASSEXW()
class_name = 'PlyerTaskbar' + str(WindowsBalloonTip._get_unique_id())
class_name = f"PlyerTaskbar{WindowsBalloonTip._get_unique_id())}"
wnd_class_ex.lpszClassName = class_name
@ -127,7 +126,7 @@ class WindowsBalloonTip:
)
if hicon is None:
raise Exception('Could not load icon {}'.format(app_icon))
raise Exception(f'Could not load icon {app_icon}')
self._balloon_icon = self._hicon = hicon
else:
self._hicon = win_api_defs.LoadIconW(

View File

@ -18,7 +18,7 @@ def battery_status():
if not win_api_defs.GetSystemPowerStatus(ctypes.pointer(status)):
raise Exception('Could not get system power status.')
return dict(
(field, getattr(status, field))
return {
field: getattr(status, field)
for field, _ in status._fields_
)
}

View File

@ -308,14 +308,14 @@ def blank_lines(logical_line, blank_lines, indent_level, line_number,
if blank_lines:
yield 0, "E304 blank lines found after function decorator"
elif blank_lines > 2 or (indent_level and blank_lines == 2):
yield 0, "E303 too many blank lines (%d)" % blank_lines
yield 0, f"E303 too many blank lines ({int(blank_lines)})"
elif logical_line.startswith(('def ', 'class ', '@')):
if indent_level:
if not (blank_lines or previous_indent_level < indent_level or
DOCSTRING_REGEX.match(previous_logical)):
yield 0, "E301 expected 1 blank line, found 0"
elif blank_lines != 2:
yield 0, "E302 expected 2 blank lines, found %d" % blank_lines
yield 0, f"E302 expected 2 blank lines, found {int(blank_lines)}"
def extraneous_whitespace(logical_line):
@ -343,12 +343,12 @@ def extraneous_whitespace(logical_line):
text = match.group()
char = text.strip()
found = match.start()
if text == char + ' ':
if text == f"{char} ":
# assert char in '([{'
yield found + 1, "E201 whitespace after '%s'" % char
yield found + 1, f"E201 whitespace after '{char}'"
elif line[found - 1] != ',':
code = ('E202' if char in '}])' else 'E203') # if char in ',;:'
yield found, "%s whitespace before '%s'" % (code, char)
yield found, f"{code} whitespace before '{char}'"
def whitespace_around_keywords(logical_line):
@ -397,7 +397,7 @@ def missing_whitespace(logical_line):
continue # Slice syntax, no space required
if char == ',' and line[index + 1] == ')':
continue # Allow tuple with only one element: (3,)
yield index, "E231 missing whitespace after '%s'" % char
yield index, f"E231 missing whitespace after '{char}'"
def indentation(logical_line, previous_logical, indent_char,
@ -474,7 +474,7 @@ def continuation_line_indentation(logical_line, tokens, indent_level, verbose):
indent_chances = {}
last_indent = (0, 0)
if verbose >= 3:
print((">>> " + tokens[0][4].rstrip()))
print(f">>> {tokens[0][4].rstrip()}")
for token_type, text, start, end, line in tokens:
newline = row < start[0] - first_row
@ -487,7 +487,7 @@ def continuation_line_indentation(logical_line, tokens, indent_level, verbose):
# this is the beginning of a continuation line.
last_indent = start
if verbose >= 3:
print(("... " + line.rstrip()))
print(f"... {line.rstrip()}")
# record the initial indent.
rel_indent[row] = start[1] - indent_level
@ -544,7 +544,7 @@ def continuation_line_indentation(logical_line, tokens, indent_level, verbose):
indent[depth] = start[1]
indent_chances[start[1]] = True
if verbose >= 4:
print(("bracket depth %s indent to %s" % (depth, start[1])))
print(f"bracket depth {depth} indent to {start[1]}")
# deal with implicit string concatenation
elif token_type == tokenize.STRING or text in ('u', 'ur', 'b', 'br'):
indent_chances[start[1]] = str
@ -556,8 +556,8 @@ def continuation_line_indentation(logical_line, tokens, indent_level, verbose):
indent.append(0)
parens[row] += 1
if verbose >= 4:
print(("bracket depth %s seen, col %s, visual min = %s" %
(depth, start[1], indent[depth])))
print("bracket depth %s seen, col %s, visual min = %s" %
(depth, start[1], indent[depth]))
elif text in ')]}' and depth > 0:
# parent indents should not be more than this one
prev_indent = indent.pop() or last_indent[1]
@ -616,7 +616,7 @@ def whitespace_before_parameters(logical_line, tokens):
(index < 2 or tokens[index - 2][1] != 'class') and
# Allow "return (a.foo for a in range(5))"
not keyword.iskeyword(prev_text)):
yield prev_end, "E211 whitespace before '%s'" % text
yield prev_end, f"E211 whitespace before '{text}'"
prev_type = token_type
prev_text = text
prev_end = end
@ -743,9 +743,9 @@ def whitespace_around_comma(logical_line):
for m in WHITESPACE_AFTER_COMMA_REGEX.finditer(line):
found = m.start() + 1
if '\t' in m.group():
yield found, "E242 tab after '%s'" % m.group()[0]
yield found, f"E242 tab after '{m.group()[0]}'"
else:
yield found, "E241 multiple spaces after '%s'" % m.group()[0]
yield found, f"E241 multiple spaces after '{m.group()[0]}'"
def whitespace_around_named_parameter_equals(logical_line, tokens):
@ -925,16 +925,15 @@ def comparison_to_singleton(logical_line):
if match:
same = (match.group(1) == '==')
singleton = match.group(2)
msg = "'if cond is %s:'" % (('' if same else 'not ') + singleton)
msg = f"'if cond is {('' if same else 'not ') + singleton}:'"
if singleton in ('None',):
code = 'E711'
else:
code = 'E712'
nonzero = ((singleton == 'True' and same) or
(singleton == 'False' and not same))
msg += " or 'if %scond:'" % ('' if nonzero else 'not ')
yield match.start(1), ("%s comparison to %s should be %s" %
(code, singleton, msg))
msg += f" or 'if {'' if nonzero else 'not '}cond:'"
yield match.start(1), (f"{code} comparison to {singleton} should be {msg}")
def comparison_type(logical_line):
@ -1023,7 +1022,7 @@ def python_3000_backticks(logical_line):
##############################################################################
if '' == ''.encode():
if '' == b'':
# Python 2: implicit encoding.
def readlines(filename):
f = open(filename)
@ -1114,16 +1113,16 @@ def parse_udiff(diff, patterns=None, parent='.'):
nrows -= 1
continue
if line[:3] == '@@ ':
row, nrows = [int(g) for g in HUNK_REGEX.match(line).groups()]
row, nrows = (int(g) for g in HUNK_REGEX.match(line).groups())
rv[path].update(list(range(row, row + nrows)))
elif line[:3] == '+++':
path = line[4:].split('\t', 1)[0]
if path[:2] == 'b/':
path = path[2:]
rv[path] = set()
return dict([(os.path.join(parent, path), rows)
return {os.path.join(parent, path): rows
for (path, rows) in list(rv.items())
if rows and filename_match(path, patterns)])
if rows and filename_match(path, patterns)}
def filename_match(filename, patterns, default=True):
@ -1178,9 +1177,9 @@ class Checker:
elif lines is None:
try:
self.lines = readlines(filename)
except IOError:
except OSError:
exc_type, exc = sys.exc_info()[:2]
self._io_error = '%s: %s' % (exc_type.__name__, exc)
self._io_error = f'{exc_type.__name__}: {exc}'
self.lines = []
else:
self.lines = lines
@ -1273,10 +1272,10 @@ class Checker:
self.previous_indent_level = self.indent_level
self.indent_level = expand_indent(indent)
if self.verbose >= 2:
print((self.logical_line[:80].rstrip()))
print(self.logical_line[:80].rstrip())
for name, check, argument_names in self._logical_checks:
if self.verbose >= 4:
print((' ' + name))
print(f" {name}")
for result in self.run_check(check, argument_names):
offset, text = result
if isinstance(offset, tuple):
@ -1291,18 +1290,17 @@ class Checker:
def generate_tokens(self):
if self._io_error:
self.report_error(1, 0, 'E902 %s' % self._io_error, readlines)
self.report_error(1, 0, f'E902 {self._io_error}', readlines)
tokengen = tokenize.generate_tokens(self.readline_check_physical)
try:
for token in tokengen:
yield token
yield from tokengen
except (SyntaxError, tokenize.TokenError):
exc_type, exc = sys.exc_info()[:2]
offset = exc.args[1]
if len(offset) > 2:
offset = offset[1:3]
self.report_error(offset[0], offset[1],
'E901 %s: %s' % (exc_type.__name__, exc.args[0]),
f'E901 {exc_type.__name__}: {exc.args[0]}',
self.generate_tokens)
generate_tokens.__doc__ = " Check if the syntax is valid."
@ -1323,11 +1321,11 @@ class Checker:
token_type, text = token[0:2]
if self.verbose >= 3:
if token[2][0] == token[3][0]:
pos = '[%s:%s]' % (token[2][1] or '', token[3][1])
pos = f"[{token[2][1] or ''}:{token[3][1]}]"
else:
pos = 'l.%s' % token[3][0]
print(('l.%s\t%s\t%s\t%r' %
(token[2][0], pos, tokenize.tok_name[token[0]], text)))
pos = f'l.{token[3][0]}'
print('l.%s\t%s\t%s\t%r' %
(token[2][0], pos, tokenize.tok_name[token[0]], text))
if token_type == tokenize.COMMENT or token_type == tokenize.STRING:
for sre in re.finditer(r"[:.;,] ?[A-Za-z]", text):
pos = sre.span()[0]
@ -1426,7 +1424,7 @@ class BaseReport:
if code in self.expected:
return
if self.print_filename and not self.file_errors:
print((self.filename))
print(self.filename)
self.file_errors += 1
self.total_errors += 1
return code
@ -1459,12 +1457,12 @@ class BaseReport:
def print_benchmark(self):
"""Print benchmark numbers."""
print(('%-7.2f %s' % (self.elapsed, 'seconds elapsed')))
print(f'{self.elapsed:<7.2f} seconds elapsed')
if self.elapsed:
for key in self._benchmark_keys:
print(('%-7d %s per second (%d total)' %
print('%-7d %s per second (%d total)' %
(self.counters[key] / self.elapsed, key,
self.counters[key])))
self.counters[key]))
class FileReport(BaseReport):
@ -1489,20 +1487,20 @@ class StandardReport(BaseReport):
code = super().error(line_number, offset,
text, check)
if code and (self.counters[code] == 1 or self._repeat):
print((self._fmt % {
print(self._fmt % {
'path': self.filename,
'row': self.line_offset + line_number, 'col': offset + 1,
'code': code, 'text': text[5:],
}))
})
if self._show_source:
if line_number > len(self.lines):
line = ''
else:
line = self.lines[line_number - 1]
print((line.rstrip()))
print((' ' * offset + '^'))
print(line.rstrip())
print(f"{' ' * offset}^")
if self._show_pep8 and check is not None:
print((check.__doc__.lstrip('\n').rstrip()))
print(check.__doc__.lstrip('\n').rstrip())
return code
@ -1529,16 +1527,15 @@ class TestReport(StandardReport):
def get_file_results(self):
# Check if the expected errors were found
label = '%s:%s:1' % (self.filename, self.line_offset)
label = f'{self.filename}:{self.line_offset}:1'
codes = sorted(self.expected)
for code in codes:
if not self.counters.get(code):
self.file_errors += 1
self.total_errors += 1
print(('%s: error %s not found' % (label, code)))
print(f'{label}: error {code} not found')
if self._verbose and not self.file_errors:
print(('%s: passed (%s)' %
(label, ' '.join(codes) or 'Okay')))
print(f"{label}: passed ({' '.join(codes) or 'Okay'})")
self.counters['test cases'] += 1
if self.file_errors:
self.counters['failed tests'] += 1
@ -1552,10 +1549,10 @@ class TestReport(StandardReport):
results = ("%(physical lines)d lines tested: %(files)d files, "
"%(test cases)d test cases%%s." % self.counters)
if self.total_errors:
print((results % ", %s failures" % self.total_errors))
print(results % ", %s failures" % self.total_errors)
else:
print((results % ""))
print(("Test failed." if self.total_errors else "Test passed."))
print(results % "")
print("Test failed." if self.total_errors else "Test passed.")
class StyleGuide:
@ -1614,7 +1611,7 @@ class StyleGuide:
def input_file(self, filename, lines=None, expected=None, line_offset=0):
"""Run all checks on a Python source file."""
if self.options.verbose:
print(('checking %s' % filename))
print(f'checking {filename}')
fchecker = Checker(filename, lines=lines, options=self.options)
return fchecker.check_all(expected=expected, line_offset=line_offset)
@ -1629,15 +1626,15 @@ class StyleGuide:
runner = self.runner
for root, dirs, files in os.walk(dirname):
if verbose:
print(('directory ' + root))
print(f"directory {root}")
counters['directories'] += 1
for subdir in sorted(dirs):
if self.excluded(subdir):
dirs.remove(subdir)
for filename in sorted(files):
# contain a pattern that matches?
if ((filename_match(filename, filepatterns) and
not self.excluded(filename))):
if (filename_match(filename, filepatterns) and
not self.excluded(filename)):
runner(os.path.join(root, filename))
def excluded(self, filename):
@ -1740,16 +1737,16 @@ def selftest(options):
for part in source.split(r'\n'):
part = part.replace(r'\t', '\t')
part = part.replace(r'\s', ' ')
checker.lines.append(part + '\n')
checker.lines.append(f"{part}\n")
checker.check_all()
error = None
if code == 'Okay':
if len(counters) > len(options.benchmark_keys):
codes = [key for key in counters
if key not in options.benchmark_keys]
error = "incorrectly found %s" % ', '.join(codes)
error = f"incorrectly found {', '.join(codes)}"
elif not counters.get(code):
error = "failed to find %s" % code
error = f"failed to find {code}"
# Keep showing errors for multiple tests
for key in set(counters) - set(options.benchmark_keys):
del counters[key]
@ -1757,12 +1754,12 @@ def selftest(options):
count_all += 1
if not error:
if options.verbose:
print(("%s: %s" % (code, source)))
print(f"{code}: {source}")
else:
count_failed += 1
print(("%s: %s:" % (__file__, error)))
print(f"{__file__}: {error}:")
for line in checker.lines:
print((line.rstrip()))
print(line.rstrip())
return count_failed, count_all
@ -1773,7 +1770,7 @@ def read_config(options, args, arglist, parser):
user_conf = options.config
if user_conf and os.path.isfile(user_conf):
if options.verbose:
print(('user configuration: %s' % user_conf))
print(f'user configuration: {user_conf}')
config.read(user_conf)
parent = tail = args and os.path.abspath(os.path.commonprefix(args))
@ -1781,14 +1778,14 @@ def read_config(options, args, arglist, parser):
local_conf = os.path.join(parent, '.pep8')
if os.path.isfile(local_conf):
if options.verbose:
print(('local configuration: %s' % local_conf))
print(f'local configuration: {local_conf}')
config.read(local_conf)
break
parent, tail = os.path.split(parent)
if config.has_section('pep8'):
option_list = dict([(o.dest, o.type or o.action)
for o in parser.option_list])
option_list = {o.dest: o.type or o.action
for o in parser.option_list}
# First, read the default values
new_options, _ = parser.parse_args([])
@ -1796,10 +1793,10 @@ def read_config(options, args, arglist, parser):
# Second, parse the configuration
for opt in config.options('pep8'):
if options.verbose > 1:
print((' %s = %s' % (opt, config.get('pep8', opt))))
print(f" {opt} = {config.get('pep8', opt)}")
if opt.replace('_', '-') not in parser.config_options:
print(('Unknown option: \'%s\'\n not in [%s]' %
(opt, ' '.join(parser.config_options))))
print('Unknown option: \'%s\'\n not in [%s]' %
(opt, ' '.join(parser.config_options)))
sys.exit(1)
normalized_opt = opt.replace('-', '_')
opt_type = option_list[normalized_opt]
@ -1930,8 +1927,8 @@ def _main():
count_failed = fail_s + fail_d
if not options.quiet:
count_passed = done_d + done_s - count_failed
print(("%d passed and %d failed." % (count_passed, count_failed)))
print(("Test failed." if count_failed else "Test passed."))
print(f"{int(count_passed)} passed and {int(count_failed)} failed.")
print("Test failed." if count_failed else "Test passed.")
if count_failed:
sys.exit(1)
if options.testsuite:
@ -1945,7 +1942,7 @@ def _main():
report.print_results()
if report.total_errors:
if options.count:
sys.stderr.write(str(report.total_errors) + '\n')
sys.stderr.write(f"{report.total_errors)}\n")
sys.exit(1)

View File

@ -26,7 +26,7 @@ class KivyStyleChecker(pep8.Checker):
)
# html generation
print('<tr><td>{0}</td><td>{1}</td></tr>'.format(line_number, text))
print(f'<tr><td>{line_number}</td><td>{text}</td></tr>')
if __name__ == '__main__':
@ -52,7 +52,7 @@ if __name__ == '__main__':
def check(fn):
try:
checker = KivyStyleChecker(fn)
except IOError:
except OSError:
# File couldn't be opened, so was deleted apparently.
# Don't check deleted files.
return 0
@ -68,10 +68,9 @@ if __name__ == '__main__':
if isdir(target):
if htmlmode:
path = join(dirname(abspath(__file__)), 'pep8base.html')
print(open(path, 'r').read())
print(open(path).read())
print(
'''<p>Generated: %s</p><table>'''
'' % (time.strftime('%c'))
f'''<p>Generated: {time.strftime('%c')}</p><table>'''
)
for dirpath, dirnames, filenames in walk(target):
@ -95,8 +94,7 @@ if __name__ == '__main__':
if htmlmode:
print(
'<tr><th colspan="2">%s</td></tr>'
'' % complete_filename
f'<tr><th colspan="2">{complete_filename}</td></tr>'
)
errors += check(complete_filename)

View File

@ -32,10 +32,7 @@ class Platform:
return self._get_platform()
def __repr__(self):
return 'platform name: \'{platform}\' from: \n{instance}'.format(
platform=self._get_platform(),
instance=super().__repr__()
)
return f'platform name: \'{self._get_platform()}\' from: \n{super().__repr__()}'
def __hash__(self):
return self._get_platform().__hash__()
@ -93,9 +90,9 @@ class Proxy:
try:
name = object.__getattribute__(self, '_name')
if RNS.vendor.platformutils.is_android():
module = 'plyer.platforms.{}.{}'.format(platform, name)
module = f'plyer.platforms.{platform}.{name}'
else:
module = 'sbapp.plyer.platforms.{}.{}'.format(platform, name)
module = f'sbapp.plyer.platforms.{platform}.{name}'
mod = __import__(module, fromlist='.')
obj = mod.instance()
except Exception:
@ -227,7 +224,7 @@ def deprecated(obj):
)
)
warnings.warn('[{}] {}'.format('WARNING', warning))
warnings.warn(f'[WARNING] {warning}')
# if there is a docstring present, emit docstring too
if obj.__doc__:

View File

@ -1,5 +1,3 @@
from __future__ import division
import array
import os
import subprocess
@ -42,13 +40,12 @@ from .exceptions import (
MissingAudioParameter,
)
if sys.version_info >= (3, 0):
basestring = str
xrange = range
StringIO = BytesIO
basestring = str
xrange = range
StringIO = BytesIO
class ClassPropertyDescriptor(object):
class ClassPropertyDescriptor:
def __init__(self, fget, fset=None):
self.fget = fget
@ -116,8 +113,7 @@ def read_wav_audio(data, headers=None):
pos = fmt.position + 8
audio_format = struct.unpack_from('<H', data[pos:pos + 2])[0]
if audio_format != 1 and audio_format != 0xFFFE:
raise CouldntDecodeError("Unknown audio format 0x%X in wav data" %
audio_format)
raise CouldntDecodeError(f"Unknown audio format 0x{audio_format:X} in wav data")
channels = struct.unpack_from('<H', data[pos + 2:pos + 4])[0]
sample_rate = struct.unpack_from('<I', data[pos + 4:pos + 8])[0]
@ -149,7 +145,7 @@ def fix_wav_headers(data):
data[pos + 4:pos + 8] = struct.pack('<I', len(data) - pos - 8)
class AudioSegment(object):
class AudioSegment:
"""
AudioSegments are *immutable* objects representing segments of audio
that can be manipulated using python code.
@ -255,7 +251,7 @@ class AudioSegment(object):
self.sample_width = 4
self.frame_width = self.channels * self.sample_width
super(AudioSegment, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
@property
def raw_data(self):
@ -516,9 +512,9 @@ class AudioSegment(object):
if format == f:
return True
if isinstance(orig_file, basestring):
return orig_file.lower().endswith(".{0}".format(f))
return orig_file.lower().endswith(f".{f}")
if isinstance(orig_file, bytes):
return orig_file.lower().endswith((".{0}".format(f)).encode('utf8'))
return orig_file.lower().endswith(f".{f}".encode('utf8'))
return False
if is_format("wav"):
@ -622,7 +618,7 @@ class AudioSegment(object):
try:
if p.returncode != 0:
raise CouldntDecodeError(
"Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format(
"Decoding failed. ffmpeg returned error code: {}\n\nOutput from ffmpeg/avlib:\n\n{}".format(
p.returncode, p_err.decode(errors='ignore') ))
obj = cls._from_safe_wav(output)
finally:
@ -660,7 +656,7 @@ class AudioSegment(object):
return True
if filename:
return filename.lower().endswith(".{0}".format(f))
return filename.lower().endswith(f".{f}")
return False
@ -740,7 +736,7 @@ class AudioSegment(object):
if bits_per_sample == 8:
acodec = 'pcm_u8'
else:
acodec = 'pcm_s%dle' % bits_per_sample
acodec = f'pcm_s{int(bits_per_sample)}le'
conversion_command += ["-acodec", acodec]
@ -771,7 +767,7 @@ class AudioSegment(object):
if close_file:
file.close()
raise CouldntDecodeError(
"Decoding failed. ffmpeg returned error code: {0}\n\nOutput from ffmpeg/avlib:\n\n{1}".format(
"Decoding failed. ffmpeg returned error code: {}\n\nOutput from ffmpeg/avlib:\n\n{}".format(
p.returncode, p_err.decode(errors='ignore') ))
p_out = bytearray(p_out)
@ -938,13 +934,13 @@ class AudioSegment(object):
# print(tags)
for key, value in tags.items():
conversion_command.extend(
['-metadata', '{0}={1}'.format(key, value)])
['-metadata', f'{key}={value}'])
if format == 'mp3':
# set id3v2 tag version
if id3v2_version not in id3v2_allowed_versions:
raise InvalidID3TagVersion(
"id3v2_version not allowed, allowed versions: %s" % id3v2_allowed_versions)
f"id3v2_version not allowed, allowed versions: {id3v2_allowed_versions}")
conversion_command.extend([
"-id3v2_version", id3v2_version
])
@ -968,7 +964,7 @@ class AudioSegment(object):
if p.returncode != 0:
raise CouldntEncodeError(
"Encoding failed. ffmpeg/avlib returned error code: {0}\n\nCommand:{1}\n\nOutput from ffmpeg/avlib:\n\n{2}".format(
"Encoding failed. ffmpeg/avlib returned error code: {}\n\nCommand:{}\n\nOutput from ffmpeg/avlib:\n\n{}".format(
p.returncode, conversion_command, p_err.decode(errors='ignore') ))
output.seek(0)

View File

@ -12,8 +12,7 @@ from .utils import (
from .silence import split_on_silence
from .exceptions import TooManyMissingFrames, InvalidDuration
if sys.version_info >= (3, 0):
xrange = range
xrange = range
@register_pydub_effect
@ -204,7 +203,7 @@ def invert_phase(seg, channels=(1, 1)):
if seg.channels == 2:
left, right = seg.split_to_mono()
else:
raise Exception("Can't implicitly convert an AudioSegment with " + str(seg.channels) + " channels to stereo.")
raise Exception(f"Can't implicitly convert an AudioSegment with {seg.channels)} channels to stereo.")
if channels == (1, 0):
left = left.invert_phase()

View File

@ -21,7 +21,7 @@ from .utils import (
class SignalGenerator(object):
class SignalGenerator:
def __init__(self, sample_rate=44100, bit_depth=16):
self.sample_rate = sample_rate
self.bit_depth = bit_depth
@ -64,7 +64,7 @@ class SignalGenerator(object):
class Sine(SignalGenerator):
def __init__(self, freq, **kwargs):
super(Sine, self).__init__(**kwargs)
super().__init__(**kwargs)
self.freq = freq
def generate(self):
@ -78,7 +78,7 @@ class Sine(SignalGenerator):
class Pulse(SignalGenerator):
def __init__(self, freq, duty_cycle=0.5, **kwargs):
super(Pulse, self).__init__(**kwargs)
super().__init__(**kwargs)
self.freq = freq
self.duty_cycle = duty_cycle
@ -101,13 +101,13 @@ class Pulse(SignalGenerator):
class Square(Pulse):
def __init__(self, freq, **kwargs):
kwargs['duty_cycle'] = 0.5
super(Square, self).__init__(freq, **kwargs)
super().__init__(freq, **kwargs)
class Sawtooth(SignalGenerator):
def __init__(self, freq, duty_cycle=1.0, **kwargs):
super(Sawtooth, self).__init__(**kwargs)
super().__init__(**kwargs)
self.freq = freq
self.duty_cycle = duty_cycle
@ -133,7 +133,7 @@ class Sawtooth(SignalGenerator):
class Triangle(Sawtooth):
def __init__(self, freq, **kwargs):
kwargs['duty_cycle'] = 0.5
super(Triangle, self).__init__(freq, **kwargs)
super().__init__(freq, **kwargs)
class WhiteNoise(SignalGenerator):

View File

@ -1,5 +1,3 @@
from __future__ import division
import json
import os
import re
@ -15,8 +13,7 @@ try:
except ImportError:
import pyaudioop as audioop
if sys.version_info >= (3, 0):
basestring = str
basestring = str
FRAME_WIDTHS = {
8: 1,
@ -214,7 +211,7 @@ def fsdecode(filename):
if isinstance(filename, basestring):
return filename
raise TypeError("type {0} not accepted by fsdecode".format(type(filename)))
raise TypeError(f"type {type(filename)} not accepted by fsdecode")
def get_extra_info(stderr):
@ -236,7 +233,7 @@ def get_extra_info(stderr):
for i in re.finditer(re_stream, stderr):
if i.group('space_end') is not None and len(i.group('space_start')) <= len(
i.group('space_end')):
content_line = ','.join([i.group('content_0'), i.group('content_1')])
content_line = f"{i.group('content_0')},{i.group('content_1')}"
else:
content_line = i.group('content_0')
tokens = [x.strip() for x in re.split('[:,]', content_line) if x]
@ -297,8 +294,8 @@ def mediainfo_json(filepath, read_ahead_limit=-1):
stream[prop] = value
for token in extra_info[stream['index']]:
m = re.match('([su]([0-9]{1,2})p?) \(([0-9]{1,2}) bit\)$', token)
m2 = re.match('([su]([0-9]{1,2})p?)( \(default\))?$', token)
m = re.match(r'([su]([0-9]{1,2})p?) \(([0-9]{1,2}) bit\)$', token)
m2 = re.match(r'([su]([0-9]{1,2})p?)( \(default\))?$', token)
if m:
set_property(stream, 'sample_fmt', m.group(1))
set_property(stream, 'bits_per_sample', int(m.group(2)))
@ -307,11 +304,11 @@ def mediainfo_json(filepath, read_ahead_limit=-1):
set_property(stream, 'sample_fmt', m2.group(1))
set_property(stream, 'bits_per_sample', int(m2.group(2)))
set_property(stream, 'bits_per_raw_sample', int(m2.group(2)))
elif re.match('(flt)p?( \(default\))?$', token):
elif re.match(r'(flt)p?( \(default\))?$', token):
set_property(stream, 'sample_fmt', token)
set_property(stream, 'bits_per_sample', 32)
set_property(stream, 'bits_per_raw_sample', 32)
elif re.match('(dbl)p?( \(default\))?$', token):
elif re.match(r'(dbl)p?( \(default\))?$', token):
set_property(stream, 'sample_fmt', token)
set_property(stream, 'bits_per_sample', 64)
set_property(stream, 'bits_per_raw_sample', 64)

View File

@ -45,7 +45,7 @@ class FlacFile(AudioFile):
self.frequency = metadata.contents.data.stream_info.sample_rate
def error_callback(self,decoder, status, client_data):
raise PyOggError("An error occured during the process of decoding. Status enum: {}".format(flac.FLAC__StreamDecoderErrorStatusEnum[status]))
raise PyOggError(f"An error occured during the process of decoding. Status enum: {flac.FLAC__StreamDecoderErrorStatusEnum[status]}")
def __init__(self, path):
self.decoder = flac.FLAC__stream_decoder_new()
@ -84,16 +84,16 @@ class FlacFile(AudioFile):
if init_status: # error
error = flac.FLAC__StreamDecoderInitStatusEnum[init_status]
raise PyOggError(
"An error occured when trying to open '{}': {}".format(path, error)
f"An error occured when trying to open '{path}': {error}"
)
metadata_status = (flac.FLAC__stream_decoder_process_until_end_of_metadata(self.decoder))
if not metadata_status: # error
raise PyOggError("An error occured when trying to decode the metadata of {}".format(path))
raise PyOggError(f"An error occured when trying to decode the metadata of {path}")
stream_status = (flac.FLAC__stream_decoder_process_until_end_of_stream(self.decoder))
if not stream_status: # error
raise PyOggError("An error occured when trying to decode the audio stream of {}".format(path))
raise PyOggError(f"An error occured when trying to decode the audio stream of {path}")
flac.FLAC__stream_decoder_finish(self.decoder)

View File

@ -41,7 +41,7 @@ class FlacFileStream:
self.frequency = metadata.contents.data.stream_info.sample_rate
def error_callback(self,decoder, status, client_data):
raise PyOggError("An error occured during the process of decoding. Status enum: {}".format(flac.FLAC__StreamDecoderErrorStatusEnum[status]))
raise PyOggError(f"An error occured during the process of decoding. Status enum: {flac.FLAC__StreamDecoderErrorStatusEnum[status]}")
def __init__(self, path):
self.decoder = flac.FLAC__stream_decoder_new()
@ -75,11 +75,11 @@ class FlacFileStream:
self.client_data)
if init_status: # error
raise PyOggError("An error occured when trying to open '{}': {}".format(path, flac.FLAC__StreamDecoderInitStatusEnum[init_status]))
raise PyOggError(f"An error occured when trying to open '{path}': {flac.FLAC__StreamDecoderInitStatusEnum[init_status]}")
metadata_status = (flac.FLAC__stream_decoder_process_until_end_of_metadata(self.decoder))
if not metadata_status: # error
raise PyOggError("An error occured when trying to decode the metadata of {}".format(path))
raise PyOggError(f"An error occured when trying to decode the metadata of {path}")
#: Bytes per sample
self.bytes_per_sample = 2
@ -94,7 +94,7 @@ class FlacFileStream:
# Attempt to read a single frame of audio
stream_status = (flac.FLAC__stream_decoder_process_single(self.decoder))
if not stream_status: # error
raise PyOggError("An error occured when trying to decode the audio stream of {}".format(path))
raise PyOggError(f"An error occured when trying to decode the audio stream of {path}")
# Check if we encountered the end of the stream
if (flac.FLAC__stream_decoder_get_state(self.decoder) == 4): # end of stream

View File

@ -23,12 +23,12 @@ _other_styles = ["{}", "lib{}"]
if architecture == "32bit":
for arch_style in ["32bit", "32" "86", "win32", "x86", "_x86", "_32", "_win32", "_32bit"]:
for style in ["{}", "lib{}"]:
_windows_styles.append(style.format("{}"+arch_style))
_windows_styles.append(style.format(f"{{}}{arch_style}"))
elif architecture == "64bit":
for arch_style in ["64bit", "64" "86_64", "amd64", "win_amd64", "x86_64", "_x86_64", "_64", "_amd64", "_64bit"]:
for style in ["{}", "lib{}"]:
_windows_styles.append(style.format("{}"+arch_style))
_windows_styles.append(style.format(f"{{}}{arch_style}"))
run_tests = lambda lib, tests: [f(lib) for f in tests]
@ -69,7 +69,7 @@ class InternalLibrary:
return None
# Attempt to load the library from here
path = _here + "/" + lib_dir + "/" + name
path = f"{_here}/{lib_dir}/{name}"
try:
lib = ctypes.CDLL(path)
except OSError as e:
@ -101,8 +101,8 @@ class ExternalLibrary:
@staticmethod
def load_other(name, paths = None, tests = []):
os.environ["PATH"] += ";" + ";".join((os.getcwd(), _here))
if paths: os.environ["PATH"] += ";" + ";".join(paths)
os.environ["PATH"] += f";{f"{os.getcwd()};{_here}"}"
if paths: os.environ["PATH"] += f";{';'.join(paths)}"
for style in _other_styles:
candidate = style.format(name)
@ -117,8 +117,8 @@ class ExternalLibrary:
@staticmethod
def load_windows(name, paths = None, tests = []):
os.environ["PATH"] += ";" + ";".join((os.getcwd(), _here))
if paths: os.environ["PATH"] += ";" + ";".join(paths)
os.environ["PATH"] += f";{f"{os.getcwd()};{_here}"}"
if paths: os.environ["PATH"] += f";{';'.join(paths)}"
not_supported = [] # libraries that were found, but are not supported
for style in _windows_styles:
@ -130,17 +130,17 @@ class ExternalLibrary:
if tests and all(run_tests(lib, tests)):
return lib
not_supported.append(library)
except WindowsError:
except OSError:
pass
except OSError:
not_supported.append(library)
if not_supported:
raise ExternalLibraryError("library '{}' couldn't be loaded, because the following candidates were not supported:".format(name)
raise ExternalLibraryError(f"library '{name}' couldn't be loaded, because the following candidates were not supported:"
+ ("\n{}" * len(not_supported)).format(*not_supported))
raise ExternalLibraryError("library '{}' couldn't be loaded".format(name))
raise ExternalLibraryError(f"library '{name}' couldn't be loaded")

View File

@ -107,8 +107,7 @@ class OggOpusWriter():
# Check that the stream hasn't already been finished
if self._finished:
raise PyOggError(
"Stream has already ended. Perhaps close() was "+
"called too early?")
f"Stream has already ended. Perhaps close() was called too early?")
# If we haven't already written out the headers, do so
# now. Then, write a frame of silence to warm up the

View File

@ -38,8 +38,7 @@ class OpusBufferedEncoder(OpusEncoder):
# units of 0.1ms to avoid floating point comparison
if int(frame_size*10) not in [25, 50, 100, 200, 400, 600]:
raise PyOggError(
"Frame size ({:f}) not one of ".format(frame_size)+
"the acceptable values"
f"Frame size ({frame_size:f}) not one of the acceptable values"
)
self._frame_size_ms = frame_size
@ -336,7 +335,7 @@ class OpusBufferedEncoder(OpusEncoder):
Returns None if insufficient data is available.
"""
next_frame = bytes()
next_frame = b''
samples = 0
# Ensure frame size has been specified

View File

@ -32,8 +32,7 @@ class OpusDecoder:
if self._decoder is None:
if n < 0 or n > 2:
raise PyOggError(
"Invalid number of channels in call to "+
"set_channels()"
f"Invalid number of channels in call to set_channels()"
)
self._channels = n
else:
@ -65,7 +64,7 @@ class OpusDecoder:
else:
raise PyOggError(
"Specified sampling frequency "+
"({:d}) ".format(samples_per_second)+
f"({samples_per_second:d}) "+
"was not one of the accepted values"
)
else:
@ -152,7 +151,7 @@ class OpusDecoder:
# avoid floating-point comparisons.
if int(frame_duration*10) not in [25, 50, 100, 200, 400, 600]:
raise PyOggError(
"Frame duration ({:f}) is not one of the accepted values".format(frame_duration)
f"Frame duration ({frame_duration:f}) is not one of the accepted values"
)
# Calculate frame size

View File

@ -32,8 +32,7 @@ class OpusEncoder:
if self._encoder is None:
if n < 0 or n > 2:
raise PyOggError(
"Invalid number of channels in call to "+
"set_channels()"
f"Invalid number of channels in call to set_channels()"
)
self._channels = n
else:
@ -62,7 +61,7 @@ class OpusEncoder:
else:
raise PyOggError(
"Specified sampling frequency "+
"({:d}) ".format(samples_per_second)+
f"({samples_per_second:d}) "+
"was not one of the accepted values"
)
else:
@ -111,7 +110,7 @@ class OpusEncoder:
self._application = opus.OPUS_APPLICATION_RESTRICTED_LOWDELAY
else:
raise PyOggError(
"The application specification '{:s}' ".format(application)+
f"The application specification '{application:s}' "+
"wasn't one of the accepted values."
)
@ -170,8 +169,7 @@ class OpusEncoder:
# Check that we have a valid frame size
if int(frame_duration) not in [25, 50, 100, 200, 400, 600]:
raise PyOggError(
"The effective frame duration ({:.1f} ms) "
.format(frame_duration/10)+
f"The effective frame duration ({frame_duration / 10:.1f} ms) "+
"was not one of the acceptable values."
)

View File

@ -72,8 +72,7 @@ class OpusFile(AudioFile):
# Check for errors
if ns<0:
raise PyOggError(
"Error while reading OggOpus file. "+
"Error code: {}".format(ns)
f"Error while reading OggOpus file. Error code: {ns}"
)
# Increment the pointer

View File

@ -21,7 +21,7 @@ class OpusFileStream:
if error.value != 0:
self.of = None
raise PyOggError("file couldn't be opened or doesn't exist. Error code : {}".format(error.value))
raise PyOggError(f"file couldn't be opened or doesn't exist. Error code : {error.value}")
#: Number of channels in audio file
self.channels = opus.op_channel_count(self.of, -1)
@ -75,7 +75,7 @@ class OpusFileStream:
# Check for errors
if samples_read < 0:
raise PyOggError(
"Failed to read OpusFileStream. Error {:d}".format(samples_read)
f"Failed to read OpusFileStream. Error {samples_read:d}"
)
# Check if we've reached the end of the stream

View File

@ -131,8 +131,7 @@ class VorbisFile(AudioFile):
# Check for errors
if result < 0:
raise PyOggError(
"An error occurred decoding the Vorbis file: "+
f"Error code: {result}"
f"An error occurred decoding the Vorbis file: Error code: {result}"
)
# Check that the bitstream hasn't changed as we only

View File

@ -11,7 +11,7 @@ class VorbisFileStream:
self.vf = vorbis.OggVorbis_File()
error = vorbis.ov_fopen(path, ctypes.byref(self.vf))
if error != 0:
raise PyOggError("file couldn't be opened or doesn't exist. Error code : {}".format(error))
raise PyOggError(f"file couldn't be opened or doesn't exist. Error code : {error}")
info = vorbis.ov_info(ctypes.byref(self.vf), -1)

View File

@ -78,11 +78,11 @@ class SidebandService():
channel_id = package_name
group_id = ""
if group != None:
channel_id += "."+str(group)
channel_id += f".{group)}"
group_id += str(group)
if context_id != None:
channel_id += "."+str(context_id)
group_id += "."+str(context_id)
channel_id += f".{context_id)}"
group_id += f".{context_id)}"
if not title or title == "":
channel_name = "Sideband"
@ -134,12 +134,12 @@ class SidebandService():
def check_permission(self, permission):
if RNS.vendor.platformutils.is_android():
try:
result = self.android_service.checkSelfPermission("android.permission."+permission)
result = self.android_service.checkSelfPermission(f"android.permission.{permission}")
if result == 0:
return True
except Exception as e:
RNS.log("Error while checking permission: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while checking permission: {e)}", RNS.LOG_ERROR)
return False
@ -238,14 +238,14 @@ class SidebandService():
except Exception as e:
self.wifi_manager = None
RNS.log("Could not acquire Android WiFi Manager! Keeping WiFi-based interfaces up will be unavailable.", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"The contained exception was: {e)}", RNS.LOG_ERROR)
try:
self.power_manager = self.app_context.getSystemService(Context.POWER_SERVICE)
except Exception as e:
self.power_manager = None
RNS.log("Could not acquire Android Power Manager! Taking wakelocks and keeping the CPU running will be unavailable.", RNS.LOG_ERROR)
RNS.log("The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"The contained exception was: {e)}", RNS.LOG_ERROR)
self.discover_usb_devices()
@ -259,7 +259,7 @@ class SidebandService():
self.update_power_restrictions()
if RNS.vendor.platformutils.is_android():
RNS.log("Discovered USB devices: "+str(self.usb_devices), RNS.LOG_EXTREME)
RNS.log(f"Discovered USB devices: {self.usb_devices)}", RNS.LOG_EXTREME)
self.update_location_provider()
@ -281,7 +281,7 @@ class SidebandService():
self.usb_devices.append(device_entry)
except Exception as e:
RNS.log("Could not list USB devices. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Could not list USB devices. The contained exception was: {e)}", RNS.LOG_ERROR)
def start(self):
self.should_run = True
@ -351,7 +351,7 @@ class SidebandService():
if len(netdevs) > 0:
ds = "Using "
for netdev in netdevs:
ds += "[i]"+str(netdev)+"[/i], "
ds += f"[i]{netdev)}[/i], "
ds = ds[:-2]
else:
ds = "No usable network devices"
@ -360,13 +360,13 @@ class SidebandService():
if np == 1:
ws = "1 reachable peer"
else:
ws = str(np)+" reachable peers"
ws = f"{np)} reachable peers"
stat += "[b]Local[/b]\n{ds}\n{ws}\n\n".format(ds=ds, ws=ws)
stat += f"[b]Local[/b]\n{ds}\n{ws}\n\n"
if self.sideband.interface_rnode != None:
if self.sideband.interface_rnode.online:
rs = "On-air at "+str(self.sideband.interface_rnode.bitrate_kbps)+" Kbps"
rs = f"On-air at {self.sideband.interface_rnode.bitrate_kbps)} Kbps"
else:
rs = "Interface Down"
@ -384,23 +384,23 @@ class SidebandService():
else:
rm = "Interface Down"
stat += "[b]Radio Modem[/b]\n{rm}\n\n".format(rm=rm)
stat += f"[b]Radio Modem[/b]\n{rm}\n\n"
if self.sideband.interface_serial != None:
if self.sideband.interface_serial.online:
rs = "Running at "+RNS.prettysize(self.sideband.interface_serial.bitrate/8, suffix="b")+"ps"
rs = f"Running at {RNS.prettysize(self.sideband.interface_serial.bitrate / 8, suffix='b')}ps"
else:
rs = "Interface Down"
stat += "[b]Serial Port[/b]\n{rs}\n\n".format(rs=rs)
stat += f"[b]Serial Port[/b]\n{rs}\n\n"
if self.sideband.interface_tcp != None:
if self.sideband.interface_tcp.online:
ts = "Connected to "+str(self.sideband.interface_tcp.target_ip)+":"+str(self.sideband.interface_tcp.target_port)
ts = f"Connected to {self.sideband.interface_tcp.target_ip)}:{self.sideband.interface_tcp.target_port)}"
else:
ts = "Interface Down"
stat += "[b]TCP[/b]\n{ts}\n\n".format(ts=ts)
stat += f"[b]TCP[/b]\n{ts}\n\n"
if self.sideband.interface_i2p != None:
i2s = "Unknown"
@ -417,7 +417,7 @@ class SidebandService():
else:
i2s = "Connecting to I2P"
stat += "[b]I2P[/b]\n{i2s}\n\n".format(i2s=i2s)
stat += f"[b]I2P[/b]\n{i2s}\n\n"
total_rxb = 0
total_txb = 0
@ -449,7 +449,7 @@ class SidebandService():
if RNS.Reticulum.transport_enabled():
stat += "[b]Transport Instance[/b]\nRouting Traffic\n\n"
stat += "[b]Traffic[/b]\nIn: {inb}\nOut: {outb}\n\n".format(inb=RNS.prettysize(total_rxb), outb=RNS.prettysize(total_txb))
stat += f"[b]Traffic[/b]\nIn: {RNS.prettysize(total_rxb)}\nOut: {RNS.prettysize(total_txb)}\n\n"
if stat.endswith("\n\n"):
stat = stat[:-2]
@ -492,7 +492,7 @@ def handle_exception(exc_type, exc_value, exc_traceback):
import traceback
exc_text = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
RNS.log(f"An unhandled {str(exc_type)} exception occurred: {str(exc_value)}", RNS.LOG_ERROR)
RNS.log(f"An unhandled {exc_type)} exception occurred: {exc_value)}", RNS.LOG_ERROR)
RNS.log(exc_text, RNS.LOG_ERROR)
sys.excepthook = handle_exception

View File

@ -1,5 +1,5 @@
import os
import glob
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
modules = glob.glob(f"{os.path.dirname(__file__)}/*.py")
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]

View File

@ -108,7 +108,7 @@ def voice_processing(input_path):
filters = "highpass=f=250, lowpass=f=3000,speechnorm=e=12.5:r=0.0001:l=1"
output_bitrate = "12k"
opus_apptype = "audio"
output_path = input_path.replace(".ogg","")+".p.ogg"
output_path = f"{input_path.replace('.ogg', '')}.p.ogg"
args = [
"-i", input_path, "-filter:a", filters,
"-c:a", "libopus", "-application", opus_apptype,
@ -148,7 +148,7 @@ def encode_codec2(samples, mode):
c2 = pycodec2.Codec2(codec2_modes[mode])
SPF = c2.samples_per_frame()
PACKET_SIZE = SPF * 2 # 16-bit samples
STRUCT_FORMAT = '{}h'.format(SPF)
STRUCT_FORMAT = f'{SPF}h'
F_FRAMES = len(samples)/SPF
N_FRAMES = math.floor(len(samples)/SPF)
# TODO: Add padding to align to whole frames
@ -163,7 +163,7 @@ def encode_codec2(samples, mode):
encoded += encoded_packet
ap_duration = time.time() - ap_start
RNS.log("Codec2 encoding complete in "+RNS.prettytime(ap_duration)+", bytes out: "+str(len(encoded)), RNS.LOG_DEBUG)
RNS.log(f"Codec2 encoding complete in {RNS.prettytime(ap_duration)}, bytes out: {len(encoded))}", RNS.LOG_DEBUG)
return encoded
@ -176,7 +176,7 @@ def decode_codec2(encoded_bytes, mode):
c2 = pycodec2.Codec2(codec2_modes[mode])
SPF = c2.samples_per_frame()
BPF = c2.bytes_per_frame()
STRUCT_FORMAT = '{}h'.format(SPF)
STRUCT_FORMAT = f'{SPF}h'
N_FRAMES = math.floor(len(encoded_bytes)/BPF)
decoded = b""
@ -188,6 +188,6 @@ def decode_codec2(encoded_bytes, mode):
decoded += struct.pack(STRUCT_FORMAT, *decoded_frame)
ap_duration = time.time() - ap_start
RNS.log("Codec2 decoding complete in "+RNS.prettytime(ap_duration)+", samples out: "+str(len(decoded)), RNS.LOG_DEBUG)
RNS.log(f"Codec2 decoding complete in {RNS.prettytime(ap_duration)}, samples out: {len(decoded))}", RNS.LOG_DEBUG)
return decoded

File diff suppressed because it is too large Load Diff

View File

@ -312,7 +312,7 @@ def altitude_to_aamsl(alt, lat, lon):
# LGPLv3 License #
######################################################
class GeoidHeight(object):
class GeoidHeight:
c0 = 240
c3 = (
( 9, -18, -88, 0, 96, 90, 0, 0, -60, -20),

View File

@ -38,7 +38,7 @@ class Telemeter():
return t
except Exception as e:
RNS.log("An error occurred while unpacking telemetry. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while unpacking telemetry. The contained exception was: {e)}", RNS.LOG_ERROR)
return None
def __init__(self, from_packed=False, android_context=None, service=False, location_provider=None):
@ -153,18 +153,18 @@ class Telemeter():
if RNS.vendor.platformutils.is_android():
if self.android_context != None:
try:
result = self.android_context.checkSelfPermission("android.permission."+permission)
result = self.android_context.checkSelfPermission(f"android.permission.{permission}")
if result == 0:
return True
except Exception as e:
RNS.log("Error while checking permission: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while checking permission: {e)}", RNS.LOG_ERROR)
return False
else:
from android.permissions import check_permission
return check_permission("android.permission."+permission)
return check_permission(f"android.permission.{permission}")
else:
return False
@ -273,7 +273,7 @@ class Sensor():
return self._telemeter.check_permission(permission)
else:
from android.permissions import check_permission
return check_permission("android.permission."+permission)
return check_permission(f"android.permission.{permission}")
class Time(Sensor):
SID = Sensor.SID_TIME
@ -446,9 +446,9 @@ class Battery(Sensor):
bn = 0
node_name = None
for bi in range(0,10):
path = os.path.join('/sys', 'class', 'power_supply', 'BAT'+str(bi))
path = os.path.join('/sys', 'class', 'power_supply', f"BAT{bi)}")
if os.path.isdir(path):
node_name = "BAT"+str(bi)
node_name = f"BAT{bi)}"
break
self.battery_node_name = node_name
@ -784,7 +784,7 @@ class Location(Sensor):
d["last_update"],
]
except Exception as e:
RNS.log("An error occurred while packing location sensor data. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while packing location sensor data. The contained exception was: {e)}", RNS.LOG_ERROR)
return None
def unpack(self, packed):

View File

@ -1,5 +1,5 @@
import os
import glob
modules = glob.glob(os.path.dirname(__file__)+"/*.py")
modules = glob.glob(f"{os.path.dirname(__file__)}/*.py")
__all__ = [ os.path.basename(f)[:-3] for f in modules if not f.endswith('__init__.py')]

View File

@ -63,7 +63,7 @@ class Announces():
self.fetch_announces()
self.update_widget()
self.app.sideband.setstate("app.flags.new_announces", False)
RNS.log("Updated announce stream widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG)
RNS.log(f"Updated announce stream widgets in {RNS.prettytime(time.time() - us)}", RNS.LOG_DEBUG)
def update_widget(self):
if self.list == None:
@ -105,10 +105,10 @@ class Announces():
def x(sender):
yes_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
if dtype == "lxmf.delivery":
ad_text = "[size=22dp]LXMF Peer[/size]\n\n[b]Received[/b] "+ts+"\n[b]Address[/b] "+RNS.prettyhexrep(dest)+"\n[b]Name[/b] "+name+"\n[b]Stamp Cost[/b] "+cost
ad_text = f"[size=22dp]LXMF Peer[/size]\n\n[b]Received[/b] {ts}\n[b]Address[/b] {RNS.prettyhexrep(dest)}\n[b]Name[/b] {name}\n[b]Stamp Cost[/b] {cost}"
if dtype == "lxmf.propagation":
ad_text = "[size=22dp]LXMF Propagation Node[/size]\n\n[b]Received[/b] "+ts+"\n[b]Address[/b] "+RNS.prettyhexrep(dest)
ad_text = f"[size=22dp]LXMF Propagation Node[/size]\n\n[b]Received[/b] {ts}\n[b]Address[/b] {RNS.prettyhexrep(dest)}"
dialog = MDDialog(
text=ad_text,
@ -130,7 +130,7 @@ class Announces():
iconl = IconLeftWidget(icon=trust_icon)
elif dest_type == "lxmf.propagation":
disp_name = "Propagation Node "+RNS.prettyhexrep(context_dest)
disp_name = f"Propagation Node {RNS.prettyhexrep(context_dest)}"
iconl = IconLeftWidget(icon="upload-network")
else:

View File

@ -224,7 +224,7 @@ class Conversations():
dialog = MDDialog(
title="Edit Conversation",
text= "With "+RNS.prettyhexrep(dest),
text= f"With {RNS.prettyhexrep(dest)}",
type="custom",
content_cls=dialog_content,
buttons=[ yes_button, no_button ],
@ -269,7 +269,7 @@ class Conversations():
self.app.sideband.named_conversation(name, dest)
except Exception as e:
RNS.log("Error while saving conversation settings: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while saving conversation settings: {e)}", RNS.LOG_ERROR)
dialog.dismiss()
@ -284,10 +284,10 @@ class Conversations():
no_button.bind(on_release=dl_no)
item.dmenu.dismiss()
dialog.open()
RNS.log("Generated edit dialog in "+str(RNS.prettytime(time.time()-t_s)), RNS.LOG_DEBUG)
RNS.log(f"Generated edit dialog in {RNS.prettytime(time.time() - t_s))}", RNS.LOG_DEBUG)
except Exception as e:
RNS.log("Error while creating conversation settings: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while creating conversation settings: {e)}", RNS.LOG_ERROR)
return x
@ -479,7 +479,7 @@ class Conversations():
self.list.children.sort(key=lambda w: (w.trusted, w.last_activity))
RNS.log("Updated conversation list widgets in "+RNS.prettytime(time.time()-us), RNS.LOG_DEBUG)
RNS.log(f"Updated conversation list widgets in {RNS.prettytime(time.time() - us)}", RNS.LOG_DEBUG)
def get_widget(self):
return self.list

View File

@ -83,7 +83,7 @@ def multilingual_markup(data):
if pfont != "default":
do += "[/font]"
if rfont != "default":
do += "[font="+str(rfont)+"]"
do += f"[font={rfont)}]"
do += cp

View File

@ -278,7 +278,7 @@ class Messages():
sphrase = "Sending"
prg = self.app.sideband.get_lxm_progress(msg["hash"])
if prg != None:
prgstr = ", "+str(round(prg*100, 1))+"% done"
prgstr = f", {round(prg * 100, 1))}% done"
if prg <= 0.00:
stamp_cost = self.app.sideband.get_lxm_stamp_cost(msg["hash"])
if stamp_cost:
@ -296,8 +296,8 @@ class Messages():
sphrase = "Sending"
if msg["title"]:
titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n"
w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] "+sphrase+prgstr+" "
titlestr = f"[b]Title[/b] {msg['title'].decode('utf-8')}\n"
w.heading = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] {sphrase}{prgstr} "
if w.has_audio:
alstr = RNS.prettysize(w.audio_size)
w.heading += f"\n[b]Audio Message[/b] ({alstr})"
@ -309,8 +309,8 @@ class Messages():
txstr = time.strftime(ts_format, time.localtime(msg["sent"]))
titlestr = ""
if msg["title"]:
titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n"
w.heading = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] Delivered"
titlestr = f"[b]Title[/b] {msg['title'].decode('utf-8')}\n"
w.heading = f"{titlestr}[b]Sent[/b] {txstr}{delivery_syms}\n[b]State[/b] Delivered"
if w.has_audio:
alstr = RNS.prettysize(w.audio_size)
w.heading += f"\n[b]Audio Message[/b] ({alstr})"
@ -321,8 +321,8 @@ class Messages():
txstr = time.strftime(ts_format, time.localtime(msg["sent"]))
titlestr = ""
if msg["title"]:
titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n"
w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Paper Message"
titlestr = f"[b]Title[/b] {msg['title'].decode('utf-8')}\n"
w.heading = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] Paper Message"
m["state"] = msg["state"]
if msg["method"] == LXMF.LXMessage.PROPAGATED and msg["state"] == LXMF.LXMessage.SENT:
@ -330,8 +330,8 @@ class Messages():
txstr = time.strftime(ts_format, time.localtime(msg["sent"]))
titlestr = ""
if msg["title"]:
titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n"
w.heading = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] On Propagation Net"
titlestr = f"[b]Title[/b] {msg['title'].decode('utf-8')}\n"
w.heading = f"{titlestr}[b]Sent[/b] {txstr}{delivery_syms}\n[b]State[/b] On Propagation Net"
if w.has_audio:
alstr = RNS.prettysize(w.audio_size)
w.heading += f"\n[b]Audio Message[/b] ({alstr})"
@ -342,8 +342,8 @@ class Messages():
txstr = time.strftime(ts_format, time.localtime(msg["sent"]))
titlestr = ""
if msg["title"]:
titlestr = "[b]Title[/b] "+msg["title"].decode("utf-8")+"\n"
w.heading = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed"
titlestr = f"[b]Title[/b] {msg['title'].decode('utf-8')}\n"
w.heading = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] Failed"
m["state"] = msg["state"]
if w.has_audio:
alstr = RNS.prettysize(w.audio_size)
@ -388,7 +388,7 @@ class Messages():
if message_input.strip() == b"":
if not ("lxm" in m and m["lxm"] != None and m["lxm"].fields != None and LXMF.FIELD_COMMANDS in m["lxm"].fields):
message_input = "[i]This message contains no text content[/i]".encode("utf-8")
message_input = b"[i]This message contains no text content[/i]"
message_markup = multilingual_markup(message_input)
@ -438,18 +438,18 @@ class Messages():
commands = m["lxm"].fields[LXMF.FIELD_COMMANDS]
for command in commands:
if Commands.ECHO in command:
extra_content = "[font=RobotoMono-Regular]> echo "+command[Commands.ECHO].decode("utf-8")+"[/font]\n"
extra_content = f"[font=RobotoMono-Regular]> echo {command[Commands.ECHO].decode('utf-8')}[/font]\n"
if Commands.PING in command:
extra_content = "[font=RobotoMono-Regular]> ping[/font]\n"
if Commands.SIGNAL_REPORT in command:
extra_content = "[font=RobotoMono-Regular]> sig[/font]\n"
if Commands.PLUGIN_COMMAND in command:
cmd_content = command[Commands.PLUGIN_COMMAND]
extra_content = "[font=RobotoMono-Regular]> "+str(cmd_content)+"[/font]\n"
extra_content = f"[font=RobotoMono-Regular]> {cmd_content)}[/font]\n"
extra_content = extra_content[:-1]
force_markup = True
except Exception as e:
RNS.log("Error while generating command display: "+str(e), RNS.LOG_ERROR)
RNS.log(f"Error while generating command display: {e)}", RNS.LOG_ERROR)
if telemeter == None and "lxm" in m and m["lxm"] and m["lxm"].fields != None and LXMF.FIELD_TELEMETRY in m["lxm"].fields:
try:
@ -488,11 +488,11 @@ class Messages():
if "euclidian" in d:
edst = d["euclidian"]
if edst != None:
rcvd_d_str = "\n[b]Distance[/b] "+RNS.prettydistance(edst)
rcvd_d_str = f"\n[b]Distance[/b] {RNS.prettydistance(edst)}"
elif "geodesic" in d:
gdst = d["geodesic"]
if gdst != None:
rcvd_d_str = "\n[b]Distance[/b] "+RNS.prettydistance(gdst) + " (geodesic)"
rcvd_d_str = f"\n[b]Distance[/b] {RNS.prettydistance(gdst)} (geodesic)"
phy_stats_str = ""
if "extras" in m and m["extras"] != None:
@ -500,64 +500,64 @@ class Messages():
if "q" in phy_stats:
try:
lq = round(float(phy_stats["q"]), 1)
phy_stats_str += "[b]Link Quality[/b] "+str(lq)+"% "
phy_stats_str += f"[b]Link Quality[/b] {lq)}% "
extra_telemetry["quality"] = lq
except:
pass
if "rssi" in phy_stats:
try:
lr = round(float(phy_stats["rssi"]), 1)
phy_stats_str += "[b]RSSI[/b] "+str(lr)+"dBm "
phy_stats_str += f"[b]RSSI[/b] {lr)}dBm "
extra_telemetry["rssi"] = lr
except:
pass
if "snr" in phy_stats:
try:
ls = round(float(phy_stats["snr"]), 1)
phy_stats_str += "[b]SNR[/b] "+str(ls)+"dB "
phy_stats_str += f"[b]SNR[/b] {ls)}dB "
extra_telemetry["snr"] = ls
except:
pass
if m["title"]:
titlestr = "[b]Title[/b] "+m["title"].decode("utf-8")+"\n"
titlestr = f"[b]Title[/b] {m['title'].decode('utf-8')}\n"
if m["source"] == self.app.sideband.lxmf_destination.hash:
if m["state"] == LXMF.LXMessage.DELIVERED:
msg_color = mdc(color_delivered, intensity_msgs)
heading_str = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] Delivered"
heading_str = f"{titlestr}[b]Sent[/b] {txstr}{delivery_syms}\n[b]State[/b] Delivered"
elif m["method"] == LXMF.LXMessage.PROPAGATED and m["state"] == LXMF.LXMessage.SENT:
msg_color = mdc(color_propagated, intensity_msgs)
heading_str = titlestr+"[b]Sent[/b] "+txstr+delivery_syms+"\n[b]State[/b] On Propagation Net"
heading_str = f"{titlestr}[b]Sent[/b] {txstr}{delivery_syms}\n[b]State[/b] On Propagation Net"
elif m["method"] == LXMF.LXMessage.PAPER:
msg_color = mdc(color_paper, intensity_msgs)
heading_str = titlestr+"[b]Created[/b] "+txstr+"\n[b]State[/b] Paper Message"
heading_str = f"{titlestr}[b]Created[/b] {txstr}\n[b]State[/b] Paper Message"
elif m["state"] == LXMF.LXMessage.FAILED:
msg_color = mdc(color_failed, intensity_msgs)
heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Failed"
heading_str = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] Failed"
elif m["state"] == LXMF.LXMessage.OUTBOUND or m["state"] == LXMF.LXMessage.SENDING:
msg_color = mdc(color_unknown, intensity_msgs)
heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Sending "
heading_str = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] Sending "
else:
msg_color = mdc(color_unknown, intensity_msgs)
heading_str = titlestr+"[b]Sent[/b] "+txstr+"\n[b]State[/b] Unknown"
heading_str = f"{titlestr}[b]Sent[/b] {txstr}\n[b]State[/b] Unknown"
else:
msg_color = mdc(color_received, intensity_msgs)
heading_str = titlestr
if phy_stats_str != "" and self.app.sideband.config["advanced_stats"]:
heading_str += phy_stats_str+"\n"
heading_str += f"{phy_stats_str}\n"
# TODO: Remove
# if stamp_valid:
# txstr += f" [b]Stamp[/b] value is {stamp_value} "
heading_str += "[b]Sent[/b] "+txstr+delivery_syms
heading_str += "\n[b]Received[/b] "+rxstr
heading_str += f"[b]Sent[/b] {txstr}{delivery_syms}"
heading_str += f"\n[b]Received[/b] {rxstr}"
if rcvd_d_str != "":
heading_str += rcvd_d_str
@ -575,7 +575,7 @@ class Messages():
if has_attachment:
heading_str += "\n[b]Attachments[/b] "
for attachment in attachments_field:
heading_str += str(attachment[0])+", "
heading_str += f"{attachment[0])}, "
heading_str = heading_str[:-2]
if has_audio:
@ -724,7 +724,7 @@ class Messages():
def x():
image_field = item.image_field
extension = str(image_field[0]).replace(".", "")
filename = time.strftime("LXM_%Y_%m_%d_%H_%M_%S", time.localtime(time.time()))+"."+str(extension)
filename = f"{time.strftime('LXM_%Y_%m_%d_%H_%M_%S', time.localtime(time.time()))}.{extension)}"
self.app.share_image(image_field[1], filename)
item.dmenu.dismiss()
@ -735,11 +735,11 @@ class Messages():
image_field = item.image_field
try:
extension = str(image_field[0]).replace(".", "")
filename = time.strftime("LXM_%Y_%m_%d_%H_%M_%S", time.localtime(time.time()))+"."+str(extension)
filename = f"{time.strftime('LXM_%Y_%m_%d_%H_%M_%S', time.localtime(time.time()))}.{extension)}"
if RNS.vendor.platformutils.is_darwin():
save_path = str(plyer.storagepath.get_downloads_dir()+filename).replace("file://", "")
else:
save_path = plyer.storagepath.get_downloads_dir()+"/"+filename
save_path = f"{plyer.storagepath.get_downloads_dir()}/{filename}"
with open(save_path, "wb") as save_file:
save_file.write(image_field[1])
@ -749,7 +749,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Image Saved",
text="The image has been saved to: "+save_path+"",
text=f"The image has been saved to: {save_path}",
buttons=[ ok_button ],
# elevation=0,
)
@ -764,7 +764,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Error",
text="Could not save the image:\n\n"+save_path+"\n\n"+str(e),
text=f"Could not save the image:\n\n{save_path}\n\n{e)}",
buttons=[ ok_button ],
# elevation=0,
)
@ -786,13 +786,13 @@ class Messages():
if RNS.vendor.platformutils.is_darwin():
output_path = str(plyer.storagepath.get_downloads_dir()).replace("file://", "")
else:
output_path = plyer.storagepath.get_downloads_dir()+"/"
output_path = f"{plyer.storagepath.get_downloads_dir()}/"
if len(attachments_field) == 1:
saved_text = "The attached file has been saved to: "+output_path
saved_text = f"The attached file has been saved to: {output_path}"
saved_title = "Attachment Saved"
else:
saved_text = "The attached files have been saved to: "+output_path
saved_text = f"The attached files have been saved to: {output_path}"
saved_title = "Attachment Saved"
for attachment in attachments_field:
@ -800,15 +800,15 @@ class Messages():
if RNS.vendor.platformutils.is_darwin():
save_path = str(plyer.storagepath.get_downloads_dir()+filename).replace("file://", "")
else:
save_path = plyer.storagepath.get_downloads_dir()+"/"+filename
save_path = f"{plyer.storagepath.get_downloads_dir()}/{filename}"
name_counter = 1
pre_count = save_path
while os.path.exists(save_path):
save_path = str(pre_count)+"."+str(name_counter)
save_path = f"{pre_count)}.{name_counter)}"
name_counter += 1
saved_text = "The attached file has been saved to: "+save_path
saved_text = f"The attached file has been saved to: {save_path}"
with open(save_path, "wb") as save_file:
save_file.write(attachment[1])
@ -833,7 +833,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Error",
text="Could not save the attachment:\n\n"+save_path+"\n\n"+str(e),
text=f"Could not save the attachment:\n\n{save_path}\n\n{e)}",
buttons=[ ok_button ],
# elevation=0,
)
@ -863,7 +863,7 @@ class Messages():
Clipboard.copy(str(tlm))
item.dmenu.dismiss()
except Exception as e:
RNS.log("An error occurred while decoding telemetry. The contained exception was: "+str(e), RNS.LOG_ERROR)
RNS.log(f"An error occurred while decoding telemetry. The contained exception was: {e)}", RNS.LOG_ERROR)
Clipboard.copy("Could not decode telemetry")
return x
@ -880,7 +880,7 @@ class Messages():
def x():
qr_image = lxm.as_qr()
hash_str = RNS.hexrep(lxm.hash[-2:], delimit=False)
filename = "Paper_Message_"+time.strftime(file_ts_format, time.localtime(m["sent"]))+"_"+hash_str+".png"
filename = f"Paper_Message_{time.strftime(file_ts_format, time.localtime(m['sent']))}_{hash_str}.png"
# filename = "Paper_Message.png"
self.app.share_image(qr_image, filename)
item.dmenu.dismiss()
@ -891,11 +891,11 @@ class Messages():
try:
qr_image = lxm.as_qr()
hash_str = RNS.hexrep(lxm.hash[-2:], delimit=False)
filename = "Paper_Message_"+time.strftime(file_ts_format, time.localtime(m["sent"]))+"_"+hash_str+".png"
filename = f"Paper_Message_{time.strftime(file_ts_format, time.localtime(m['sent']))}_{hash_str}.png"
if RNS.vendor.platformutils.is_darwin():
save_path = str(plyer.storagepath.get_downloads_dir()+filename).replace("file://", "")
else:
save_path = plyer.storagepath.get_downloads_dir()+"/"+filename
save_path = f"{plyer.storagepath.get_downloads_dir()}/{filename}"
qr_image.save(save_path)
item.dmenu.dismiss()
@ -903,7 +903,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="QR Code Saved",
text="The paper message has been saved to: "+save_path+"",
text=f"The paper message has been saved to: {save_path}",
buttons=[ ok_button ],
# elevation=0,
)
@ -918,7 +918,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Error",
text="Could not save the paper message QR-code to:\n\n"+save_path+"\n\n"+str(e),
text=f"Could not save the paper message QR-code to:\n\n{save_path}\n\n{e)}",
buttons=[ ok_button ],
# elevation=0,
)
@ -940,10 +940,10 @@ class Messages():
def x():
try:
qr_image = lxm.as_qr()
qr_tmp_path = self.app.sideband.tmp_dir+"/"+str(RNS.hexrep(lxm.hash, delimit=False))
qr_tmp_path = f"{self.app.sideband.tmp_dir}/{RNS.hexrep(lxm.hash, delimit=False))}"
qr_image.save(qr_tmp_path)
print_command = self.app.sideband.config["print_command"]+" "+qr_tmp_path
print_command = f"{self.app.sideband.config['print_command']} {qr_tmp_path}"
return_code = subprocess.call(shlex.split(print_command), stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
os.unlink(qr_tmp_path)
@ -955,7 +955,7 @@ class Messages():
ok_button = MDRectangleFlatButton(text="OK",font_size=dp(18))
dialog = MDDialog(
title="Error",
text="Could not print the paper message QR-code.\n\n"+str(e),
text=f"Could not print the paper message QR-code.\n\n{e)}",
buttons=[ ok_button ],
# elevation=0,
)

Some files were not shown because too many files have changed in this diff Show More