run scripts
All checks were successful
Build AppImage / Explore-Gitea-Actions (push) Successful in 1m46s
All checks were successful
Build AppImage / Explore-Gitea-Actions (push) Successful in 1m46s
run scripts Co-authored-by: Dominik Demuth <dominik.demuth@physik.tu-darmstadt.de> Reviewed-on: #291
This commit is contained in:
0
src/gui_qt/editors/__init__.py
Normal file
0
src/gui_qt/editors/__init__.py
Normal file
309
src/gui_qt/editors/codeeditor.py
Normal file
309
src/gui_qt/editors/codeeditor.py
Normal file
@@ -0,0 +1,309 @@
|
||||
# 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.Key_Tab:
|
||||
# use spaces instead of tab
|
||||
self.insertPlainText(' '*4)
|
||||
elif evt.key() == QtCore.Qt.Key.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.GlobalColor.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.GlobalColor.black)
|
||||
painter.drawText(0, int(top), self.current_linenumber.width() - 3, height,
|
||||
QtCore.Qt.AlignmentFlag.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.GlobalColor.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)
|
||||
30
src/gui_qt/editors/script_editor.py
Normal file
30
src/gui_qt/editors/script_editor.py
Normal file
@@ -0,0 +1,30 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from .usermodeleditor import QUsermodelEditor
|
||||
from ..Qt import QtWidgets, QtCore, QtGui
|
||||
|
||||
|
||||
class QEditor(QUsermodelEditor):
|
||||
runSignal = QtCore.pyqtSignal(str)
|
||||
|
||||
def __init__(self, path: str | Path = None, parent=None):
|
||||
super().__init__(path, parent=parent)
|
||||
|
||||
self.add_run_button()
|
||||
|
||||
def add_run_button(self):
|
||||
self.disclaimer = QtWidgets.QLabel("This is work in progress and less than perfect :(")
|
||||
self.disclaimer.setStyleSheet('QLabel {color: rgb(255, 0, 0); font-weight: bold; font-size: 2.5em;};')
|
||||
self.centralwidget.layout().insertWidget(0, self.disclaimer)
|
||||
|
||||
self.run_button = QtWidgets.QPushButton("Run")
|
||||
self.centralwidget.layout().addWidget(self.run_button)
|
||||
|
||||
self.run_button.clicked.connect(self.start_script)
|
||||
|
||||
@QtCore.pyqtSlot()
|
||||
def start_script(self):
|
||||
self.runSignal.emit(self.edit_field.toPlainText())
|
||||
|
||||
139
src/gui_qt/editors/usermodeleditor.py
Normal file
139
src/gui_qt/editors/usermodeleditor.py
Normal file
@@ -0,0 +1,139 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from ..Qt import QtWidgets, QtCore, QtGui
|
||||
from .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.LayoutDirection.LeftToRight,
|
||||
QtCore.Qt.AlignmentFlag.AlignCenter,
|
||||
self.size(),
|
||||
QtWidgets.qApp.desktop().availableGeometry()
|
||||
)
|
||||
)
|
||||
|
||||
def is_modified(self):
|
||||
return self.edit_field.editor.document().isModified()
|
||||
|
||||
def set_modified(self, val: bool):
|
||||
self.edit_field.editor.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)
|
||||
|
||||
if self.fname is not None:
|
||||
with self.fname.open('r') as f:
|
||||
self.edit_field.setPlainText(f.read())
|
||||
|
||||
def set_fname_opts(self, fname: str | Path):
|
||||
fname = Path(fname)
|
||||
if fname.is_file():
|
||||
self.fname = Path(fname)
|
||||
self._dir = self.fname.parent
|
||||
self.setWindowTitle('Edit ' + str(fname))
|
||||
elif fname.is_dir():
|
||||
self._dir = fname
|
||||
|
||||
|
||||
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.set_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.set_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.set_modified(False)
|
||||
|
||||
def closeEvent(self, evt: QtGui.QCloseEvent):
|
||||
if not self.changes_saved():
|
||||
evt.ignore()
|
||||
else:
|
||||
super().closeEvent(evt)
|
||||
Reference in New Issue
Block a user