Improving python coding format

This commit is contained in:
Adsooi 2024-09-17 22:43:24 +02:00
parent 1bf175b09c
commit b50d56d511
Signed by: Ad5001
GPG key ID: EF45F9C6AFE20160
7 changed files with 47 additions and 44 deletions

View file

@ -20,13 +20,13 @@ from shutil import which
__VERSION__ = "0.6.0"
is_release = False
# Check if development version, if so get the date of the latest git patch
# and append it to the version string.
if not is_release and which('git') is not None:
from os.path import realpath, join, dirname, exists
from subprocess import check_output
from datetime import datetime
# Command to check date of latest git commit
cmd = ['git', 'log', '--format=%ci', '-n 1']
cwd = realpath(join(dirname(__file__), '..')) # Root AccountFree directory.
@ -41,4 +41,5 @@ if not is_release and which('git') is not None:
if __name__ == "__main__":
from .logarithmplotter import run
run()

View file

@ -87,7 +87,6 @@ def run():
icon_fallbacks.append(path.realpath(path.join(base_icon_path, "settings", "custom")))
QIcon.setFallbackSearchPaths(icon_fallbacks);
QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
app = QApplication(argv)
app.setApplicationName("LogarithmPlotter")
app.setDesktopFileName("eu.ad5001.LogarithmPlotter.desktop")
@ -104,10 +103,10 @@ def run():
app.installTranslator(translator);
# Installing macOS file handler.
macOSFileOpenHandler = None
macos_file_open_handler = None
if platform == "darwin":
macOSFileOpenHandler = native.MacOSFileOpenHandler()
app.installEventFilter(macOSFileOpenHandler)
macos_file_open_handler = native.MacOSFileOpenHandler()
app.installEventFilter(macos_file_open_handler)
engine = QQmlApplicationEngine()
global tmpfile
@ -138,7 +137,7 @@ def run():
chdir(path.dirname(path.realpath(__file__)))
if platform == "darwin":
macOSFileOpenHandler.init_io(js_globals.Modules.IO)
macos_file_open_handler.init_io(js_globals.Modules.IO)
# Check for LaTeX installation if LaTeX support is enabled
if config.getSetting("enable_latex"):

View file

