Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Syntax checker in the model editor. #1875

Merged
merged 6 commits into from
Jul 6, 2021
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 98 additions & 0 deletions src/sas/qtgui/Utilities/CodeEditor.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@

from PyQt5.QtCore import Qt, QRect, QSize
from PyQt5.QtWidgets import QWidget, QPlainTextEdit, QTextEdit
from PyQt5.QtGui import QColor, QPainter, QTextFormat


class QLineNumberArea(QWidget):
def __init__(self, editor):
super().__init__(editor)
self.codeEditor = editor

def sizeHint(self):
return QSize(self.editor.lineNumberAreaWidth(), 0)

def paintEvent(self, event):
self.codeEditor.lineNumberAreaPaintEvent(event)


class QCodeEditor(QPlainTextEdit):
def __init__(self, parent=None):
super().__init__(parent)
self.lineNumberArea = QLineNumberArea(self)
self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
self.updateRequest.connect(self.updateLineNumberArea)
self.cursorPositionChanged.connect(self.highlightCurrentLine)
self.updateLineNumberAreaWidth()

def lineNumberAreaWidth(self):
digits = 1
max_value = max(1, self.blockCount())
while max_value >= 10:
max_value /= 10
digits += 1
# line number display width padded with extra pixels.
# Chosen to "look nice", hence magic numbers
space = 3 + self.fontMetrics().width('9') * digits
krzywon marked this conversation as resolved.
Show resolved Hide resolved
return space

def updateLineNumberAreaWidth(self):
self.setViewportMargins(self.lineNumberAreaWidth(), 0, 0, 0)

def updateLineNumberArea(self, rect, dy):
if dy:
self.lineNumberArea.scroll(0, dy)
else:
self.lineNumberArea.update(0, rect.y(), self.lineNumberArea.width(), rect.height())
if rect.contains(self.viewport().rect()):
self.updateLineNumberAreaWidth()

def resizeEvent(self, event):
super().resizeEvent(event)
cr = self.contentsRect()
self.lineNumberArea.setGeometry(QRect(cr.left(), cr.top(), self.lineNumberAreaWidth(), cr.height()))

def highlightCurrentLine(self):
extraSelections = []
if not self.isReadOnly():
selection = QTextEdit.ExtraSelection()
lineColor = QColor(Qt.yellow).lighter(160)
selection.format.setBackground(lineColor)
selection.format.setProperty(QTextFormat.FullWidthSelection, True)
selection.cursor = self.textCursor()
selection.cursor.clearSelection()
extraSelections.append(selection)
self.setExtraSelections(extraSelections)

def lineNumberAreaPaintEvent(self, event):
painter = QPainter(self.lineNumberArea)

painter.fillRect(event.rect(), Qt.lightGray)

block = self.firstVisibleBlock()
blockNumber = 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 <= event.rect().bottom()):
if block.isVisible() and (bottom >= event.rect().top()):
number = str(blockNumber + 1)
painter.setPen(Qt.black)
painter.drawText(0, top, self.lineNumberArea.width(), height, Qt.AlignRight, number)

block = block.next()
top = bottom
bottom = top + self.blockBoundingRect(block).height()
blockNumber += 1


if __name__ == '__main__':
import sys
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)
codeEditor = QCodeEditor()
codeEditor.show()
sys.exit(app.exec_())
48 changes: 45 additions & 3 deletions src/sas/qtgui/Utilities/TabbedModelEditor.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
# global
import sys
import os
import ast
import datetime
import logging
import traceback
Expand Down Expand Up @@ -119,7 +120,6 @@ def onLoad(self):
if saveCancelled:
return
self.is_modified = False
self.buttonBox.button(QtWidgets.QDialogButtonBox.Apply).setEnabled(False)

