1
0
forked from IPKM/nmreval

run scripts

run scripts

Co-authored-by: Dominik Demuth <dominik.demuth@physik.tu-darmstadt.de>
Reviewed-on: IPKM/nmreval#291
This commit is contained in:
2024-09-29 17:21:40 +00:00
parent b2a3881fa8
commit 4108deb69a
20 changed files with 401 additions and 229 deletions

View File

@ -1,309 +0,0 @@
# CodeEditor based on QT example, Python syntax highlighter found on Python site
import typing
from ast import parse
from ..Qt import QtGui, QtCore, QtWidgets
def _make_textformats(color, style=''):
"""Return a QTextCharFormat with the given attributes.
"""
_color = QtGui.QColor()
_color.setNamedColor(color)
_format = QtGui.QTextCharFormat()
_format.setForeground(_color)
if 'bold' in style:
_format.setFontWeight(QtGui.QFont.Bold)
if 'italic' in style:
_format.setFontItalic(True)
return _format
# Syntax styles that can be shared by all languages
STYLES = {
'keyword': _make_textformats('blue'),
'operator': _make_textformats('black'),
'brace': _make_textformats('black'),
'defclass': _make_textformats('black', 'bold'),
'string': _make_textformats('darkGreen'),
'comment': _make_textformats('gray', 'italic'),
'self': _make_textformats('brown', 'italic'),
'property': _make_textformats('brown'),
'numbers': _make_textformats('darkRed'),
}
class PythonHighlighter(QtGui.QSyntaxHighlighter):
"""
Syntax highlighter for the Python language.
"""
# Python keywords
keywords = [
'and', 'assert', 'break', 'class', 'continue', 'def',
'del', 'elif', 'else', 'except', 'exec', 'finally',
'for', 'from', 'global', 'if', 'import', 'in',
'is', 'lambda', 'not', 'or', 'pass', 'print',
'raise', 'return', 'try', 'while', 'yield',
'None', 'True', 'False', 'object'
]
def __init__(self, document):
super().__init__(document)
# Multi-line strings (expression, flag, style)
# FIXME: The triple-quotes in these two lines will mess up the
# syntax highlighting from this point onward
self.tri_single = (QtCore.QRegExp("r'{3}"), 1, STYLES['string'])
self.tri_double = (QtCore.QRegExp('r?"{3}'), 2, STYLES['string'])
rules = []
# Keyword, operator, and brace rules
rules += [(rf'\b{w}\b', 0, STYLES['keyword']) for w in PythonHighlighter.keywords]
# Other rules
rules += [
# 'self'
(r'\bself\b', 0, STYLES['self']),
# 'def' followed by an identifier
(r'\bdef\b\s*(\w+)', 1, STYLES['defclass']),
# 'class' followed by an identifier
(r'\bclass\b\s*(\w+)', 1, STYLES['defclass']),
# decorator @ followed by a word
(r'\s*@(\w+)\s*', 0, STYLES['property']),
# Numeric literals
(r'\b[+-]?\d+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?0[xX][\dA-Fa-f]+[lL]?\b', 0, STYLES['numbers']),
(r'\b[+-]?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?\b', 0, STYLES['numbers']),
# Double-quoted string, possibly containing escape sequences
(r'[rf]?"[^"\\]*(\\.[^"\\]*)*"', 0, STYLES['string']),
# Single-quoted string, possibly containing escape sequences
(r"[rf]?'[^'\\]*(\\.[^'\\]*)*'", 0, STYLES['string']),
# From '#' until a newline
(r'#[^\n]*', 0, STYLES['comment']),
]
# Build a QRegExp for each pattern
self.rules = [(QtCore.QRegExp(pat), index, fmt) for (pat, index, fmt) in rules]
def highlightBlock(self, text):
"""
Apply syntax highlighting to the given block of text.
"""
# Do other syntax formatting
for expression, nth, rule in self.rules:
index = expression.indexIn(text, 0)
while index >= 0:
# We actually want the index of the nth match
index = expression.pos(nth)
length = len(expression.cap(nth))
self.setFormat(index, length, rule)
index = expression.indexIn(text, index + length)
self.setCurrentBlockState(0)
# Do multi-line strings
in_multiline = self.match_multiline(text, *self.tri_single)
if not in_multiline:
in_multiline = self.match_multiline(text, *self.tri_double)
def match_multiline(self, text, delimiter, in_state, style):
"""
Highlighting of multi-line strings. ``delimiter`` should be a
``QRegExp`` for triple-single-quotes or triple-double-quotes, and
``in_state`` should be a unique integer to represent the corresponding
state changes when inside those strings. Returns True if we're still
inside a multi-line string when this function is finished.
"""
# If inside triple-single quotes, start at 0
if self.previousBlockState() == in_state:
start = 0
add = 0
# Otherwise, look for the delimiter on this line
else:
start = delimiter.indexIn(text)
# Move past this match
add = delimiter.matchedLength()
# As long as there's a delimiter match on this line...
while start >= 0:
# Look for the ending delimiter
end = delimiter.indexIn(text, start + add)
# Ending delimiter on this line?
if end >= add:
length = end - start + add + delimiter.matchedLength()
self.setCurrentBlockState(0)
# No; multi-line string
else:
self.setCurrentBlockState(in_state)
try:
length = text.length() - start + add
except AttributeError:
length = len(text) - start + add
# Apply formatting
self.setFormat(start, length, style)
# Look for the next match
start = delimiter.indexIn(text, start + length)
# Return True if still inside a multi-line string, False otherwise
if self.currentBlockState() == in_state:
return True
else:
return False
class LineNumbers(QtWidgets.QWidget):
def __init__(self, editor):
super().__init__(editor)
self.editor = editor
def sizeHint(self):
return QtCore.QSize(self.editor.width_linenumber, 0)
def paintEvent(self, event):
self.editor.paintevent_linenumber(event)
class CodeEditor(QtWidgets.QPlainTextEdit):
# more or less a direct translation of the Qt example
def __init__(self, parent):
super().__init__(parent)
self.current_linenumber = LineNumbers(self)
self.blockCountChanged.connect(self.update_width_linenumber)
self.updateRequest.connect(self.update_current_area)
self.cursorPositionChanged.connect(self.highlight_current_line)
self.update_width_linenumber(0)
self.highlight = PythonHighlighter(self.document())
def keyPressEvent(self, evt):
if evt.key() == QtCore.Qt.Key_Tab:
# use spaces instead of tab
self.insertPlainText(' '*4)
elif evt.key() == QtCore.Qt.Key_Insert:
self.setOverwriteMode(not self.overwriteMode())
else:
super().keyPressEvent(evt)
@property
def width_linenumber(self):
digits = 1
count = max(1, self.blockCount())
while count >= 10:
count /= 10
digits += 1
space = 6 + self.fontMetrics().width('9') * digits
return space
def update_width_linenumber(self, _):
self.setViewportMargins(self.width_linenumber, 0, 0, 0)
def update_current_area(self, rect, dy):
if dy:
self.current_linenumber.scroll(0, dy)
else:
self.current_linenumber.update(0, rect.y(), self.current_linenumber.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.update_width_linenumber(0)
def resizeEvent(self, evt):
super().resizeEvent(evt)
cr = self.contentsRect()
self.current_linenumber.setGeometry(QtCore.QRect(cr.left(), cr.top(), self.width_linenumber, cr.height()))
def paintevent_linenumber(self, evt):
painter = QtGui.QPainter(self.current_linenumber)
painter.fillRect(evt.rect(), QtCore.Qt.lightGray)
block = self.firstVisibleBlock()
block_number = block.blockNumber()
top = self.blockBoundingGeometry(block).translated(self.contentOffset()).top()
bottom = top + self.blockBoundingRect(block).height()
# Just to make sure I use the right font
height = self.fontMetrics().height()
while block.isValid() and (top <= evt.rect().bottom()):
if block.isVisible() and (bottom >= evt.rect().top()):
number = str(block_number + 1)
painter.setPen(QtCore.Qt.black)
painter.drawText(0, int(top), self.current_linenumber.width() - 3, height,
QtCore.Qt.AlignRight, number)
block = block.next()
top = bottom
bottom = top + self.blockBoundingRect(block).height()
block_number += 1
def highlight_current_line(self):
extra_selections = []
if not self.isReadOnly():
selection = QtWidgets.QTextEdit.ExtraSelection()
line_color = QtGui.QColor(QtCore.Qt.yellow).lighter(180)
selection.format.setBackground(line_color)
selection.format.setProperty(QtGui.QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extra_selections.append(selection)
self.setExtraSelections(extra_selections)
class EditorWidget(QtWidgets.QWidget):
def __init__(self, parent=None):
super().__init__(parent=parent)
layout = QtWidgets.QVBoxLayout()
layout.setContentsMargins(0, 0, 0, 0)
self.editor = CodeEditor(self)
layout.addWidget(self.editor)
self.error_label = QtWidgets.QLabel(self)
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
self.error_label.setFont(font)
self.error_label.setVisible(False)
layout.addWidget(self.error_label)
self.setLayout(layout)
for attr in ['appendPlainText', 'toPlainText', 'insertPlainText', 'setPlainText']:
setattr(self, attr, getattr(self.editor, attr))
self.editor.textChanged.connect(self._check_syntax)
def _check_syntax(self) -> (int, tuple[typing.Any]):
is_valid = True
# Compile into an AST and check for syntax errors.
try:
_ = parse(self.toPlainText(), filename='<string>')
except SyntaxError as e:
self.error_label.setText(f'Syntax error in line {e.lineno}: {e.args[0]}')
is_valid = False
except Exception as e:
self.error_label.setText(f'Unexpected error: {e.args[0]}')
is_valid = False
self.error_label.setVisible(not is_valid)

View File

@ -3,7 +3,7 @@ from pathlib import Path
from PyQt5 import QtWidgets
from .codeeditor import _make_textformats
from ..editors.codeeditor import _make_textformats
from ..Qt import QtWidgets, QtCore, QtGui
from nmreval.configs import config_paths

View File

@ -4,6 +4,8 @@ from collections import namedtuple
import numpy as np
import nmreval
from nmreval import models
from nmreval.configs import config_paths
from nmreval.lib.importer import find_models, import_
@ -28,6 +30,7 @@ class Namespace:
'y_err': (None, 'y error values'),
'fit': (None, 'dictionary of fit parameter', 'fit["PIKA"]'),
'np': (np, 'numpy module'),
'nmreval': (nmreval, 'built-in classes and stuff')
},
parents=('Basic', 'General'),
)