@ -54,7 +54,9 @@ DEFAULT_SETTINGS = {
# Create config directory
CONFIG_PATH = {
"Linux": path.join(environ["XDG_CONFIG_HOME"], "LogarithmPlotter") if "XDG_CONFIG_HOME" in environ else path.join(path.expanduser("~"), ".config", "LogarithmPlotter"),
"Linux": path.join(environ["XDG_CONFIG_HOME"], "LogarithmPlotter")
if "XDG_CONFIG_HOME" in environ else
path.join(path.expanduser("~"), ".config", "LogarithmPlotter"),
"Windows": path.join(path.expandvars('%APPDATA%'), "LogarithmPlotter", "config"),
"Darwin": path.join(path.expanduser("~"), "Library", "Application Support", "LogarithmPlotter"),
}[system()]
@ -79,7 +81,7 @@ def init():
setSetting(setting_name+"."+setting_name2, cfg_data[setting_name][setting_name2])
else:
setSetting(setting_name, cfg_data[setting_name])
def save():
"""
Saves the config to the path.

View file

@ -94,16 +94,16 @@ class Helper(QObject):
pass
elif data[:3] == "LPF":
# More recent version of LogarithmPlotter file, but incompatible with the current format
raise Exception(QCoreApplication.translate("This file was created by a more recent version of LogarithmPlotter and cannot be backloaded in LogarithmPlotter v{}.\nPlease update LogarithmPlotter to open this file.".format(__VERSION__)))
msg = QCoreApplication.translate("This file was created by a more recent version of LogarithmPlotter and cannot be backloaded in LogarithmPlotter v{}.\nPlease update LogarithmPlotter to open this file.".format(__VERSION__))
raise Exception(msg)
else:
raise Exception("Invalid LogarithmPlotter file.")
except Exception as e: # If file can't be loaded
QMessageBox.warning(None, 'LogarithmPlotter',
QCoreApplication.translate('main', 'Could not open file "{}":\n{}').format(filename,
e),
QMessageBox.Ok) # Cannot parse file
msg = QCoreApplication.translate('main', 'Could not open file "{}":\n{}')
QMessageBox.warning(None, 'LogarithmPlotter', msg.format(filename, e), QMessageBox.Ok) # Cannot parse file
else:
QMessageBox.warning(None, 'LogarithmPlotter', QCoreApplication.translate('main', 'Could not open file: "{}"\nFile does not exist.').format(filename), QMessageBox.Ok) # Cannot parse file
msg = QCoreApplication.translate('main', 'Could not open file: "{}"\nFile does not exist.')
QMessageBox.warning(None, 'LogarithmPlotter', msg.format(filename), QMessageBox.Ok) # Cannot parse file
try:
chdir(path.dirname(path.realpath(__file__)))
except NotADirectoryError as e:
@ -159,9 +159,8 @@ class Helper(QObject):
"""
Returns the version info about Qt, PySide6 & Python
"""
return QCoreApplication.translate('main', "Built with PySide6 (Qt) v{} and python v{}").format(PySide6_version,
sys_version.split(
"\n")[0])
msg = QCoreApplication.translate('main', "Built with PySide6 (Qt) v{} and python v{}")
return msg.format(PySide6_version, sys_version.split("\n")[0])
@Slot()
def fetchChangelog(self):

View file

@ -23,6 +23,7 @@ class PyJSValue:
"""
Wrapper to provide easy way to interact with JavaScript values in Python directly.
"""
def __init__(self, js_value: QJSValue, parent: QJSValue = None):
self.qjs_value = js_value
self._parent = parent
@ -49,4 +50,3 @@ class PyJSValue:
return self.qjs_value.callWithInstance(self._parent, args)
else:
raise ValueError('Cannot call non-function JS value.')

View file

@ -78,19 +78,22 @@ class Latex(QObject):
if LATEX_PATH is None:
print("No Latex installation found.")
if "--test-build" not in argv:
QMessageBox.warning(None, "LogarithmPlotter - Latex setup",
QCoreApplication.translate("latex", "No Latex installation found.\nIf you already have a latex distribution installed, make sure it's installed on your path.\nOtherwise, you can download a Latex distribution like TeX Live at https://tug.org/texlive/."))
msg = QCoreApplication.translate("latex",
"No Latex installation found.\nIf you already have a latex distribution installed, make sure it's installed on your path.\nOtherwise, you can download a Latex distribution like TeX Live at https://tug.org/texlive/.")
QMessageBox.warning(None, "LogarithmPlotter - Latex setup", msg)
valid_install = False
elif DVIPNG_PATH is None:
print("DVIPNG not found.")
if "--test-build" not in argv:
QMessageBox.warning(None, "LogarithmPlotter - Latex setup", QCoreApplication.translate("latex", "DVIPNG was not found. Make sure you include it from your Latex distribution."))
msg = QCoreApplication.translate("latex",
"DVIPNG was not found. Make sure you include it from your Latex distribution.")
QMessageBox.warning(None, "LogarithmPlotter - Latex setup", msg)
valid_install = False
else:
try:
self.render("", 14, QColor(0, 0, 0, 255))
except Exception as e:
valid_install = False # Should have sent an error message if failed to render
valid_install = False # Should have sent an error message if failed to render
return valid_install
@Slot(str, float, QColor, result=str)
@ -119,7 +122,7 @@ class Latex(QObject):
img = QImage(export_path)
# Small hack, not very optimized since we load the image twice, but you can't pass a QImage to QML and expect it to be loaded
return f'{export_path}.png,{img.width()},{img.height()}'
@Slot(str, float, QColor, result=str)
def findPrerendered(self, latex_markup: str, font_size: float, color: QColor) -> str:
"""
@ -131,8 +134,7 @@ class Latex(QObject):
img = QImage(export_path)
data = f'{export_path}.png,{img.width()},{img.height()}'
return data
def create_export_path(self, latex_markup: str, font_size: float, color: QColor):
"""
Standardizes export path for renders.
@ -140,7 +142,6 @@ class Latex(QObject):
markup_hash = "render" + str(hash(latex_markup))
export_path = path.join(self.tempdir.name, f'{markup_hash}_{int(font_size)}_{color.rgb()}')
return markup_hash, export_path
def create_latex_doc(self, export_path: str, latex_markup: str):
"""
@ -183,16 +184,18 @@ class Latex(QObject):
"""
Runs a subprocess and handles exceptions and messages them to the user.
"""
cmd = " ".join(process)
proc = Popen(process, stdout=PIPE, stderr=PIPE, cwd=self.tempdir.name)
try:
out, err = proc.communicate(timeout=2) # 2 seconds is already FAR too long.
if proc.returncode != 0:
# Process errored
output = str(out, 'utf8') + "\n" + str(err, 'utf8')
QMessageBox.warning(None, "LogarithmPlotter - Latex",
QCoreApplication.translate("latex", "An exception occured within the creation of the latex formula.\nProcess '{}' ended with a non-zero return code {}:\n\n{}\nPlease make sure your latex installation is correct and report a bug if so.")
.format(" ".join(process), proc.returncode, output))
raise Exception("{0} process exited with return code {1}:\n{2}\n{3}".format(" ".join(process), str(proc.returncode), str(out, 'utf8'), str(err, 'utf8')))
msg = QCoreApplication.translate("latex",
"An exception occured within the creation of the latex formula.\nProcess '{}' ended with a non-zero return code {}:\n\n{}\nPlease make sure your latex installation is correct and report a bug if so.")
msg = msg.format(cmd, proc.returncode, output)
QMessageBox.warning(None, "LogarithmPlotter - Latex", msg)
raise Exception(f"{cmd} process exited with return code {str(proc.returncode)}:\n{str(out, 'utf8')}\n{str(err, 'utf8')}")
except TimeoutExpired as e:
# Process timed out
proc.kill()
@ -202,14 +205,14 @@ class Latex(QObject):
for pkg in PACKAGES:
if f'{pkg}.sty' in output:
# Package missing.
QMessageBox.warning(None, "LogarithmPlotter - Latex",
QCoreApplication.translate("latex", "Your LaTeX installation does not include some required packages:\n\n- {} (https://ctan.org/pkg/{})\n\nMake sure said package is installed, or disable the LaTeX rendering in LogarithmPlotter.")
.format(pkg, pkg))
msg = QCoreApplication.translate("latex",
"Your LaTeX installation does not include some required packages:\n\n- {} (https://ctan.org/pkg/{})\n\nMake sure said package is installed, or disable the LaTeX rendering in LogarithmPlotter.")
QMessageBox.warning(None, "LogarithmPlotter - Latex", msg.format(pkg, pkg))
raise Exception("Latex: Missing package " + pkg)
QMessageBox.warning(None, "LogarithmPlotter - Latex",
QCoreApplication.translate("latex", "An exception occured within the creation of the latex formula.\nProcess '{}' took too long to finish:\n{}\nPlease make sure your latex installation is correct and report a bug if so.")
.format(" ".join(process), output))
raise Exception(" ".join(process) + " process timed out:\n" + output)
msg = QCoreApplication.translate("latex",
"An exception occured within the creation of the latex formula.\nProcess '{}' took too long to finish:\n{}\nPlease make sure your latex installation is correct and report a bug if so.")
QMessageBox.warning(None, "LogarithmPlotter - Latex", msg.format(cmd, output))
raise Exception(f"{cmd} process timed out:\n{output}")
def cleanup(self, export_path):
"""

View file

@ -53,9 +53,8 @@ class UpdateCheckerRunnable(QRunnable):
current_version_tuple = self.current_version.split(".")
is_version_newer = version_tuple > current_version_tuple
if is_version_newer:
msg_text = QCoreApplication.translate("update",
"An update for LogarithmPlotter (v{}) is available.").format(
version)
msg_text = QCoreApplication.translate("update", "An update for LogarithmPlotter (v{}) is available.")
msg_text = msg_text.format(version)
update_available = True
else:
show_alert = False
@ -63,11 +62,11 @@ class UpdateCheckerRunnable(QRunnable):
except HTTPError as e:
msg_text = QCoreApplication.translate("update",
"Could not fetch update information: Server error {}.").format(
str(e.code))
"Could not fetch update information: Server error {}.")
msg_text = msg_text.format(str(e.code))
except URLError as e:
msg_text = QCoreApplication.translate("update", "Could not fetch update information: {}.").format(
str(e.reason))
msg_text = QCoreApplication.translate("update", "Could not fetch update information: {}.")
msg_text = msg_text.format(str(e.reason))
self.callback.got_update_info.emit(show_alert, msg_text, update_available)