plugin_location = models.find_plugins_dir()
filename = QtWidgets.QFileDialog.getOpenFileName(
Expand All @@ -145,16 +145,22 @@ def loadFile(self, filename):
Performs the load operation and updates the view
"""
self.editor_widget.blockSignals(True)
plugin_text = ""
with open(filename, 'r', encoding="utf-8") as plugin:
self.editor_widget.txtEditor.setPlainText(plugin.read())
plugin_text = plugin.read()
self.editor_widget.txtEditor.setPlainText(plugin_text)
self.editor_widget.setEnabled(True)
self.editor_widget.blockSignals(False)
self.buttonBox.button(QtWidgets.QDialogButtonBox.Apply).setEnabled(True)
self.filename = filename
display_name, _ = os.path.splitext(os.path.basename(filename))
self.setWindowTitle(self.window_title + " - " + display_name)
# Name the tab with .py filename
display_name = os.path.basename(filename)
self.tabWidget.setTabText(0, display_name)
# Check the validity of loaded model
if not self.checkModel(plugin_text):
return

# See if there is filename.c present
c_path = self.filename.replace(".py", ".c")
Expand Down Expand Up @@ -274,7 +280,6 @@ def updateFromPlugin(self):

# disable "Apply"
self.buttonBox.button(QtWidgets.QDialogButtonBox.Apply).setEnabled(False)
# test the model

# Run the model test in sasmodels
if not self.isModelCorrect(full_path):
Expand All @@ -299,6 +304,36 @@ def updateFromPlugin(self):
self.parent.communicate.statusBarUpdateSignal.emit(msg)
logging.info(msg)

def checkModel(self, model_str):
"""
Run the ast check
and return True if the model is good.
False otherwise.
"""
successfulCheck = True
try:
ast.parse(model_str)

except SyntaxError as ex:
msg = "Error building model: " + str(ex)
logging.error(msg)
# print three last lines of the stack trace
# this will point out the exact line failing
last_lines = traceback.format_exc().split('\n')[-4:]
rozyczko marked this conversation as resolved.
Show resolved Hide resolved
traceback_to_show = '\n'.join(last_lines)
logging.error(traceback_to_show)

# Set the status bar message
self.parent.communicate.statusBarUpdateSignal.emit("Model check failed")

# Put a thick, red border around the mini-editor
self.tabWidget.currentWidget().txtEditor.setStyleSheet("border: 5px solid red")
# last_lines = traceback.format_exc().split('\n')[-4:]
traceback_to_show = '\n'.join(last_lines)
self.tabWidget.currentWidget().txtEditor.setToolTip(traceback_to_show)
successfulCheck = False
return successfulCheck

def isModelCorrect(self, full_path):
"""
Run the sasmodels method for model check
Expand Down Expand Up @@ -347,6 +382,13 @@ def updateFromEditor(self):
assert(filename != "")
# Retrieve model string
model_str = self.getModel()['text']
if self.tabWidget.currentWidget().is_python:
if not self.checkModel(model_str):
return

# change the frame colours back
self.tabWidget.currentWidget().txtEditor.setStyleSheet("")
self.tabWidget.currentWidget().txtEditor.setToolTip("")
# Save the file
self.writeFile(filename, model_str)
# Update the tab title
Expand Down
17 changes: 8 additions & 9 deletions src/sas/qtgui/Utilities/UI/ModelEditor.ui
Original file line number Diff line number Diff line change
Expand Up @@ -21,21 +21,20 @@
</property>
<layout class="QGridLayout" name="gridLayout_16">
<item row="0" column="0">
<widget class="QTextEdit" name="txtEditor">
<property name="html">
<string>&lt;!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.0//EN&quot; &quot;http://www.w3.org/TR/REC-html40/strict.dtd&quot;&gt;
&lt;html&gt;&lt;head&gt;&lt;meta name=&quot;qrichtext&quot; content=&quot;1&quot; /&gt;&lt;style type=&quot;text/css&quot;&gt;
p, li { white-space: pre-wrap; }
&lt;/style&gt;&lt;/head&gt;&lt;body style=&quot; font-family:'MS Shell Dlg 2'; font-size:7.8pt; font-weight:400; font-style:normal;&quot;&gt;
&lt;p style=&quot;-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;&quot;&gt;&lt;br /&gt;&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;</string>
</property>
</widget>
<widget class="QCodeEditor" name="txtEditor" native="true"/>
</item>
</layout>
</widget>
</item>
</layout>
</widget>
<customwidgets>
<customwidget>
<class>QCodeEditor</class>
<extends>QWidget</extends>
<header location="global">sas.qtgui.Utilities.CodeEditor.h</header>
</customwidget>
</customwidgets>
<resources/>
<connections/>
</ui>