View File

@ -3,8 +3,10 @@ import urllib.request
from functools import cache
from PyQt5 import QtWidgets, QtGui, QtCore
from .._py.pokewindow import Ui_Dialog
from .._py.pokeentry import Ui_Form
from numpy.random import randint
from gui_qt._py.pokewindow import Ui_Dialog
from gui_qt._py.pokeentry import Ui_Form
def get_connection(db):
@ -37,6 +39,8 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
self.comboBox_2.currentIndexChanged.connect(self.collect_pokemon)
self.comboBox.currentIndexChanged.connect(self.collect_pokemon)
self.pushButton.clicked.connect(self.randomize)
self.collect_pokemon()
def _fetch_names(self):
@ -149,12 +153,15 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
self.tableWidget_2.clearContents()
self.tableWidget_2.setRowCount(0)
self.tableWidget_2.setSortingEnabled(False)
for entry in result:
row = self.tableWidget_2.rowCount()
self.tableWidget_2.setRowCount(row+1)
item = QtWidgets.QTableWidgetItem(f"{entry['entry_number']:04d}")
item.setData(QtCore.Qt.ItemDataRole.UserRole, entry['species_id'])
item.setData(QtCore.Qt.ItemDataRole.UserRole+1, entry['pokemon_id'])
self.tableWidget_2.setItem(row, 0, item)
name_en = entry['name_en']
@ -181,7 +188,7 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
type_en.append(t_en)
type_de.append(t_de)
item = QtWidgets.QTableWidgetItem('\n'.join(type_en))
item = QtWidgets.QTableWidgetItem(' / '.join(type_en))
item.setToolTip('\n'.join(type_en))
self.tableWidget_2.setItem(row, 2, item)
@ -215,11 +222,20 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
self.tableWidget_2.setItem(row, 12, item)
self.tableWidget_2.resizeColumnToContents(1)
self.tableWidget_2.resizeColumnToContents(2)
self.tableWidget_2.setSortingEnabled(True)
def show_pokemon(self):
table = self.sender()
row = table.currentRow()
poke_id = table.item(row, 0).data(QtCore.Qt.ItemDataRole.UserRole)
def randomize(self):
select = randint(0, self.tableWidget_2.rowCount())
self.show_pokemon(select)
def show_pokemon(self, row: int = None):
table = self.tableWidget_2
if row is None:
row = table.currentRow()
species_id = table.item(row, 0).data(QtCore.Qt.ItemDataRole.UserRole)
poke_id = table.item(row, 0).data(QtCore.Qt.ItemDataRole.UserRole+1)
pokemon_name = table.item(row, 1).text()
connection = get_connection(self._db)
@ -227,7 +243,7 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
cursor.execute(
'SELECT p.id FROM pokemon p WHERE p.species_id = ?',
(poke_id,)
(species_id,)
)
pokemon = cursor.fetchall()
@ -237,9 +253,14 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
for i in range(1, self.tabWidget.count()):
self.tabWidget.setTabVisible(i, False)
widget_idx = 0
for i, p in enumerate(pokemon):
entry_widget = self.tabWidget.widget(i)
if poke_id == p[0]:
widget_idx = i
if entry_widget is None:
self.tabWidget.addTab(PokemonEntry(p[0]), '')
@ -247,12 +268,13 @@ class QPoke(QtWidgets.QDialog, Ui_Dialog):
self.tabWidget.setTabVisible(i, True)
name = self.tabWidget.widget(i).create_pokemon(p[0])
self.tabWidget.setTabText(i, name)
self.tabWidget.setCurrentIndex(widget_idx)
class PokemonEntry(QtWidgets.QWidget, Ui_Form):
_db = ''
def __init__(self, pokemon_id, parent=None):
def __init__(self, pokemon_id: int, parent=None):
super().__init__(parent=parent)
self.setupUi(self)
@ -275,7 +297,7 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
self.species_label.setToolTip(species['genus_de'])
self.height_label.setText(f"{pokemon['height'] / 10} m")
self.weight_label.setText(f"{pokemon['weight']} kg")
self.weight_label.setText(f"{pokemon['weight'] / 10} kg")
if species['gender_ratio'] == -1:
gender = "Gender unknown"
@ -326,10 +348,23 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
self.type_labels[slot].setToolTip(QPoke.types[type_id][0])
evolutions = self.make_evolution(pokemon['evolution_id'])
evo_text = []
for e in evolutions:
evo_text.append(f'{e[0]} (#{e[1]:04d}) to {e[2]} (#{e[3]:04d}) \t\t ({e[4]})')
self.evolution_bar.setText('<br>'.join(evo_text))
self.tableWidget.clear()
self.tableWidget.setColumnCount(4)
self.tableWidget.setRowCount(len(evolutions))
for i, e in enumerate(evolutions):
item = QtWidgets.QTableWidgetItem(f'{e[0]} (#{e[1]:04d})')
self.tableWidget.setItem(i, 0, item)
item = QtWidgets.QTableWidgetItem('to')
self.tableWidget.setItem(i, 1, item)
item = QtWidgets.QTableWidgetItem(f'{e[2]} (#{e[3]:04d})')
self.tableWidget.setItem(i, 2, item)
item = QtWidgets.QTableWidgetItem(f'{e[4]}')
self.tableWidget.setItem(i, 3, item)
self.tableWidget.resizeColumnsToContents()
self.tableWidget.resizeRowsToContents()
if form['full_name_en'] is not None:
return form['full_name_en']
@ -438,7 +473,6 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
return form, types
@cache
def make_evolution(self, poke_id: int):
steps = []
@ -448,6 +482,7 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
cursor.execute('SELECT * FROM evolution_names WHERE id = ?', (poke_id,))
chain = cursor.fetchall()
conn.close()
trigger_texts = [
None,
@ -497,7 +532,6 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
}
for c in chain:
lvl0 = c["name_en"]
if c['gender'] == 1:
lvl0 += ' (female)'
@ -519,17 +553,4 @@ class PokemonEntry(QtWidgets.QWidget, Ui_Form):
(lvl0, c['evolves_from'], c['evolve_en'], c['species_id'], ', '.join(filter(lambda x: x, level_text)))
)
conn.close()
return steps
if __name__ == '__main__':
app = QtWidgets.QApplication([])
sourcedb = 'pokemon.sqlite'
w = QPoke(sourcedb)
w.show()
app.exec()

