-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmjrender.py
executable file
·177 lines (151 loc) · 6.48 KB
/
mjrender.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
#import sys
#from functools import partial
#from PyQt5.QtWidgets import *
#from PyQt5.QtCore import Qt, QUrl, QEvent, QSize, QItemSelection, QItemSelectionModel, QMimeData, pyqtSlot
#from PyQt5.QtGui import QTextDocument, QPalette, QColor, QCursor, QClipboard, QImage, QPainter
from PyQt5.QtWebEngineWidgets import QWebEnginePage, QWebEngineView, QWebEngineSettings
#from PyQt5.QtSvg import QSvgWidget, QGraphicsSvgItem, QSvgRenderer
#from io import BytesIO
#from texsyntax import LatexHighlighter
import matplotlib.pyplot as plt
#
#from PyQt5.QtWidgets import (QWidget, QSlider, QLineEdit, QLabel, QPushButton, QScrollArea,QApplication,
# QHBoxLayout, QVBoxLayout, QMainWindow, QSizePolicy, QAbstractItemView)
#
#from PyQt5 import QtWidgets, uic
#
#from formulalist import FormulaList
#
#from pysvg.parser import parse
# from PyQt5 import Qt
# 'PyQt5.QtWebEngineWidgets.QWebEngineSettings.ShowScrollBars'
context = r'''\newcommand{\Ex}{\mathop{\rm Ex}}
\newcommand{\T}{\mathop{\rm T}}
\newcommand{\range}{\mathop{\rm range}}
'''.replace('{', '{{').replace('}', '}}')
mathjax_v2_url = "file:///usr/share/javascript/mathjax/MathJax.js?delayStartupUntil=onload"
mathjax_url_remote = "https://cdn.jsdelivr.net/npm/mathjax@3/es5/tex-svg.js?delayStartupUntil=onload"
mathjax_url = 'file:///usr/share/javascript/mathjax@3/es5/tex-svg-full.js'
mathjax_config_old = """
MathJax.Hub.Config({
showMathMenu: false,
jax: ['input/TeX', 'output/SVG'],
extensions: ['tex2jax.js', 'MathMenu.js', 'MathZoom.js'],
TeX: {
extensions: ['AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js']
}
});
""".replace('{', '{{').replace('}', '}}')
mathjax_config_v2_old = """
MathJax.Hub.Config({
showMathMenu: false,
jax: ['input/TeX', 'output/SVG'],
extensions: ['tex2jax.js', 'MathMenu.js', 'MathZoom.js'],
TeX: {
extensions: ['AMSmath.js', 'AMSsymbols.js', 'noErrors.js', 'noUndefined.js']
}
});
""".replace('{', '{{').replace('}', '}}')
mathjax_v2_config = """
MathJax.Hub.Config({
jax: ["input/TeX","input/MathML","input/AsciiMath","output/SVG"],
extensions: ["tex2jax.js","mml2jax.js","asciimath2jax.js","MathMenu.js",
"MathZoom.js","AssistiveMML.js", "a11y/accessibility-menu.js"],
TeX: { extensions:
["AMSmath.js","AMSsymbols.js","noErrors.js","noUndefined.js"]
});
""".replace('{', '{{').replace('}', '}}')
mathjax_config = """
window.MathJax = {
options: {
enableMenu: false, ignoreHtmlClass:
'tex2jax_ignore', processHtmlClass:
'tex2jax_process' },
tex: { packages: ['base', 'ams', 'noerrors', 'noundefined', '+', 'color']
color: { padding: 5px
borderWidth: 5px
}
},
loader: { load: ['input/tex-base', 'output/svg', 'ui/menu',
'[tex]/require'] },
};
""".replace('{', '{{').replace('}', '}}')
page_template = """
<html>
<head>
<script type="text/javascript" id="MathJax-script"
src="{url}">
</script>
<script type="text/x-mathjax-config">
{config}
</script>
</head>
<body>
<div style="background-color: white">
<mathjax id="mathjax-context" style="font-size:2.3em">\[{context}\]</mathjax>
<mathjax id="mathjax-container" style="font-size:2.3em">\[{{formula}}\]</mathjax>
</div>
</body>
</html>
""".format(url=mathjax_url, context=context, config=mathjax_config)
plt.rc('mathtext', fontset='cm')
def render_latex_as_svg(latex_formula):
fig, ax = plt.subplots()
ax.text(0.5, 0.5, fr'${latex_formula}$', size=30, ha='center', va='center')
# ax.text(0.5, 0.5, fr'[{latex_formula}]', size=30, ha='center', va='center')
ax.set_axis_off()
buffer = BytesIO()
plt.savefig(buffer, format='svg')
svg_image = buffer.getvalue()
buffer.close()
plt.close(fig)
return svg_image
class MathJaxRender(QWebEnginePage):
def __init__(self):
super().__init__()
self.page_template = page_template
# self.loadFinished.connect(self._on_load_finished)
self.copy_profile_button.setMenu(self.copy_menu)
def append_content(self, content):
# Append the formula to the list box
content_html= f"{content}<br>"
if '\\(' in content and '\\)' in content:
# Use MathJax to render math expressions enclosed in \( and \)
content_html = content_html.replace('\\(', '<mathjax style="font-size:2.3em" >').replace('\\)', '</mathjax>')
# js_code = f"document.body.innerHTML += '{content_html}'; MathJax.typeset();"
# self.text_area.page().runJavaScript(js_code)
self.eq_list.append_formula(content)
def updatePreview(self):
formula_str = self.input_box.toPlainText()
self.preview.setHtml(self.page_template.format(formula=formula_str), QUrl('file://'))
def eventFilter(self, obj, event):
if obj is self.input_box and event.type() == QEvent.FocusIn:
# Clear the input box when it receives focus
# self.input_box.setPlainText('')
...
if event.type() == QEvent.KeyPress and obj is self.input_box:
if event.key() == Qt.Key_Return and self.input_box.hasFocus():
if event.modifiers() & Qt.ControlModifier:
self.add_current_formula()
return True # this seems to delete the trailing \n.. interesting
return super().eventFilter(obj, event)
def add_current_formula(self):
formula_str = self.input_box.toPlainText()
if formula_str:
print('appending formula: ', formula_str)
self.eq_queue.append(formula_str)
print('svg: ', self.formula_svg)
self.input_box.clear()
self.render.setHtml(self.page_template.format(formula=formula_str),
QUrl('file://'))
def _on_load_finished(self):
# Extract the SVG output from the page and add an XML header
xml_header = b'<?xml version="1.0" encoding="utf-8" standalone="no"?>'
self.runJavaScript("""
var mjelement = document.getElementById('mathjax-container');
mjelement.getElementsByTagName('svg')[0].outerHTML;
""", lambda result: self.update_svg(xml_header + result.encode()))
def update_svg(self, svg:bytes):
# add XML header
formula = self.eq_queue.pop(0)
self.eq_list.append_formula_svg(formula, svg)