Changing version, making Helper objects globals, adding their polyfills.
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
Adsooi 2024-03-28 22:52:14 +01:00
parent 08fea34366
commit 861bb001c9
Signed by: Ad5001
GPG key ID: EF45F9C6AFE20160
7 changed files with 77 additions and 71 deletions

View file

@ -17,8 +17,8 @@
"""
from shutil import which
__VERSION__ = "0.5.0"
is_release = True
__VERSION__ = "0.5.1"
is_release = False
# Check if development version, if so get the date of the latest git patch

View file

@ -112,9 +112,12 @@ def run():
global tmpfile
helper = Helper(pwd, tmpfile)
latex = Latex(tempdir)
engine.globalObject().setProperty('Runtime', engine.newObject())
engine.rootContext().setContextProperty("Helper", helper)
engine.rootContext().setContextProperty("Latex", latex)
modules = engine.newObject()
engine.globalObject().setProperty('Runtime', modules)
engine.globalObject().setProperty('Helper', engine.newQObject(helper))
engine.globalObject().setProperty("Latex", engine.newQObject(latex))
# engine.rootContext().setContextProperty("Helper", helper)
# engine.rootContext().setContextProperty("Latex", latex)
engine.rootContext().setContextProperty("TestBuild", "--test-build" in argv)
engine.rootContext().setContextProperty("StartTime", dep_time)

View file

@ -44,16 +44,7 @@ ApplicationWindow {
color: sysPalette.window
title: "LogarithmPlotter " + (settings.saveFilename != "" ? " - " + settings.saveFilename.split('/').pop() : "") + (history.saved ? "" : "*")
SystemPalette {
id: sysPalette; colorGroup: SystemPalette.Active
Component.onCompleted: {
// LatexJS initialization.
Runtime.Latex.enabled = Helper.getSettingBool("enable_latex")
Runtime.Latex.Renderer = Latex
Runtime.Latex.defaultColor = sysPalette.windowText
}
}
SystemPalette { id: sysPalette; colorGroup: SystemPalette.Active }
SystemPalette { id: sysPaletteIn; colorGroup: SystemPalette.Disabled }
menuBar: appMenu.trueItem

View file

@ -108,7 +108,7 @@ export class Action {
if(!Latex.enabled)
throw new Error("Cannot render an item as LaTeX when LaTeX is disabled.")
let imgDepth = Runtime.History.imageDepth
let [src, width, height] = Latex.Renderer.render(
let [src, width, height] = Latex.render(
latexString,
imgDepth * (Runtime.History.fontSize + 2),
Runtime.History.themeTextColor

View file

@ -28,3 +28,28 @@ qsTr = qsTr || function(string) { throw new Error('qsTr not implemented.'); }
QT_TRANSLATE_NOOP = QT_TRANSLATE_NOOP || function(string, string) { throw new Error('QT_TRANSLATE_NOOP not implemented.'); }
/** @type {function(string|boolean|int): string} */
String.prototype.arg = String.prototype.arg || function(parameter) { throw new Error('arg not implemented.'); }
/** Typehints for Helper. */
const Helper = {
/** @type {function(string): boolean} */
getSettingBool: (setting) => true,
/** @type {function(string): int} */
getSettingInt: (setting) => 0,
/** @type {function(string): string} */
getSetting: (setting) => '',
/** @type {function(string, boolean)} */
setSettingBool: (setting, value) => {},
/** @type {function(string, int)} */
setSettingInt: (setting, value) => 0,
/** @type {function(string, string)} */
setSetting: (setting, value) => '',
/** @type {function(string, string)} */
write: (filename, data) => {},
/** @type {function(string): string} */
load: (filename) => '',
}
const Latex = {
/** @type {function(string, number, string): string} */
render: (latex_markup, font_size, color) => '',
}

View file

@ -50,11 +50,12 @@ class LatexAPI extends RuntimeAPI {
/**
* true if latex has been enabled by the user, false otherwise.
*/
this.enabled = false
this.enabled = Helper.getSettingBool("enable_latex")
/**
* LaTeX python backend QObject.
* Mirror method for Python object.
* @type {function(string, number, string): string}.
*/
this.Renderer = null
this.render = Latex.render
}
/**

View file

@ -52,12 +52,14 @@ $$$$ $markup $$$$
\end{document}
""")
class Latex(QObject):
"""
Base class to convert Latex equations into PNG images with custom font color and size.
It doesn't have any python dependency, but requires a working latex installation and
dvipng to be installed on the system.
"""
def __init__(self, tempdir: TemporaryDirectory):
QObject.__init__(self)
self.tempdir = tempdir
@ -69,7 +71,8 @@ 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/."))
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/."))
elif DVIPNG_PATH is None:
print("DVIPNG not found.")
if "--test-build" not in argv:
@ -103,7 +106,7 @@ class Latex(QObject):
# self.convert_dvi_to_png(latex_path, export_path+"@4", font_size*4, color)
except Exception as e: # One of the processes failed. A message will be sent every time.
raise e
img = QImage(export_path);
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()}'
@ -155,8 +158,12 @@ class Latex(QObject):
# Process errored
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, str(out, 'utf8')+"\n"+str(err,'utf8')))
raise Exception(" ".join(process) + " process exited with return code " + str(proc.returncode) + ":\n" + str(out, 'utf8')+"\n"+str(err,'utf8'))
.format(" ".join(process), proc.returncode,
str(out, 'utf8') + "\n" + str(err, 'utf8')))
raise Exception(
" ".join(process) + " 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()
@ -172,24 +179,3 @@ class Latex(QObject):
"""
for i in [".tex", ".aux", ".log"]:
remove(export_path + i)
"""
@Slot(str, float, QColor, result=str)
def render_legacy(self, latexstring, font_size, color = True):
exprpath = path.join(self.tempdir.name, f'{hash(latexstring)}_{font_size}_{color.rgb()}.png')
print("Rendering", latexstring, exprpath)
if not path.exists(exprpath):
fg = color.convertTo(QColor.Rgb)
fg = f'rgb {fg.redF()} {fg.greenF()} {fg.blueF()}'
preview('$${' + latexstring + '}$$', viewer='file', filename=exprpath, dvioptions=[
"-T", "tight",
"-z", "0",
"--truecolor",
f"-D {int(font_size * 72.27 / 100) * 10}", # See https://linux.die.net/man/1/dvipng#-D for convertion
"-bg", "Transparent",
"-fg", fg],
euler=False)
img = QImage(exprpath);
# 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'{exprpath},{img.width()},{img.height()}'
"""