View File

@ -1,132 +0,0 @@
from __future__ import annotations
from pathlib import Path
from ..Qt import QtWidgets, QtCore, QtGui
from ..lib.codeeditor import EditorWidget
class QUsermodelEditor(QtWidgets.QMainWindow):
modelsChanged = QtCore.pyqtSignal()
def __init__(self, fname: str | Path = None, parent=None):
super().__init__(parent=parent)
self._init_gui()
self.fname = None
self._dir = None
if fname is not None:
self.read_file(fname)
def _init_gui(self):
self.centralwidget = QtWidgets.QWidget(self)
layout = QtWidgets.QVBoxLayout(self.centralwidget)
layout.setContentsMargins(3, 3, 3, 3)
layout.setSpacing(3)
self.edit_field = EditorWidget(self.centralwidget)
font = QtGui.QFont('default')
font.setStyleHint(font.Monospace)
font.setPointSize(10)
self.edit_field.setFont(font)
layout.addWidget(self.edit_field)
self.setCentralWidget(self.centralwidget)
self.statusbar = QtWidgets.QStatusBar(self)
self.setStatusBar(self.statusbar)
self.menubar = self.menuBar()
self.menuFile = QtWidgets.QMenu('File', self.menubar)
self.menubar.addMenu(self.menuFile)
self.menuFile.addAction('Open...', self.open_file, QtGui.QKeySequence.Open)
self.menuFile.addAction('Save', self.overwrite_file, QtGui.QKeySequence.Save)
self.menuFile.addAction('Save as...', self.save_file, QtGui.QKeySequence('Ctrl+Shift+S'))
self.menuFile.addSeparator()
self.menuFile.addAction('Close', self.close, QtGui.QKeySequence.Quit)
self.resize(800, 600)
self.setGeometry(QtWidgets.QStyle.alignedRect(
QtCore.Qt.LeftToRight, QtCore.Qt.AlignCenter,
self.size(), QtWidgets.qApp.desktop().availableGeometry()
))
@property
def is_modified(self):
return self.edit_field.document().isModified()
@is_modified.setter
def is_modified(self, val: bool):
self.edit_field.document().setModified(val)
@QtCore.pyqtSlot()
def open_file(self):
overwrite = self.changes_saved
if overwrite:
fname, _ = QtWidgets.QFileDialog.getOpenFileName(directory=str(self._dir))
if fname:
self.read_file(fname)
def read_file(self, fname: str | Path):
self.set_fname_opts(fname)
with self.fname.open('r') as f:
self.edit_field.setPlainText(f.read())
def set_fname_opts(self, fname: str | Path):
self.fname = Path(fname)
self._dir = self.fname.parent
self.setWindowTitle('Edit ' + str(fname))
@property
def changes_saved(self) -> bool:
if not self.is_modified:
return True
ret = QtWidgets.QMessageBox.question(self, 'Time to think',
'<h4><p>The document was modified.</p>\n'
'<p>Do you want to save changes?</p></h4>',
QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
QtWidgets.QMessageBox.Cancel)
if ret == QtWidgets.QMessageBox.Yes:
self.save_file()
if ret == QtWidgets.QMessageBox.No:
self.is_modified = False
return not self.is_modified
@QtCore.pyqtSlot()
def save_file(self):
outfile, _ = QtWidgets.QFileDialog().getSaveFileName(parent=self, caption='Save file', directory=str(self._dir))
if outfile:
with open(outfile, 'w') as f:
f.write(self.edit_field.toPlainText())
self.set_fname_opts(outfile)
self.is_modified = False
return self.is_modified
@QtCore.pyqtSlot()
def overwrite_file(self):
if self.fname is not None:
with self.fname.open('w') as f:
f.write(self.edit_field.toPlainText())
self.modelsChanged.emit()
self.is_modified = False
def closeEvent(self, evt: QtGui.QCloseEvent):
if not self.changes_saved:
evt.ignore()
else:
super().closeEvent(evt)