def openFile(self): files = QFileDialog.getOpenFileNames(self, "Open", FormWidget.path) if files[0]: FormWidget.filepath = files[0] FormWidget.path = os.path.dirname(files[0][0]) self.form_widget.tree.setRootIndex( self.form_widget.model.index(FormWidget.path)) for i in files[0]: n = os.path.basename(i) for j in range(self.form_widget.tab.count()): if n == self.form_widget.tab.tabText(j): self.form_widget.tab.removeTab(j) break newEdit = QsciScintilla() newEdit.setFont(QFont('Times', 10)) newEdit.setMarginType(0, QsciScintilla.NumberMargin) newEdit.setMarginWidth(0, '00000000') self.form_widget.checkExtensionToHighlight(i, newEdit) try: newEdit.setText(open(i).read()) newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) newEdit.setAutoCompletionCaseSensitivity(False) newEdit.setAutoCompletionReplaceWord(False) newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument) newEdit.setAutoCompletionThreshold(1) self.form_widget.tab.insertTab(0, newEdit, QIcon('icon.png'), n) self.form_widget.tab.setCurrentIndex(0) except: QMessageBox.warning(self, 'Warning', 'Unsupported file type', QMessageBox.Ok)
def findPath(self, index): path = self.sender().model().filePath(index) if os.path.isfile(path): global name FormWidget.filepath.append(path) name = os.path.basename(path) for i in range(self.tab.count()): if name == self.tab.tabText(i): self.tab.removeTab(i) break newEdit = QsciScintilla() self.checkExtensionToHighlight(path, newEdit) newEdit.setFont(QFont('Times', 10)) newEdit.setMarginType(0, QsciScintilla.NumberMargin) newEdit.setMarginWidth(0, '00000000') try: newEdit.setText(open(path).read()) newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) newEdit.setAutoCompletionCaseSensitivity(False) newEdit.setAutoCompletionReplaceWord(False) newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument) newEdit.setAutoCompletionThreshold(1) self.tab.insertTab(0, newEdit, QIcon('icon.png'), os.path.basename(path)) self.tab.setCurrentIndex(0) except: QMessageBox.warning(self, "Warning", "Unsupported file type", QMessageBox.Ok)
def agregar_tab(self): text, okPressed = QInputDialog.getText(self.centralwidget, "Nuevo archivo", "Nombre:", QLineEdit.Normal, "") if okPressed and text != '': tab = QtWidgets.QWidget() area = QsciScintilla(tab) area.setGeometry(QtCore.QRect(10, 10, 631, 371)) area.setObjectName("plainTextEdit") area.setFont(self.__myFont) area.setMarginType(0, QsciScintilla.NumberMargin) area.setMarginWidth(0, "00000") area.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) area.markerDefine(QsciScintilla.RightArrow, 0) area.setMarginSensitivity(0, True) area.setWrapMode(QsciScintilla.WrapWord) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.setWrapIndentMode(QsciScintilla.WrapIndentIndented) area.setEolMode(QsciScintilla.EolWindows) area.setEolVisibility(False) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.marginClicked.connect(self.on_margin_clicked) __lexer = QsciLexerCPP(area) area.setLexer(__lexer) self.editor.addTab(tab, "") area.setObjectName("area") self.editor.addTab(tab, text + ".mc")
def newFile(self): text, ok = QInputDialog.getText(self, 'New', 'Enter File name:') if ok: newEdit = QsciScintilla() newEdit.setMarginType(0, QsciScintilla.NumberMargin) newEdit.setMarginWidth(0, '00000000') newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) newEdit.setAutoCompletionCaseSensitivity(False) newEdit.setAutoCompletionReplaceWord(False) newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument) newEdit.setAutoCompletionThreshold(1) self.form_widget.checkExtensionToHighlight(text, newEdit) newEdit.setFont(QFont('Times', 10)) self.form_widget.tab.insertTab(0, newEdit, QIcon('icon.png'), text) self.form_widget.tab.setCurrentIndex(0)
def createTabWidget(self, code, textLexer: QsciLexer): tabWidget = QWidget() # 垂直布局 layout = WidgetUtil.createVBoxLayout() # 设置布局方式 tabWidget.setLayout(layout) editor = QsciScintilla(tabWidget) editor.setLexer(textLexer) # 行号提示 editor.setMarginType(0, QsciScintilla.NumberMargin) # 设置编号为1的页边显示行号。 editor.setMarginLineNumbers(0, True) # 对该页边启用行号 editor.setMarginWidth(0, 30) # 设置页边宽度 editor.setText(code) editor.SendScintilla(QsciScintilla.SCI_SETCODEPAGE, QsciScintilla.SC_CP_UTF8) # 设置编码为UTF-8 editor.setReadOnly(True) # 添加控件到布局中 layout.addWidget(editor) return tabWidget
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, code): super(QDialog, self).__init__() self.codeEdit = QsciScintilla() self.codeEdit.setText(code) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) verticalLayout = QVBoxLayout() verticalLayout.addWidget(self.codeEdit) self.setLayout(verticalLayout) self.codeEdit.textChanged.connect(self.changeCode) def changeCode(self): self.codeChanged.emit(self.codeEdit.text())
def getEditor(): editor = QsciScintilla() lexer = QsciLexerYAML() editor.setLexer(lexer) font = getFont() # lexer.setDefaultFont(font) lexer.setFont(font) settings = QSettings() lexer.readSettings(settings) print(settings.allKeys()) lexer.setDefaultPaper(QColor('#252721')) for i in range(10): lexer.setPaper(QColor('#252721'), i) lexer.setColor(QColor('#f8f8f2'), i) print(lexer.color(i).name()) lexer.setColor(QColor('#e6db74'), 0) # foreground (yellow) lexer.setColor(QColor('#75715e'), 1) # comment (gray) lexer.setColor(QColor('#f92672'), 2) # identifier (red) lexer.setColor(QColor('#ae81ff'), 3) # keyword (purple) lexer.setColor(QColor('#ae81ff'), 4) # number (purple) lexer.setColor(QColor('#ae81ff'), 5) # reference (purple) lexer.setColor(QColor('#ae81ff'), 6) # documentdelimiter (purple) lexer.setColor(QColor('#ae81ff'), 7) # text block marker (purple) lexer.setColor(QColor('#f92672'), 8) # syntax error marker (red) lexer.setColor(QColor('#f92672'), 9) # operator (red) # editor.setFont(font) # editor.setMarginsFont(font) editor.setCaretForegroundColor(QColor('#f8f8f0')) editor.setMarginWidth(0, getMarginWidth(font)) editor.setMarginWidth(1, 0) editor.setMarginLineNumbers(0, True) editor.setMarginsBackgroundColor(QColor('#252721')) editor.setMarginsForegroundColor(QColor('#f8f8f2')) editor.setExtraAscent(3) editor.setTabWidth(4) editor.setMinimumSize(600, 450) return editor
def abrir_archivo(self): try: dialog = QtWidgets.QFileDialog().getOpenFileName( None, ' Open document', r"C:\Users\\", "All Files (*)") ruta = dialog[0] trozos = ruta.split("/") name = trozos[len(trozos) - 1] self.pestañas[name] = ruta file = open(ruta, 'r') codigo = file.read() tab = QtWidgets.QWidget() area = QsciScintilla(tab) area.setGeometry(QtCore.QRect(10, 10, 631, 371)) area.setObjectName("plainTextEdit") area.setFont(self.__myFont) area.setMarginType(0, QsciScintilla.NumberMargin) area.setMarginWidth(0, "00000") area.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) area.markerDefine(QsciScintilla.RightArrow, 0) area.setMarginSensitivity(0, True) area.setWrapMode(QsciScintilla.WrapWord) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.setWrapIndentMode(QsciScintilla.WrapIndentIndented) area.setEolMode(QsciScintilla.EolWindows) area.setEolVisibility(False) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.marginClicked.connect(self.on_margin_clicked) __lexer = QsciLexerCPP(area) area.setLexer(__lexer) self.editor.addTab(tab, "") area.setText(codigo) area.setObjectName("area") self.editor.addTab(tab, name) file.close() except: em = QtWidgets.QErrorMessage(self.mw) em.showMessage("Error al abrir {0}".format(name))
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # Window setup # -------------- # 1. Define the geometry of the main window self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # QScintilla editor setup # ------------------------ # ! Make instance of QsciScintilla class! self.__editor = QsciScintilla() self.__editor.setText("Hello\n") self.__editor.append("world \n") self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # Will be overridden by lexer! #simple editor options self.__editor.setEolVisibility(False) #sets the end of each line with an EOL character self.__editor.setIndentationsUseTabs(False) #determines whether indent uses tabs or whitespace char. self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1fff0000")) self.__editor.setCaretWidth(5) #Margin SetUp. self.__editor.setMarginType(3, self.__editor.NumberMargin) self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # self.__editor.setMarginType(2, QsciScintilla.TextMargin) # Symbol Margin sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) sym_4 = self.__editor.Circle self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.markerDefine(sym_4, 4) self.__editor.setMarginType(3, self.__editor.SymbolMargin) # self.__editor.setMarginType(2, QsciScintilla.SymbolMarginDefaultBackgroundColor) # self.__editor.setMarginType(3, QsciScintilla.SymbolMarginDefaultForegroundColor) self.__editor.setMarginWidth(1, '00000') self.__editor.setMarginMarkerMask(1, 0b1111) self.__editor.setMarginMarkerMask(2, 0b1111) self.__editor.markerAdd(3, 2) # Display a few symbols, and keep their handles stored self.__editor.markerAdd(0, 0) # Green dot on line 0+1 self.__editor.markerAdd(4, 0) # Green dot on line 4+1 self.__editor.markerAdd(5, 0) # Green dot on line 5+1 self.__editor.markerAdd(8, 3) # Red arrow on line 8+1 self.__editor.markerAdd(9, 2) # Red dot on line 9+1 self.__editor.setFolding(self.__editor.BoxedFoldStyle, 4) self.__editor.SendScintilla(self.__editor.SCI_SETMULTIPLESELECTION, True) self.__editor.SendScintilla(self.__editor.SCI_SETMULTIPASTE, 1) self.__editor.SendScintilla(self.__editor.SCI_SETADDITIONALSELECTIONTYPING, True) self.__editor.SendScintilla(self.__editor.SCI_SETINDENTATIONGUIDES, self.__editor.SC_IV_REAL); self.__editor.SendScintilla(self.__editor.SCI_SETTABWIDTH, 4) # self.__editor.setMarginsBackgroundColor(QColor("#ff0000ff")) self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # available wrap modes: # QsciScintilla.WrapNone, WrapWord, WrapCharacter, WrapWhitespace self.__editor.setWrapVisualFlags( QsciScintilla.WrapFlagByText, startFlag=QsciScintilla.WrapFlagByText, indent=4) # setWrapVisualFlags(endFlag, startFlag, indent) # see: readMe self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) self.__editor.textChanged.connect(self.text_changed) #signal typing # ! Add editor to layout ! self.__lyt.addWidget(self.__editor) self.show() '''''' def __btn_action(self): self.__editor.append('Voila You just clicked the QSci button! \n') print("Hello World!") def text_changed(self): print({self.__editor.text()}) ''''''
class MainWindow(QMainWindow): def __init__(self): super().__init__() self.setWindowTitle("Untitled") icon = os.path.join(BASE_DIR, 'ide/Icon.ico') self.setWindowIcon(QIcon(icon)) self.saveLoad = SaveLoad() self.fileName = None self.setupUI() def setupUI(self): centralWidget = QWidget(self) layout = QHBoxLayout(centralWidget) self.fileSysView = QTreeView(centralWidget) self.setupFileSystemViewer() self.editor = QsciScintilla(centralWidget) self.setupEditor() layout.addWidget(self.fileSysView, 1) layout.addWidget(self.editor, 3) self.setCentralWidget(centralWidget) self.setMinimumSize(700, 500) self.defaultMenuBar = QMenuBar(self) self.setupMenus() self.setMenuBar(self.defaultMenuBar) self.show() def setupEditor(self): self.editor.setFont(QFont("Times New Roman", 12)) self.editor.setMargins(2) self.editor.setMarginType(0, QsciScintilla.NumberMargin) self.editor.setMarginType(1, QsciScintilla.SymbolMargin) self.editor.setMarginWidth(0, "000") self.editor.setMarginWidth(1, "00") self.editor.markerDefine(QsciScintilla.RightTriangle, 1) if system() == "Windows": self.editor.setEolMode(QsciScintilla.EolWindows) elif system() == "Linux": self.editor.setEolMode(QsciScintilla.EolUnix) elif system() == "Mac": self.editor.setEolMode(QsciScintilla.EolMac) else: print("Using Windows EOL") self.editor.setEolMode(QsciScintilla.EolWindows) self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.editor.setIndentationsUseTabs(True) self.editor.setTabWidth(4) self.editor.setIndentationGuides(True) self.editor.setTabIndents(True) self.editor.setAutoIndent(True) self.editor.setCaretForegroundColor(QColor("#ff11214b")) self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.editor.setUtf8(True) self.editor.setMarginSensitivity(1, True) self.editor.marginClicked.connect(self.margin_clicked) self.editor.marginRightClicked.connect(self.margin_right_clicked) self.lexer = QsciLexerPython() self.lexer.setFont(QFont("Times New Roman", 12)) self.editor.setLexer(self.lexer) self.editor.textChanged.connect(self.fileChanged) def setupFileSystemViewer(self): model = QFileSystemModel() model.setRootPath("/") self.fileSysView.setModel(model) self.fileSysView.hideColumn(1) self.fileSysView.hideColumn(2) self.fileSysView.hideColumn(3) self.fileSysView.doubleClicked.connect(self.openFile) def setupMenus(self): fileMenu = QMenu(self.defaultMenuBar) fileMenu.setTitle("File") editMenu = QMenu(self.defaultMenuBar) editMenu.setTitle("Edit") viewMenu = QMenu(self.defaultMenuBar) viewMenu.setTitle("View") runMenu = QMenu(self.defaultMenuBar) runMenu.setTitle("Run") settingsMenu = QMenu(self.defaultMenuBar) settingsMenu.setTitle("Settings") self.actionNew = QAction(self) self.actionNew.setText("New") self.actionNew.setShortcut("Ctrl+N") self.actionOpen = QAction(self) self.actionOpen.setText("Open") self.actionOpen.setShortcut("Ctrl+O") self.actionSave = QAction(self) self.actionSave.setText("Save") self.actionSave.setShortcut("Ctrl+S") self.actionSaveAs = QAction(self) self.actionSaveAs.setText("Save As") self.actionSaveAs.setShortcut("Ctrl+Shift+S") self.actionExit = QAction(self) self.actionExit.setText("Exit") self.actionExit.setShortcut("Alt+X") self.actionUndo = QAction(self) self.actionUndo.setText("Undo") self.actionUndo.setShortcut("Ctrl+Z") self.actionRedo = QAction(self) self.actionRedo.setText("Redo") self.actionRedo.setShortcut("Ctrl+Shift+Z") self.actionSelectAll = QAction(self) self.actionSelectAll.setText("Select all") self.actionSelectAll.setShortcut("Ctrl+A") self.actionCut = QAction(self) self.actionCut.setText("Cut") self.actionCut.setShortcut("Ctrl+X") self.actionCopy = QAction(self) self.actionCopy.setText("Copy") self.actionCopy.setShortcut("Ctrl+C") self.actionPaste = QAction(self) self.actionPaste.setText("Paste") self.actionPaste.setShortcut("Ctrl+V") self.actionFind = QAction(self) self.actionFind.setText("Find") self.actionFind.setShortcut("Ctrl+F") self.actionReplace = QAction(self) self.actionReplace.setText("Replace") self.actionReplace.setShortcut("Ctrl+H") self.actionRun = QAction(self) self.actionRun.setText("Run") self.actionRun.setShortcut("F5") self.actionRunCustom = QAction(self) self.actionRunCustom.setText("Run Customized") self.actionRunCustom.setShortcut("Shift+F5") self.actionShell = QAction(self) self.actionShell.setText("Python shell") self.actionShell.setShortcut("Alt+S") self.actionFont = QAction(self) self.actionFont.setText("Font") self.actionEncoding = QAction(self) self.actionEncoding.setText("Encoding") fileMenu.addAction(self.actionNew) fileMenu.addAction(self.actionOpen) fileMenu.addAction(self.actionSave) fileMenu.addAction(self.actionSaveAs) fileMenu.addSeparator() fileMenu.addAction(self.actionExit) editMenu.addAction(self.actionUndo) editMenu.addAction(self.actionRedo) editMenu.addSeparator() editMenu.addAction(self.actionSelectAll) editMenu.addSeparator() editMenu.addAction(self.actionCut) editMenu.addAction(self.actionCopy) editMenu.addAction(self.actionPaste) viewMenu.addAction(self.actionFind) viewMenu.addAction(self.actionReplace) runMenu.addAction(self.actionRun) runMenu.addAction(self.actionRunCustom) runMenu.addAction(self.actionShell) settingsMenu.addAction(self.actionFont) settingsMenu.addAction(self.actionEncoding) self.defaultMenuBar.addAction(fileMenu.menuAction()) self.defaultMenuBar.addAction(editMenu.menuAction()) self.defaultMenuBar.addAction(viewMenu.menuAction()) self.defaultMenuBar.addAction(runMenu.menuAction()) self.defaultMenuBar.addAction(settingsMenu.menuAction()) self.actionNew.triggered.connect(self.new) self.actionOpen.triggered.connect(self.open) self.actionSave.triggered.connect(self.save) self.actionSaveAs.triggered.connect(self.saveAs) self.actionExit.triggered.connect(self.close) self.actionUndo.triggered.connect(self.editor.undo) self.actionRedo.triggered.connect(self.editor.redo) self.actionSelectAll.triggered.connect( lambda: self.editor.selectAll(True)) self.actionCut.triggered.connect(self.editor.cut) self.actionCopy.triggered.connect(self.editor.copy) self.actionPaste.triggered.connect(self.editor.paste) self.actionFind.triggered.connect(self.find) self.actionReplace.triggered.connect(self.replace) self.actionRun.triggered.connect(self.run) self.actionRunCustom.triggered.connect(self.runCustom) self.actionShell.triggered.connect(self.shell) self.actionFont.triggered.connect(self.Font) def margin_clicked(self, margin_nr, line_nr, state): self.editor.markerAdd(line_nr, margin_nr) def margin_right_clicked(self, margin_nr, line_nr, state): self.editor.markerDelete(line_nr, margin_nr) def new(self): if self.windowTitle().endswith("*"): if (Dialogs().Question( self, "Do you want to save your file?") == "accept"): if self.filename is None: self.saveAs() else: self.save() self.editor.setText("") self.setWindowTitle("Untitled") def open(self): if self.windowTitle().endswith("*"): if (Dialogs().Question( self, "Do you want to save your file?") == "accept"): if self.filename is None: self.saveAs() else: self.save() filename = self.saveLoad.OpenDialog() data = Open(filename) if data is not None: self.editor.setText(data) self.setWindowTitle(filename) self.filename = filename def save(self): if self.filename is None: self.saveAs() else: returnval = Save(self.editor.text(), self.filename) if (returnval): Dialogs().Message(self, "File saved successfully") self.setWindowTitle(self.filename) else: Dialogs().Error(self, "File could not be saved") def saveAs(self): self.filename = self.saveLoad.SaveDialog() returnval = Save(self.editor.text(), self.filename) if (returnval): Dialogs().Message(self, "File saved successfully") self.setWindowTitle(self.filename) else: Dialogs().Error(self, "File could not be saved") def run(self): if self.filename is None: self.saveAs() Runfile(self.filename) def runCustom(self): if self.filename is None: self.saveAs() if self.filename != "": print(len(self.filename)) option, ok = QInputDialog().getText( self, "Customized run", "Enter parameters for sys.argv", QLineEdit.Normal, " ") if ok: Runfile(self.filename, option) def shell(self): Shell() def Font(self): font, ok = QFontDialog.getFont() if ok: self.editor.setFont(font) self.lexer.setFont(font) self.editor.setLexer(self.lexer) def openFile(self, signal): fileName = self.fileSysView.model().filePath(signal) if fileName.endswith("py") or fileName.endswith("pyw"): if self.windowTitle().endswith("*"): if Dialogs().Question( self, "Do you want to save your file?") == "accept": if self.filename is None: self.saveAs() else: self.save() data = Open(fileName) if data is not None: self.editor.setText(data) self.setWindowTitle(fileName) self.filename = fileName def fileChanged(self): title = self.windowTitle() if not (title.endswith("*")): self.setWindowTitle(title + " *") def replace(self): replaceObj = replaceDialog(self, self.editor) def find(self): findObj = findDialog(self, self.editor)
class BrowserWindow(QWidget): launcherWindow = None logoPixmap = None def __init__(self, launcherWindow, app): super().__init__() self.app = app self.launcherWindow = launcherWindow self.fontSize = 14 self.fontSizeLarge = 24 self.fontSizeSmall = 10 self.setCursor(AppData.cursors['arrow']) self.initUI() def multiple_replace(self, string, rep_dict): pattern = re.compile("|".join([re.escape(k) for k in rep_dict.keys()]), re.M) return pattern.sub(lambda x: rep_dict[x.group(0)], string) def styleEsc(self, string): return self.multiple_replace(string, { '{': '{{', '}': '}}', '@<': '{', '>@': '}' }) def initUI(self): ## pal = QPalette(); ## pal.setColor(QPalette.Background, Qt.black); ## self.setPalette(pal); self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum) self.styleTemplate = self.styleEsc(""" QWidget{ background-color: black; border-color: red; border-style: solid; border-width: 1px; border-radius: 0px; font: bold @<fontSize>@px; color: red; padding: 0px; font-family: "Candara"; font-size: @<fontSize:d>@px; } QLabel{ font-size: @<fontSizeLarge:d>@px; border-width: 0px; } QTreeView::item:hover { background: black; border: 1px solid red; } QTreeView::item:selected { border: 1px solid red; color: red; } QTreeView::item:selected:active{ background: black; border: 1px solid red; } QTreeView::item:selected:!active { border: 1px solid red; color: red; } QTreeView::branch:has-siblings:!adjoins-item { border-image: url(Gui/stylesheet-vline.png) 0; } QTreeView::branch:has-siblings:adjoins-item { border-image: url(Gui/stylesheet-branch-more.png) 0; } QTreeView::branch:!has-children:!has-siblings:adjoins-item { border-image: url(Gui/stylesheet-branch-end.png) 0; } QTreeView::branch:has-children:!has-siblings:closed, QTreeView::branch:closed:has-children:has-siblings { border-image: none; image: url(Gui/stylesheet-branch-closed.png); } QTreeView::branch:open:has-children:!has-siblings, QTreeView::branch:open:has-children:has-siblings { border-image: none; image: url(Gui/stylesheet-branch-open.png); } QScrollBar:vertical { border: 2px solid red; background: black; width: 40px; margin: 22px 0 22px 0; } QScrollBar::handle:vertical { background: red; min-height: 20px; } QScrollBar::add-line:vertical { border: 2px red; background: black; height: 20px; subcontrol-position: bottom; subcontrol-origin: margin; } QScrollBar::sub-line:vertical { border: 2px red; background: black; height: 20px; subcontrol-position: top; subcontrol-origin: margin; } QScrollBar::up-arrow:vertical, QScrollBar::down-arrow:vertical { border: 2px solid black; width: 3px; height: 3px; background: red; } QScrollBar::add-page:vertical, QScrollBar::sub-page:vertical { background: none; } """) self.setStyleSheet( self.styleTemplate.format(fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge))) #gridWidget = QWidget(self) #self.gridWidget = gridWidget grid = QGridLayout() #treeMooker = QWidget(self) #treeMooker.setStyleSheet("background-color: transparent;") #treeMooker.setAttribute(Qt.WA_TransparentForMouseEvents) #treeMooker.installEventFilter(self) #treeMookerGrid = QGridLayout() #stack = QStackedLayout() #stack.setStackingMode(QStackedLayout.StackAll) logo = QLabel(self) self.logoPixmap = QPixmap("./Project/Media/Gears.png") logo.setPixmap(self.logoPixmap) logo.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) grid.addWidget(logo, 2, 3, 1, 1) self.titleTemplate = self.styleEsc(''' <p align="left"><strong> <span style='font-size:@<fontSizeLarge>@pt; font-weight:600; color:#ff0000;'>GPU Eye And Retina Stimulation </span></strong><span style='font-size:10pt; font-weight:600; color:#aa0000;'>beta test version 0.4</span></p> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>László Szécsi</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Budapest University of Technology and Economics</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Péter Hantz</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>University of Pécs, Medical School</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Ágota Kacsó</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Budapest University of Technology and Economics</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Günther Zeck</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>Natural and Medical Sciences Institute Reutlingen</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>http://www.gears.vision</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>[email protected]</span></p> </td> </tr> </tbody> </table> ''') self.titleLabel = QLabel( self.titleTemplate.format(fontSize=self.fontSize, fontSizeLarge=self.fontSizeLarge, fontSizeSmall=self.fontSizeSmall)) self.titleLabel.setTextFormat(Qt.RichText) self.titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) grid.addWidget(self.titleLabel, 1, 3, 1, 1) self.instructionsTemplate = self.styleEsc(''' <p align="left"><strong> <table border="0" cellpadding="0" cellspacing="0"> <tbody> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Reset tree</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>press space</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Navigate</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>press key for first character</span></p> </td> </tr> <tr> <td > <p align="left"> <span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Change font size</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>ctrl+mouse wheel</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>Edit or configure</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'>right click tree item</span></p> </td> </tr> <tr> <td > <p align="left"><span style='font-size:@<fontSize>@pt; font-weight:600; color:#ff0000;'>/</span></p> </td> <td > <p><span style='font-size:@<fontSizeSmall>@pt; font-weight:600; color:#aa0000;'> @<emptyFolderOp>@ empty folders</span></p> </td> </tr> </tbody> </table> ''') self.instructionsLabel = QLabel( self.instructionsTemplate.format(fontSize=self.fontSize, fontSizeLarge=self.fontSizeLarge, fontSizeSmall=self.fontSizeSmall, emptyFolderOp='show')) self.instructionsLabel.setStyleSheet(''' QLabel{ border-width: 1px; } ''') self.instructionsLabel.setTextFormat(Qt.RichText) self.instructionsLabel.setAlignment(Qt.AlignHCenter) grid.addWidget(self.instructionsLabel, 3, 1, 1, 1) specs = QLabel(gears.getSpecs()) #self.titleLabel.setTextFormat( Qt.RichText ) self.titleLabel.setAlignment(Qt.AlignHCenter | Qt.AlignVCenter) specs.setFocusPolicy(Qt.NoFocus) #specsButton.clicked.connect(self.onSpecs) grid.addWidget(specs, 4, 1, 1, 1) quitButton = QPushButton('Quit') quitButton.setFocusPolicy(Qt.NoFocus) quitButton.clicked.connect(self.onQuit) grid.addWidget(quitButton, 4, 3, 1, 1) #settingsButton = QPushButton('Measurement hardware') #settingsButton.setFocusPolicy(Qt.NoFocus) #settingsButton.clicked.connect(self.onSet) #grid.addWidget(settingsButton, 3, 3, 1, 1) tree = BrowserTree(self.launcherWindow, self) tree.setAttribute(Qt.WA_TransparentForMouseEvents, on=False) self.tree = tree tree.setFocusPolicy(Qt.NoFocus) tree.setHeaderHidden(True) tree.setStyleSheet("background-color: black;") item0 = QTreeWidgetItem(tree) item0.setText(0, 'Sequences') itemMap = dict() itemMap["./Project/Sequences"] = item0 rootPath = "./Project/Sequences" emptyDirs = find_empty_dirs(rootPath) for (path, dirs, files) in os.walk(rootPath): for subdir in dirs: if subdir != "__pycache__": fullPath = os.path.join(path, subdir) #if(rootPath == path): # item0 = QTreeWidgetItem(tree) # itemMap[fullPath] = item0 # item0.setText(0, subdir) #else: item1 = QTreeWidgetItem() itemMap[fullPath] = item1 item1.setText(0, subdir) itemMap[path].addChild(item1) if fullPath in emptyDirs: item1.setText( 1, "gears_folder_not_holding_any_sequence_scripts") item1.setHidden(True) for item in files: if item.endswith('.pyx'): #if(rootPath == path): # item0 = QTreeWidgetItem(tree) # itemMap[os.path.join(path, item)] = item0 # item0.setText(0, item) #else: item1 = QTreeWidgetItem() itemMap[os.path.join(path, item)] = item1 item1.setText(0, item) item1.setText(1, "tags spot spatial temporal") itemMap[path].addChild(item1) item0.setExpanded(True) grid.addWidget(tree, 1, 1, 4, 3, Qt.AlignLeft | Qt.AlignTop) #qbtn = QPushButton('Quit', self) #qbtn.clicked.connect(QCoreApplication.instance().quit) #qbtn.resize(qbtn.sizeHint()) #grid.addWidget(qbtn, 8, 9) #treeMooker.setLayout(treeMookerGrid) #gridWidget.setLayout(grid) #stack.addWidget(treeMooker) #stack.addWidget(gridWidget) self.setLayout(grid) self.setWindowTitle('O\u0398\u03a6O') # self.setWindowIcon(QIcon('web.png')) self.showFullScreen() self.setFixedSize(self.size()) self.tree.setCurrentIndex(self.tree.model().index(0, 0)) def keyPressEvent(self, e): if e.key() == Qt.Key_Escape or e.text() == 'q': box = QMessageBox(self) QGuiApplication.setOverrideCursor(AppData.cursors['arrow']) box.setText('Are you sure you want to quit?') box.setWindowTitle('Please confirm!') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.No) if box.exec() == QMessageBox.Yes: self.close() QGuiApplication.restoreOverrideCursor() elif e.key() == Qt.Key_Space or e.key() == Qt.Key_Backspace: self.tree.setCurrentItem(self.tree.topLevelItem(0)) self.tree.collapseAll() self.tree.topLevelItem(0).setExpanded(True) elif e.key() == Qt.Key_Down: ni = self.tree.itemBelow(self.tree.currentItem()) if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Up: ni = self.tree.itemAbove(self.tree.currentItem()) if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Left: ni = self.tree.currentItem().parent() if (ni != None): self.tree.setCurrentItem(ni) elif e.key() == Qt.Key_Right or e.key() == Qt.Key_Return or e.key( ) == Qt.Key_Enter: ni = self.tree.currentItem().child(0) if (ni != None): self.tree.setCurrentItem(ni) else: self.tree.open(self.tree.currentItem(), False) elif e.key() == Qt.Key_Slash: self.tree.hideEmptyFolders(not self.tree.isHidingEmptyFolders) self.instructionsLabel.setText( self.instructionsTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall), emptyFolderOp=('show' if self.tree.isHidingEmptyFolders else 'hide'))) #elif e.key()==Qt.Key_0 or e.key()==Qt.Key_1 or e.key()==Qt.Key_2 or e.key()==Qt.Key_3 or e.key()==Qt.Key_4 or e.key()==Qt.Key_5 or e.key()==Qt.Key_6 or e.key()==Qt.Key_7 or e.key()==Qt.Key_8 or e.key()==Qt.Key_9 : else: self.tree.clearSelection() self.tree.keyboardSearch(e.text()) sel = self.tree.selectedItems() if len(sel) > 0: self.tree.onClick(sel[0], 0) def onSpecs(self): box = QMessageBox(self) horizontalSpacer = QSpacerItem(1000, 0, QSizePolicy.Minimum, QSizePolicy.Expanding) box.setText(gears.getSpecs()) box.setWindowTitle('System specs') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Ok) box.setDefaultButton(QMessageBox.Ok) layout = box.layout() layout.addItem(horizontalSpacer, layout.rowCount(), 0, 1, layout.columnCount()) box.exec() def onQuit(self): box = QMessageBox(self) #box.setCursor(AppData.cursors['arrow']) QGuiApplication.setOverrideCursor(AppData.cursors['arrow']) box.setText('Are you sure you want to quit?') box.setWindowTitle('Please confirm!') box.setWindowFlags(Qt.FramelessWindowHint | Qt.Dialog) box.setStandardButtons(QMessageBox.Yes | QMessageBox.No) box.setDefaultButton(QMessageBox.No) if box.exec() == QMessageBox.Yes: self.close() QGuiApplication.restoreOverrideCursor() def onSet(self): #from subprocess import call #call("notepad ./Project/Sequences/DefaultSequence.py") self.editor = QsciScintilla() # define the font to use font = QFont() font.setFamily('Courier') font.setFixedPitch(True) font.setPointSize(10) # the font metrics here will help # building the margin width later fm = QFontMetrics(font) ## set the default font of the editor ## and take the same font for line numbers self.editor.setFont(font) self.editor.setMarginsFont(font) ## Line numbers # conventionnaly, margin 0 is for line numbers self.editor.setMarginWidth(0, fm.width("00000") + 5) self.editor.setMarginLineNumbers(0, True) ## Edge Mode shows a red vetical bar at 80 chars self.editor.setEdgeMode(QsciScintilla.EdgeLine) self.editor.setEdgeColumn(80) self.editor.setEdgeColor(QColor("#FF0000")) ## Folding visual : we will use boxes self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle) ## Braces matching self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) ## Editing line color self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#CDA869")) ## Margins colors # line numbers margin self.editor.setMarginsBackgroundColor(QColor("#333333")) self.editor.setMarginsForegroundColor(QColor("#CCCCCC")) # folding margin colors (foreground,background) self.editor.setFoldMarginColors(QColor("#99CC66"), QColor("#333300")) ## Choose a lexer lexer = QsciLexerPython() lexer.setDefaultFont(font) api = QsciStrictAPIs(lexer) api.prepare() lexer.setDefaultFont(font) self.editor.setLexer(lexer) self.editor.setMinimumSize(1024, 768) self.editor.show() ## Show this file in the editor text = open("./Project/Sequences/DefaultSequence.py").read() self.editor.setText(text) def wheelEvent(self, event): if self.app.keyboardModifiers() & Qt.ControlModifier: self.fontSize += event.angleDelta().y() / 120 self.fontSizeLarge += event.angleDelta().y() / 120 self.fontSizeSmall += event.angleDelta().y() / 120 self.setStyleSheet( self.styleTemplate.format(fontSize=int(self.fontSize), fontSizeLarge=int( self.fontSizeLarge))) self.titleLabel.setText( self.titleTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall))) self.instructionsLabel.setText( self.instructionsTemplate.format( fontSize=int(self.fontSize), fontSizeLarge=int(self.fontSizeLarge), fontSizeSmall=int(self.fontSizeSmall), emptyFolderOp=('show' if self.tree.isHidingEmptyFolders else 'hide'))) self.tree.resizeColumnToContents(0) self.updateGeometry() #def eventFilter(self, obj, event): # #if event.type() in [ QEvent.MouseMove, QEvent.MouseButtonPress, QEvent.MouseButtonRelease, QEvent.MouseButtonDblClick]: # self.app.sendEvent(self.gridWidget, event) # return super().eventFilter(obj, event) def sizeHint(self): return self.app.desktop().screenGeometry().size()
class ScriptTab(QWidget,): autocomplete_lst = [] def __init__(self, parent, name, script="", filemodified=0): QWidget.__init__(self) self.parent = parent self.tabWidget = self.parent.ui.tabWidget self.gridlayout = QGridLayout(self) self._dirty = False self.initialize_editor() self.gridlayout.addWidget(self.editor) self.setAcceptDrops(True) self.filename = name self.filemodified = filemodified if self.is_file(): self.title = os.path.basename(name) # if self.equals_saved(): # self.filemodified = os.path.getmtime(self.filename) else: self.filename = "" self.title = name # Show this file in the self.editor self.editor.setText(script) self.clean_txt = self.saved() self.update_dirty() self.editor.keyPressEvent = self.key_press_event @property def scriptRunner(self): return self.parent.controller.scriptRunner def wheelEvent(self, event): if event.modifiers() == Qt.ControlModifier: if event.delta() > 0: self.editor.zoomIn() else: self.editor.zoomOut() return QWidget.wheelEvent(self, event) def initialize_editor(self): self.editor = QsciScintilla() # self.editor.cursorPositionChanged.connect(self.e) # self.editor.copyAvailable.connect(self.e) # self.editor.indicatorClicked.connect(self.e) # self.editor.indicatorReleased.connect(self.e) # self.editor.linesChanged.connect(self.e) # self.editor.marginClicked.connect(self.e) # self.editor.modificationAttempted.connect(self.e) # self.editor.modificationChanged.connect(self.e) # self.editor.selectionChanged.connect(self.e) # self.editor.textChanged.connect(self.e) # self.editor.userListActivated.connect(self.e) if self.editor.__class__.__name__ == "LineTextWidget": return # When using PySide without QSciScintilla # define the font to use font = QFont() font.setFamily("Consolas") font.setFixedPitch(True) font.setPointSize(10) # the font metrics here will help # building the margin width later fm = QFontMetrics(font) # set the default font of the self.editor # and take the same font for line numbers self.editor.setFont(font) self.editor.setMarginsFont(font) # Line numbers # conventionnaly, margin 0 is for line numbers self.editor.setMarginWidth(0, fm.width("00000") + 5) self.editor.setMarginLineNumbers(0, True) self.editor.setTabWidth(4) # Folding visual : we will use boxes self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle) self.editor.setAutoIndent(True) # Braces matching self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) # Editing line color self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#CDA869")) # Margins colors # line numbers margin self.editor.setMarginsBackgroundColor(QColor("#333333")) self.editor.setMarginsForegroundColor(QColor("#CCCCCC")) # folding margin colors (foreground,background) self.editor.setFoldMarginColors(QColor("#99CC66"), QColor("#333300")) # Choose a lexer self.lexer = QsciLexerPython() self.lexer.setDefaultFont(font) # Set the length of the string before the editor tries to autocomplete # In practise this would be higher than 1 # But its set lower here to make the autocompletion more obvious self.editor.setAutoCompletionThreshold(1) # Tell the editor we are using a QsciAPI for the autocompletion self.editor.setAutoCompletionSource(QsciScintilla.AcsAPIs) self.editor.setLexer(self.lexer) self.editor.setCallTipsStyle(QsciScintilla.CallTipsContext) # self.editor.setCallTipsVisible(0) # Create an API for us to populate with our autocomplete terms self.api = QsciAPIs(self.lexer) # Compile the api for use in the lexer self.api.prepare() # def tefocusInEvent(self, event): # self.parent.focusInEvent(event) # return QTextEdit.focusInEvent(self.textEditScript, event) def is_file(self): return os.path.isfile(self.filename) def is_modified(self): if self.is_file(): if self.equals_saved(): self.filemodified = os.path.getmtime(self.filename) return str(os.path.getmtime(self.filename)) != str(self.filemodified) else: return False def saved(self): if self.is_file(): f = open(self.filename) saved = f.read() f.close() return saved.strip() else: return "" def equals_saved(self): curr_lines = self.get_script().strip().splitlines() saved_lines = self.saved().strip().splitlines() if len(curr_lines) != len(saved_lines): return False for cl, sl in zip(curr_lines, saved_lines): if cl.strip() != sl.strip(): return False return True @property def dirty(self): if not self._dirty: self.dirty = self.clean_txt != self.get_script() return self._dirty @dirty.setter def dirty(self, dirty): if dirty is False: self.clean_txt = self.get_script() if self._dirty != dirty: self._dirty = dirty self.filename_changed() def update_dirty(self): return self.dirty def index(self): return self.tabWidget.indexOf(self) def filename_changed(self): index = self.parent.ui.tabWidget.indexOf(self) if self.dirty: self.tabWidget.setTabText(index, "%s*" % self.title) else: self.tabWidget.setTabText(index, self.title) def reload(self): self.set_script(self.parent._load_script(self.filename)) self.filemodified = os.path.getmtime(self.filename) def close(self): while self.dirty is True: # While avoids data loss, in case save operation is aborted if self.filename == "": text = "Save unsaved changes?" else: text = "Save %s?" % self.filename ans = QMessageBox.question(self, 'Save', text, QMessageBox.Yes, QMessageBox.Cancel, QMessageBox.No) if ans == QMessageBox.Cancel: return elif ans == QMessageBox.Yes: self.parent.actionSave(False) elif ans == QMessageBox.No: break self.tabWidget.removeTab(self.index()) def _save(self,): f = open(self.filename, 'w') f.write(self.get_script()) f.close() self.title = os.path.basename(self.filename) self.dirty = False def key_press_event(self, event): self.update_dirty() if self.editor.__class__.__name__ == "LineTextWidget": return self.editor.edit.keyReleaseEvent(event) # When using PySide without QSciScintilla QsciScintilla.keyPressEvent(self.editor, event) linenr, pos_in_line = self.editor.getCursorPosition() line = str(self.editor.text(linenr)[:pos_in_line]) if event.key() == Qt.Key_F1: try: self.parent.show_documentation(getattr(self.scriptRunner, str(self.editor.selectedText()))) except AttributeError: pass if event.key() == Qt.Key_Enter or event.key() == Qt.Key_Return: for tip in self.autocomplete_lst: try: if line.endswith(tip[:tip.index('(') ]): self.editor.insert(tip[tip.index('('):]) parent, residual = self.scriptRunner.split_line(line) self.parent.show_documentation(self.scriptRunner.get_function_dict(parent, residual)[residual]) return except ValueError: pass if event.key() < 100 or event.key() in [Qt.Key_Backspace, Qt.Key_Shift]: linenr, pos_in_line = self.editor.getCursorPosition() line = str(self.editor.text(linenr)[:pos_in_line]) lst = self.scriptRunner.get_autocomplete_list(line) if lst is not None: self.api.clear() list(map(self.api.add, lst)) self.api.prepare() if len(lst) > 0: self.autocomplete_lst = lst self.editor.autoCompleteFromAll() shift_event = QKeyEvent(QEvent.KeyPress, Qt.Key_Shift, Qt.NoModifier) QsciScintilla.keyPressEvent(self.editor, shift_event) # show autocomplete list def set_script(self, script): self.editor.setText(script) def get_script(self): return str(self.editor.text()).replace("\r", "").replace(">>> ", "").replace("\t", " ") def dropHandler(self, dataItemList, ctrl, shift, event): pass
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("Proyecto") MainWindow.resize(1074, 588) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.btn_abrir = QtWidgets.QPushButton(self.centralwidget) self.btn_abrir.setGeometry(QtCore.QRect(970, 20, 61, 41)) self.btn_abrir.setObjectName("btn_abrir") self.btn_guardar = QtWidgets.QPushButton(self.centralwidget) self.btn_guardar.setGeometry(QtCore.QRect(970, 70, 61, 41)) self.btn_guardar.setObjectName("btn_guardar") self.btn_guardar_como = QtWidgets.QPushButton(self.centralwidget) self.btn_guardar_como.setGeometry(QtCore.QRect(970, 120, 61, 41)) self.btn_guardar_como.setObjectName("btn_guardar_como") self.btn_ejecutar = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar.setGeometry(QtCore.QRect(960, 220, 81, 41)) self.btn_ejecutar.setObjectName("btn_ejecutar") self.btn_debug = QtWidgets.QPushButton(self.centralwidget) self.btn_debug.setGeometry(QtCore.QRect(970, 320, 61, 41)) self.btn_debug.setObjectName("btn_debug") self.btn_siguiente_paso = QtWidgets.QPushButton(self.centralwidget) self.btn_siguiente_paso.setGeometry(QtCore.QRect(970, 370, 61, 41)) self.btn_siguiente_paso.setObjectName("btn_siguiente_paso") self.tabWidget = QtWidgets.QTabWidget(self.centralwidget) self.tabWidget.setGeometry(QtCore.QRect(0, 10, 941, 551)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.txt_consola = QtWidgets.QTextEdit(self.tab) self.txt_consola.setGeometry(QtCore.QRect(10, 410, 511, 101)) self.txt_consola.setObjectName("txt_consola") self.tabWidget_4 = QtWidgets.QTabWidget(self.tab) self.tabWidget_4.setGeometry(QtCore.QRect(0, 0, 531, 391)) self.tabWidget_4.setObjectName("tabWidget_4") self.tab_8 = QtWidgets.QWidget() self.tab_8.setObjectName("tab_8") self.tabWidget_3 = QtWidgets.QTabWidget(self.tab_8) self.tabWidget_3.setGeometry(QtCore.QRect(0, 0, 521, 361)) self.tabWidget_3.setObjectName("tabWidget_3") self.tab_10 = QtWidgets.QWidget() self.tab_10.setObjectName("tab_10") self.frame_txt_entrada = QtWidgets.QFrame(self.tab_10) self.frame_txt_entrada.setGeometry(QtCore.QRect(10, 10, 501, 321)) self.frame_txt_entrada.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_txt_entrada.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_txt_entrada.setObjectName("frame_txt_entrada") self.tabWidget_3.addTab(self.tab_10, "") self.tab_11 = QtWidgets.QWidget() self.tab_11.setObjectName("tab_11") self.frame_txt_entrada_sin_optimizar = QtWidgets.QFrame(self.tab_11) self.frame_txt_entrada_sin_optimizar.setGeometry( QtCore.QRect(10, 10, 501, 321)) self.frame_txt_entrada_sin_optimizar.setFrameShape( QtWidgets.QFrame.StyledPanel) self.frame_txt_entrada_sin_optimizar.setFrameShadow( QtWidgets.QFrame.Raised) self.frame_txt_entrada_sin_optimizar.setObjectName( "frame_txt_entrada_sin_optimizar") self.tabWidget_3.addTab(self.tab_11, "") self.tabWidget_4.addTab(self.tab_8, "") self.tabWidget_2 = QtWidgets.QTabWidget(self.tab) self.tabWidget_2.setGeometry(QtCore.QRect(540, 20, 391, 491)) self.tabWidget_2.setObjectName("tabWidget_2") self.tab_12 = QtWidgets.QWidget() self.tab_12.setObjectName("tab_12") self.frame_txt_minor_c = QtWidgets.QFrame(self.tab_12) self.frame_txt_minor_c.setGeometry(QtCore.QRect(10, 10, 361, 441)) self.frame_txt_minor_c.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame_txt_minor_c.setFrameShadow(QtWidgets.QFrame.Raised) self.frame_txt_minor_c.setObjectName("frame_txt_minor_c") self.tabWidget_2.addTab(self.tab_12, "") self.tab_5 = QtWidgets.QWidget() self.tab_5.setObjectName("tab_5") self.scrollArea_2 = QtWidgets.QScrollArea(self.tab_5) self.scrollArea_2.setGeometry(QtCore.QRect(10, 10, 361, 441)) self.scrollArea_2.setWidgetResizable(True) self.scrollArea_2.setObjectName("scrollArea_2") self.scrollAreaWidgetContents_2 = QtWidgets.QWidget() self.scrollAreaWidgetContents_2.setGeometry( QtCore.QRect(0, 0, 518, 422)) self.scrollAreaWidgetContents_2.setObjectName( "scrollAreaWidgetContents_2") self.horizontalLayout = QtWidgets.QHBoxLayout( self.scrollAreaWidgetContents_2) self.horizontalLayout.setObjectName("horizontalLayout") self.treeView = QtWidgets.QTreeView(self.scrollAreaWidgetContents_2) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Minimum) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth( self.treeView.sizePolicy().hasHeightForWidth()) self.treeView.setSizePolicy(sizePolicy) self.treeView.setMinimumSize(QtCore.QSize(500, 0)) self.treeView.setLayoutDirection(QtCore.Qt.LeftToRight) self.treeView.setAnimated(True) self.treeView.setObjectName("treeView") self.horizontalLayout.addWidget(self.treeView) self.scrollArea_2.setWidget(self.scrollAreaWidgetContents_2) self.tabWidget_2.addTab(self.tab_5, "") self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.scrollArea_3 = QtWidgets.QScrollArea(self.tab_2) self.scrollArea_3.setGeometry(QtCore.QRect(10, 10, 681, 411)) self.scrollArea_3.setLayoutDirection(QtCore.Qt.LeftToRight) self.scrollArea_3.setWidgetResizable(True) self.scrollArea_3.setObjectName("scrollArea_3") self.scrollAreaWidgetContents_3 = QtWidgets.QWidget() self.scrollAreaWidgetContents_3.setGeometry( QtCore.QRect(0, 0, 679, 409)) self.scrollAreaWidgetContents_3.setObjectName( "scrollAreaWidgetContents_3") self.verticalLayout_2 = QtWidgets.QVBoxLayout( self.scrollAreaWidgetContents_3) self.verticalLayout_2.setObjectName("verticalLayout_2") self.lbl_graphviz = QtWidgets.QLabel(self.scrollAreaWidgetContents_3) self.lbl_graphviz.setMaximumSize(QtCore.QSize(16777215, 16777215)) self.lbl_graphviz.setFrameShape(QtWidgets.QFrame.Panel) self.lbl_graphviz.setText("") self.lbl_graphviz.setScaledContents(False) self.lbl_graphviz.setObjectName("lbl_graphviz") self.verticalLayout_2.addWidget(self.lbl_graphviz) self.scrollArea_3.setWidget(self.scrollAreaWidgetContents_3) self.tabWidget.addTab(self.tab_2, "") self.tab_3 = QtWidgets.QWidget() self.tab_3.setObjectName("tab_3") self.scrollArea = QtWidgets.QScrollArea(self.tab_3) self.scrollArea.setGeometry(QtCore.QRect(10, 10, 681, 411)) self.scrollArea.setWidgetResizable(True) self.scrollArea.setObjectName("scrollArea") self.scrollAreaWidgetContents = QtWidgets.QWidget() self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 679, 409)) self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents") self.tab_reporte = QtWidgets.QTabWidget(self.scrollAreaWidgetContents) self.tab_reporte.setGeometry(QtCore.QRect(20, 10, 661, 381)) self.tab_reporte.setObjectName("tab_reporte") self.tab_4 = QtWidgets.QWidget() self.tab_4.setObjectName("tab_4") self.scrollArea_4 = QtWidgets.QScrollArea(self.tab_4) self.scrollArea_4.setGeometry(QtCore.QRect(0, 10, 641, 341)) self.scrollArea_4.setWidgetResizable(True) self.scrollArea_4.setObjectName("scrollArea_4") self.scrollAreaWidgetContents_4 = QtWidgets.QWidget() self.scrollAreaWidgetContents_4.setGeometry( QtCore.QRect(0, 0, 639, 339)) self.scrollAreaWidgetContents_4.setObjectName( "scrollAreaWidgetContents_4") self.verticalLayout = QtWidgets.QVBoxLayout( self.scrollAreaWidgetContents_4) self.verticalLayout.setObjectName("verticalLayout") self.tabla_etiqueta = QtWidgets.QTableWidget( self.scrollAreaWidgetContents_4) self.tabla_etiqueta.setObjectName("tabla_etiqueta") self.tabla_etiqueta.setColumnCount(0) self.tabla_etiqueta.setRowCount(0) self.verticalLayout.addWidget(self.tabla_etiqueta) self.scrollArea_4.setWidget(self.scrollAreaWidgetContents_4) self.tab_reporte.addTab(self.tab_4, "") self.tab_6 = QtWidgets.QWidget() self.tab_6.setObjectName("tab_6") self.scrollArea_5 = QtWidgets.QScrollArea(self.tab_6) self.scrollArea_5.setGeometry(QtCore.QRect(0, 10, 641, 341)) self.scrollArea_5.setWidgetResizable(True) self.scrollArea_5.setObjectName("scrollArea_5") self.scrollAreaWidgetContents_5 = QtWidgets.QWidget() self.scrollAreaWidgetContents_5.setGeometry( QtCore.QRect(0, 0, 639, 339)) self.scrollAreaWidgetContents_5.setObjectName( "scrollAreaWidgetContents_5") self.horizontalLayout_2 = QtWidgets.QHBoxLayout( self.scrollAreaWidgetContents_5) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.tabla_error = QtWidgets.QTableWidget( self.scrollAreaWidgetContents_5) self.tabla_error.setObjectName("tabla_error") self.tabla_error.setColumnCount(0) self.tabla_error.setRowCount(0) self.horizontalLayout_2.addWidget(self.tabla_error) self.scrollArea_5.setWidget(self.scrollAreaWidgetContents_5) self.tab_reporte.addTab(self.tab_6, "") self.tab_9 = QtWidgets.QWidget() self.tab_9.setObjectName("tab_9") self.textEdit = QtWidgets.QTextEdit(self.tab_9) self.textEdit.setGeometry(QtCore.QRect(10, 20, 631, 321)) self.textEdit.setObjectName("textEdit") self.tab_reporte.addTab(self.tab_9, "") self.scrollArea.setWidget(self.scrollAreaWidgetContents) self.tabWidget.addTab(self.tab_3, "") self.tab_13 = QtWidgets.QWidget() self.tab_13.setObjectName("tab_13") self.tabWidget.addTab(self.tab_13, "") self.tab_7 = QtWidgets.QWidget() self.tab_7.setObjectName("tab_7") self.tabWidget.addTab(self.tab_7, "") self.btn_ejecutar_desc = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar_desc.setGeometry(QtCore.QRect(960, 270, 81, 41)) self.btn_ejecutar_desc.setObjectName("btn_ejecutar_desc") self.btn_ejecutar_minor_c = QtWidgets.QPushButton(self.centralwidget) self.btn_ejecutar_minor_c.setGeometry(QtCore.QRect(950, 170, 101, 41)) self.btn_ejecutar_minor_c.setObjectName("btn_ejecutar_minor_c") MainWindow.setCentralWidget(self.centralwidget) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1074, 21)) self.menubar.setObjectName("menubar") self.menuArchivo = QtWidgets.QMenu(self.menubar) self.menuArchivo.setObjectName("menuArchivo") self.menuEditar = QtWidgets.QMenu(self.menubar) self.menuEditar.setObjectName("menuEditar") self.menuAnalisis = QtWidgets.QMenu(self.menubar) self.menuAnalisis.setObjectName("menuAnalisis") MainWindow.setMenuBar(self.menubar) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.actionGuardar = QtWidgets.QAction(MainWindow) self.actionGuardar.setObjectName("actionGuardar") self.actionGuardar_Como = QtWidgets.QAction(MainWindow) self.actionGuardar_Como.setObjectName("actionGuardar_Como") self.actionGuardar_Como_2 = QtWidgets.QAction(MainWindow) self.actionGuardar_Como_2.setObjectName("actionGuardar_Como_2") self.actionAscendente = QtWidgets.QAction(MainWindow) self.actionAscendente.setObjectName("actionAscendente") self.actionDescendente = QtWidgets.QAction(MainWindow) self.actionDescendente.setObjectName("actionDescendente") self.actionReiniciar_Debug = QtWidgets.QAction(MainWindow) self.actionReiniciar_Debug.setObjectName("actionReiniciar_Debug") self.actionSiguiente_Paso_Debug = QtWidgets.QAction(MainWindow) self.actionSiguiente_Paso_Debug.setObjectName( "actionSiguiente_Paso_Debug") self.actionCopiar = QtWidgets.QAction(MainWindow) self.actionCopiar.setObjectName("actionCopiar") self.actionPegar = QtWidgets.QAction(MainWindow) self.actionPegar.setObjectName("actionPegar") self.actionBuscar = QtWidgets.QAction(MainWindow) self.actionBuscar.setObjectName("actionBuscar") self.actionReemplazar = QtWidgets.QAction(MainWindow) self.actionReemplazar.setObjectName("actionReemplazar") self.menuArchivo.addAction(self.actionGuardar) self.menuArchivo.addAction(self.actionGuardar_Como) self.menuArchivo.addAction(self.actionGuardar_Como_2) self.menuEditar.addAction(self.actionCopiar) self.menuEditar.addAction(self.actionPegar) self.menuEditar.addAction(self.actionBuscar) self.menuEditar.addAction(self.actionReemplazar) self.menuAnalisis.addAction(self.actionAscendente) self.menuAnalisis.addAction(self.actionDescendente) self.menuAnalisis.addAction(self.actionReiniciar_Debug) self.menuAnalisis.addAction(self.actionSiguiente_Paso_Debug) self.menubar.addAction(self.menuArchivo.menuAction()) self.menubar.addAction(self.menuEditar.menuAction()) self.menubar.addAction(self.menuAnalisis.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(0) self.tabWidget_4.setCurrentIndex(0) self.tabWidget_3.setCurrentIndex(0) self.tabWidget_2.setCurrentIndex(0) self.tab_reporte.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) self.__myFont = QFont() self.__myFont.setPointSize(12) #=========================================================EDITORES=================================== self.txt_minor_c = QsciScintilla() self.txt_minor_c.setText("") self.txt_minor_c.setUtf8(True) self.txt_minor_c.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_minor_c.setWrapMode(QsciScintilla.WrapWord) self.txt_minor_c.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.txt_minor_c.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_minor_c.setEolMode(QsciScintilla.EolWindows) self.txt_minor_c.setEolVisibility(False) # SANGRIA self.txt_minor_c.setIndentationsUseTabs(False) self.txt_minor_c.setTabWidth(4) self.txt_minor_c.setIndentationGuides(True) self.txt_minor_c.setTabIndents(True) self.txt_minor_c.setAutoIndent(True) self.txt_minor_c.setCaretForegroundColor(QColor("#ff0000ff")) self.txt_minor_c.setCaretLineVisible(True) self.txt_minor_c.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.txt_minor_c.setCaretWidth(2) # MARGENES self.txt_minor_c.setMarginType(0, QsciScintilla.NumberMargin) self.txt_minor_c.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_minor_c.setMarginsForegroundColor(QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerCPP(self.txt_minor_c) self.txt_minor_c.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_minor_c.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_minor_c) #====================================ENTRADA=========================== self.txt_entrada = QsciScintilla() self.txt_entrada.setText("") self.txt_entrada.setUtf8(True) self.txt_entrada.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_entrada.setWrapMode(QsciScintilla.WrapWord) self.txt_entrada.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.txt_entrada.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_entrada.setEolMode(QsciScintilla.EolWindows) self.txt_entrada.setEolVisibility(False) # SANGRIA self.txt_entrada.setIndentationsUseTabs(False) self.txt_entrada.setTabWidth(4) self.txt_entrada.setIndentationGuides(True) self.txt_entrada.setTabIndents(True) self.txt_entrada.setAutoIndent(True) self.txt_entrada.setCaretForegroundColor(QColor("#ff0000ff")) self.txt_entrada.setCaretLineVisible(True) self.txt_entrada.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.txt_entrada.setCaretWidth(2) # MARGENES self.txt_entrada.setMarginType(0, QsciScintilla.NumberMargin) self.txt_entrada.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_entrada.setMarginsForegroundColor(QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerRuby(self.txt_entrada) self.txt_entrada.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_entrada.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_entrada) #========================Entrada Sin Optimizar====================== self.txt_entrada_sin_optimizar = QsciScintilla() self.txt_entrada_sin_optimizar.setText("") self.txt_entrada_sin_optimizar.setUtf8(True) self.txt_entrada_sin_optimizar.setFont(self.__myFont) # AJUSTES DE TEXTO self.txt_entrada_sin_optimizar.setWrapMode(QsciScintilla.WrapWord) self.txt_entrada_sin_optimizar.setWrapVisualFlags( QsciScintilla.WrapFlagByText) self.txt_entrada_sin_optimizar.setWrapIndentMode( QsciScintilla.WrapIndentIndented) # FIN DE LINEA self.txt_entrada_sin_optimizar.setEolMode(QsciScintilla.EolWindows) self.txt_entrada_sin_optimizar.setEolVisibility(False) # SANGRIA self.txt_entrada_sin_optimizar.setIndentationsUseTabs(False) self.txt_entrada_sin_optimizar.setTabWidth(4) self.txt_entrada_sin_optimizar.setIndentationGuides(True) self.txt_entrada_sin_optimizar.setTabIndents(True) self.txt_entrada_sin_optimizar.setAutoIndent(True) self.txt_entrada_sin_optimizar.setCaretForegroundColor( QColor("#ff0000ff")) self.txt_entrada_sin_optimizar.setCaretLineVisible(True) self.txt_entrada_sin_optimizar.setCaretLineBackgroundColor( QColor("#1f0000ff")) self.txt_entrada_sin_optimizar.setCaretWidth(2) # MARGENES self.txt_entrada_sin_optimizar.setMarginType( 0, QsciScintilla.NumberMargin) self.txt_entrada_sin_optimizar.setMarginWidth( 0, "0000") # con este se puede quitar la linea self.txt_entrada_sin_optimizar.setMarginsForegroundColor( QColor("#ff888888")) # SE COLOCAN LAS REGLAS DEL EDITOR self.__lexer = QsciLexerRuby(self.txt_entrada_sin_optimizar) self.txt_entrada_sin_optimizar.setLexer(self.__lexer) self.__lyt = QVBoxLayout() self.frame_txt_entrada_sin_optimizar.setLayout(self.__lyt) self.__lyt.addWidget(self.txt_entrada_sin_optimizar) #====================================================================== #Para Abrir,Guardar,Como self.btn_abrir.clicked.connect(self.abrir_archivo) self.actionGuardar.triggered.connect(self.abrir_archivo) self.btn_guardar_como.clicked.connect(self.guardar_archivo_como) self.actionGuardar_Como_2.triggered.connect(self.guardar_archivo_como) self.actionGuardar_Como.triggered.connect(self.guardar_archivo) self.btn_guardar.clicked.connect(self.guardar_archivo) #Ejecucion self.btn_ejecutar.clicked.connect(self.parser) self.actionAscendente.triggered.connect(self.parser) self.btn_ejecutar_desc.clicked.connect(self.parser_descendente) self.actionDescendente.triggered.connect(self.parser_descendente) self.btn_debug.clicked.connect(self.parser_paso_iniciar) self.actionReiniciar_Debug.triggered.connect(self.parser_paso_iniciar) self.btn_siguiente_paso.clicked.connect(self.parser_paso_ejecutar) self.actionSiguiente_Paso_Debug.triggered.connect( self.parser_paso_ejecutar) self.btn_ejecutar_minor_c.clicked.connect(self.ejecutar_main_c) def ejecutar_main_c(self): from AProyecto2.Main import analizar_minor_c, analizar_minor_c_optimizar_3D rst = analizar_minor_c_optimizar_3D(self.txt_minor_c.text()) self.txt_entrada.setText(rst) def graficar_arbol(self): import pydot global Ts dot_string = Ts.generar_dot() graphs = pydot.graph_from_dot_data(dot_string) from PyQt5.QtWidgets import QApplication # app = QApplication(sys.argv) # win = QWidget() # l1 = QLabel() from PyQt5.QtGui import QPixmap qp = QPixmap() qp.loadFromData(graphs[0].create_png()) self.lbl_graphviz.resize(qp.size()) # m_imageLabel->resize(m_scaleFactor * m_imageLabel->size()); self.lbl_graphviz.setPixmap(qp) # vbox = QVBoxLayout() # vbox.addWidget(l1) # win.setLayout(vbox) # win.setWindowTitle("QPixmap Demo") # win.show() # sys.exit(app.exec_()) archivo_actual = None def guardar_archivo(self): if self.archivo_actual is None: self.guardar_archivo_como() else: file = open(self.archivo_actual, 'w') text = self.txt_entrada.text() file.write(text) self.color(text) def guardar_archivo_como(self): try: fname = QFileDialog.getSaveFileName() file = open(fname[0], 'w') text = self.txt_entrada.text() file.write(text) self.color(text) except: pass def abrir_archivo(self): try: fname = QFileDialog.getOpenFileName() f = open(fname[0], "r") input: str = f.read() self.color(input) self.archivo_actual = fname[0] self.txt_minor_c.setText(input) except: pass def color(self, input): return def parser_paso_iniciar(self): self.pasex = 1 self.ejecutar_main_c() try: self.txt_consola.clear() dim = self.txt_entrada.text() input = dim global Ts Ts.guardar_consola(self.txt_consola) Ts.nueva_ejecucion(input) raiz_produccion: ListaInstruccion = analizar_ascendente(input) self.raiz_global = raiz_produccion Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) else: Ts.mensaje_info("Error", "Error En El Codigo") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") raiz_global = None pasex = 1 def parser_paso_ejecutar(self): try: if self.raiz_global is not None: #DEFAULT_INDICATOR_ID = 1 #self.txt_entrada.indicatorDefine(QsciScintilla.FullBoxIndicator, self.pasex) #self.txt_entrada.fillIndicatorRange(self.pasex, 0, self.pasex + 1, 0, self.pasex) #self.pasex+=1 #print(self.pasex) ex = Ts.paso_a_paso_ejecutar() if ex == "exit": Ts.mensaje_info("Informacion", "Ejecucion Paso A Paso Completo") self.raiz_global = None treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() else: Ts.mensaje_info("Ejecucion", "No hay nada que ejecutar") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def parser(self): try: self.txt_consola.clear() global Ts Ts.guardar_consola(self.txt_consola) dim = self.txt_entrada.text() input = dim Ts.nueva_ejecucion(input) raiz_produccion: ListaInstruccion = analizar_ascendente(input) Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) Ts.ejecutar_main() else: Ts.mensaje_info("Error", "Error En El Codigo ") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def parser_descendente(self): try: self.txt_consola.clear() global Ts Ts.guardar_consola(self.txt_consola) dim = self.txt_entrada.text() input = dim Ts.nueva_ejecucion(input) from Contenido.Analizadores.SintacticoDescendente import analizar_descendente raiz_produccion: ListaInstruccion = analizar_descendente(input) Ts.guardar_tabla_etiqueta(self.tabla_etiqueta) Ts.guardar_tabla_error(self.tabla_error) if raiz_produccion is not None: Ts.cargar_etiquetas(raiz_produccion) Ts.ejecutar_main() else: Ts.mensaje_info("Error", "Error En El Codigo") #self.color() self.graficar_arbol() treeView = self.treeView treeView.setHeaderHidden(True) Ts.guardar_arbol(treeView) Ts.actualizar_arbol() self.textEdit.clear() self.textEdit.append("<div contenteditable>" + Ts.rp_cabecera() + "</div>") except: import sys Ts.mensaje_info("Error", "Error Durante El Analisis") print("Oops!", sys.exc_info()[0], "occurred.") def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.btn_abrir.setText(_translate("MainWindow", "Abrir")) self.btn_guardar.setText(_translate("MainWindow", "Guardar")) self.btn_guardar_como.setText( _translate("MainWindow", "Guardar\n" "Como")) self.btn_ejecutar.setText( _translate("MainWindow", "Ejecutar\n" "Ascendente")) self.btn_debug.setText(_translate("MainWindow", "Debug")) self.btn_siguiente_paso.setText( _translate("MainWindow", "Siguiente\n" "Paso")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_10), _translate("MainWindow", "Optimizada")) self.tabWidget_3.setTabText(self.tabWidget_3.indexOf(self.tab_11), _translate("MainWindow", "Sin Optimizar")) self.tabWidget_4.setTabText( self.tabWidget_4.indexOf(self.tab_8), _translate("MainWindow", "Salida De MinorC")) self.tabWidget_2.setTabText( self.tabWidget_2.indexOf(self.tab_12), _translate("MainWindow", "Entrada Minor C")) self.tabWidget_2.setTabText( self.tabWidget_2.indexOf(self.tab_5), _translate("MainWindow", "Tabla De Simbolos")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Archivo Entrada")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Visualizar")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_4), _translate("MainWindow", "Etiquetas")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_6), _translate("MainWindow", "Errores")) self.tab_reporte.setTabText(self.tab_reporte.indexOf(self.tab_9), _translate("MainWindow", "Gramatical")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_3), _translate("MainWindow", "Reporte")) self.tabWidget.setTabText( self.tabWidget.indexOf(self.tab_13), _translate("MainWindow", "Visualizar Minor C")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_7), _translate("MainWindow", "Reporte Minor C")) self.btn_ejecutar_desc.setText( _translate("MainWindow", "Ejecutar\n" "Descendente")) self.btn_ejecutar_minor_c.setText( _translate("MainWindow", "Ejecutar Minor C")) self.menuArchivo.setTitle(_translate("MainWindow", "Archivo")) self.menuEditar.setTitle(_translate("MainWindow", "Editar")) self.menuAnalisis.setTitle(_translate("MainWindow", "Analisis")) self.actionGuardar.setText(_translate("MainWindow", "Abrir")) self.actionGuardar_Como.setText(_translate("MainWindow", "Guardar")) self.actionGuardar_Como_2.setText( _translate("MainWindow", "Guardar Como")) self.actionAscendente.setText(_translate("MainWindow", "Ascendente")) self.actionDescendente.setText(_translate("MainWindow", "Descendente")) self.actionReiniciar_Debug.setText( _translate("MainWindow", "Reiniciar Debug")) self.actionSiguiente_Paso_Debug.setText( _translate("MainWindow", "Siguiente Paso Debug")) self.actionCopiar.setText(_translate("MainWindow", "Copiar")) self.actionPegar.setText(_translate("MainWindow", "Pegar")) self.actionBuscar.setText(_translate("MainWindow", "Buscar")) self.actionReemplazar.setText(_translate("MainWindow", "Reemplazar"))
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # -------------------------------- # # Window setup # # -------------------------------- # # 1. Define the geometry of the main window # ------------------------------------------ self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout # --------------------------- self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button # ------------------ self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # -------------------------------- # # QScintilla editor setup # # -------------------------------- # # ! Make instance of QSciScintilla class! # ---------------------------------------- self.__editor = QsciScintilla() self.__editor.setText("This\n") # Line 1 self.__editor.append("is\n") # Line 2 self.__editor.append("a\n") # Line 3 self.__editor.append("QScintilla\n") # Line 4 self.__editor.append("test\n") # Line 5 self.__editor.append("program\n") # Line 6 self.__editor.append("to\n") # Line 7 self.__editor.append("illustrate\n") # Line 8 self.__editor.append("some\n") # Line 9 self.__editor.append("basic\n") # Line 10 self.__editor.append("functions.") # Line 11 self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # 1. Text wrapping # ----------------- self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # 2. End-of-line mode # -------------------- self.__editor.setEolMode(QsciScintilla.EolWindows) self.__editor.setEolVisibility(False) # 3. Indentation # --------------- self.__editor.setIndentationsUseTabs(False) self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) # 4. Caret # --------- self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.__editor.setCaretWidth(2) # 5. Margins # ----------- # Margin 0 = Line nr margin self.__editor.setMarginType(0, QsciScintilla.NumberMargin) self.__editor.setMarginWidth(0, "0000") self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # Margin 1 = Symbol margin self.__editor.setMarginType(1, QsciScintilla.SymbolMargin) self.__editor.setMarginWidth(1, "00000") sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.setMarginMarkerMask(1, 0b1111) # 6. Margin mouse clicks # ----------------------- self.__editor.setMarginSensitivity(1, True) self.__editor.marginClicked.connect(self.__margin_left_clicked) self.__editor.marginRightClicked.connect(self.__margin_right_clicked) # ! Add editor to layout ! # ------------------------- self.__lyt.addWidget(self.__editor) self.show() '''''' def __margin_left_clicked(self, margin_nr, line_nr, state): print("Margin clicked (left mouse btn)!") print(" -> margin_nr: " + str(margin_nr)) print(" -> line_nr: " + str(line_nr)) print("") if state == Qt.ControlModifier: # Show green dot. self.__editor.markerAdd(line_nr, 0) elif state == Qt.ShiftModifier: # Show green arrow. self.__editor.markerAdd(line_nr, 1) elif state == Qt.AltModifier: # Show red dot. self.__editor.markerAdd(line_nr, 2) else: # Show red arrow. self.__editor.markerAdd(line_nr, 3) '''''' def __margin_right_clicked(self, margin_nr, line_nr, state): print("Margin clicked (right mouse btn)!") print(" -> margin_nr: " + str(margin_nr)) print(" -> line_nr: " + str(line_nr)) print("") '''''' def __btn_action(self): print("Hello World!") ''''''
class highlightEditor(QMainWindow): """ 语法高亮代码框 """ def __init__(self, parent=None, lineNumberOn=False): super(highlightEditor, self).__init__() self.editor = QsciScintilla(parent) font = QFont() font.setFamily("Consolas") font.setPointSize(12) font.setFixedPitch(True) self.editor.setFont(font) self.editor.setObjectName("editor") self.editor.setUtf8(True) self.editor.setMarginsFont(font) if lineNumberOn: self.editor.setMarginWidth( 0, len(str(len(self.editor.text().split('\n')))) * 20) self.editor.setMarginLineNumbers(0, lineNumberOn) self.editor.setBraceMatching(QsciScintilla.StrictBraceMatch) self.editor.setIndentationsUseTabs(True) self.editor.setIndentationWidth(4) self.editor.setTabIndents(True) self.editor.setAutoIndent(True) self.editor.setBackspaceUnindents(True) self.editor.setTabWidth(4) self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor('#DCDCDC')) self.editor.setIndentationGuides(True) self.editor.setFolding(QsciScintilla.PlainFoldStyle) self.editor.setMarginWidth(2, 12) self.editor.markerDefine(QsciScintilla.Minus, QsciScintilla.SC_MARKNUM_FOLDEROPEN) self.editor.markerDefine(QsciScintilla.Plus, QsciScintilla.SC_MARKNUM_FOLDER) self.editor.markerDefine(QsciScintilla.Minus, QsciScintilla.SC_MARKNUM_FOLDEROPENMID) self.editor.markerDefine(QsciScintilla.Plus, QsciScintilla.SC_MARKNUM_FOLDEREND) self.editor.setMarkerBackgroundColor( QColor("#FFFFFF"), QsciScintilla.SC_MARKNUM_FOLDEREND) self.editor.setMarkerForegroundColor( QColor("#272727"), QsciScintilla.SC_MARKNUM_FOLDEREND) self.editor.setMarkerBackgroundColor( QColor("#FFFFFF"), QsciScintilla.SC_MARKNUM_FOLDEROPENMID) self.editor.setMarkerForegroundColor( QColor("#272727"), QsciScintilla.SC_MARKNUM_FOLDEROPENMID) self.editor.setAutoCompletionSource(QsciScintilla.AcsAll) self.editor.setAutoCompletionCaseSensitivity(True) self.editor.setAutoCompletionReplaceWord(False) self.editor.setAutoCompletionThreshold(1) self.editor.setAutoCompletionUseSingle(QsciScintilla.AcusExplicit) self.lexer = highlight(self.editor) self.editor.setLexer(self.lexer) self.__api = QsciAPIs(self.lexer) autocompletions = keyword.kwlist + [] for ac in autocompletions: self.__api.add(ac) self.__api.prepare() self.editor.autoCompleteFromAll() self.editor.textChanged.connect(self.changed) def changed(self): self.editor.setMarginWidth( 0, len(str(len(self.editor.text().split('\n')))) * 20)
class CypherEditGridWidget(QWidget, Ui_cypherEditGridWidget): """ Class documentation goes here. """ def __init__(self, parent=None, fileName=None, fileText=None, mode=None): """ Constructor @param parent reference to the parent widget @type QWidget """ super(CypherEditGridWidget, self).__init__(parent) self.setupUi(self) self.parent = parent self.settings = QSettings() self.initUI() self.initScintilla() self.helper = Helper() self.mode = mode self.tabType = "CYPHER" self.tabName = fileName self.tabIndex = None # this is the index into the tabWidget of the tab this widget is on self.fileName = fileName self.fileText = fileText self.resultSet = None # create a neocon object for this file tab self.neoDriver = NeoDriver(name=self.parent.pageItem.neoConName, promptPW=self.parent.pageItem.promptPW) # add the data grid widget. self.dataGridGeneric = DataGridGeneric() self.dataGrid = DataGridWidget(self, neoCon=self.neoDriver, genCypher=self.dataGridGeneric) self.nodeGridLayout = QVBoxLayout(self.frmDataGrid) self.nodeGridLayout.setObjectName("nodeGridLayout") self.nodeGridLayout.setContentsMargins(1, 1, 1, 1) self.nodeGridLayout.setSpacing(1) self.nodeGridLayout.addWidget(self.dataGrid) if self.mode == MODENEW: if not self.fileText is None: self.loadText() if self.mode == MODEEDIT: self.loadFile() # position the splitter self.show( ) # you have to do this to force all the widgets sizes to update half = int((self.frmEditnGrid.height() / 2)) self.splitter.setSizes([half, half]) def logMsg(self, msg): if logging: logging.info(msg) def initUI(self, ): #initialize state of commit buttons and dropdown self.btnCommit.setEnabled(False) self.btnRollBack.setEnabled(False) self.cmbAutoCommit.setCurrentIndex(0) def initScintilla(self): # add and initialize the control to self.frmEditor self.editor = QsciScintilla() self.editor.setLexer(None) self.editor.setUtf8(True) # Set encoding to UTF-8 self.editor.setWrapMode(QsciScintilla.WrapNone) self.editor.setEolVisibility(False) self.editor.setIndentationsUseTabs(False) self.editor.setTabWidth(4) self.editor.setIndentationGuides(True) self.editor.setAutoIndent(True) self.editor.setMarginType(0, QsciScintilla.NumberMargin) self.editor.setMarginWidth(0, "00000") self.editor.setMarginsForegroundColor(QColor("#ffffffff")) self.editor.setMarginsBackgroundColor(QColor("#00000000")) self.verticalLayout_2.addWidget(self.editor) # setup the lexer self.lexer = CypherLexer(self.editor) self.editor.setLexer(self.lexer) self.setScintillaFontSize() self.editor.SendScintilla(self.editor.SCI_GETCURRENTPOS, 0) self.editor.setCaretForegroundColor(QColor("#ff0000ff")) self.editor.setCaretLineVisible(True) self.editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.editor.setCaretWidth(2) self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch) def setScintillaFontSize(self, ): # set font size to value saved in settings try: fontSize = int(self.settings.value("Lexer/FontSize", "10")) except: fontSize = 10 finally: for style in range(5): self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, style, fontSize) self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34, fontSize) self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35, fontSize) ##################################################################################### # methods related to the cypher file ##################################################################################### def loadText(self, ): QApplication.setOverrideCursor(Qt.WaitCursor) self.editor.append(self.fileText) self.editor.setModified(True) QApplication.restoreOverrideCursor() def loadFile(self, ): file = QFile(self.fileName) if not file.open(QFile.ReadOnly | QFile.Text): QMessageBox.warning( self, "NodeMaker", "Cannot read file %s:\n%s." % (self.fileName, file.errorString())) return False instr = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) self.editor.append(instr.readAll()) self.editor.setModified(False) QApplication.restoreOverrideCursor() def save(self, ): if self.mode == MODENEW: self.saveAs() else: self.saveIt() def saveAs(self, ): # first test to see if the file has changed # get filename to save as # dlg = QFileDialog() dlg.setAcceptMode(QFileDialog.AcceptSave) dlg.setDefaultSuffix("cyp") dlg.setNameFilters([ "Cypher Query (*.cyp *.cypher)", "Cypher Query (*.cyp)", "Cypher Query (*.cypher)", "all files (*.*)" ]) dlg.setDirectory(self.parent.settings.value("Default/ProjPath")) if dlg.exec_(): fileNames = dlg.selectedFiles() if fileNames: self.fileName = fileNames[0] # save the file self.saveIt() def saveIt(self, ): file = QFile(self.fileName) if not file.open(QFile.WriteOnly | QFile.Text): QMessageBox.warning( self, "NodeEra", "Cannot write file %s:\n%s." % (self.fileName, file.errorString())) return outstr = QTextStream(file) QApplication.setOverrideCursor(Qt.WaitCursor) outstr << self.editor.text() head, tail = ntpath.split(QFileInfo(self.fileName).fileName()) self.parent.tabCypher.setTabText(self.parent.tabCypher.currentIndex(), tail) self.mode = MODEEDIT QApplication.restoreOverrideCursor() def close(self, ): # print("editngrid close {}".format(self.fileName)) # see if there is an open transaction and cancel the close self.checkOpenTxn() # see if text has changed and save the file if the user wants to if self.editor.isModified(): # see if the user wants to save it if self.fileName is None: # these are unsaved cypher files so they have no filename yet displayName = self.parent.tabCypher.tabText(self.tabIndex) else: displayName = self.fileName if self.helper.saveChangedObject("Cypher File", displayName): self.save() return True ############################################################## # Button methods ############################################################## @pyqtSlot() def on_btnRun_clicked(self): """ Run the query at the cursor. """ self.runFileCursor() def runFileCursor(self): self.logMsg("User requests run Cypher in Cursor") # parse the text editor and get the index to the cypher command the cursor is pointing at currentCypherIndex = self.getSelectedCypher() # check if cursor in a query if currentCypherIndex is None: self.helper.displayErrMsg( "Run Query", "You must position cursor within the Cypher query.") QApplication.restoreOverrideCursor() return # get the cypher statement to be executed startOffset = self.cypherList[currentCypherIndex][0] self.dataGrid.cypher = self.cypherList[currentCypherIndex][1] # prompt the user for parameter values if any userCanceled = False if len(self.cypherParms[currentCypherIndex][1]) > 0: # print("Parms:{}".format(self.cypherParms[currentCypherIndex][1])) # display dialog to gather parms d = CypherParmEntryDlg( parent=self, parms=self.cypherParms[currentCypherIndex][1]) if d.exec_(): self.dataGrid.parmData = d.parmDict else: userCanceled = True self.dataGrid.parmData = None # print("Parm Dictionary:{}".format(self.dataGrid.parmData)) else: self.dataGrid.parmData = None # see if the user canceled the query rather than enter parameters if userCanceled: self.helper.displayErrMsg("Run Query", "User Canceled Query.") QApplication.restoreOverrideCursor() return # make sure the cypher is not just spaces, or nothing but a semicolon if (self.dataGrid.cypher.isspace() or len(self.dataGrid.cypher) == 0 or self.dataGrid.cypher.strip() == ";"): self.helper.displayErrMsg( "Run Query", "You must position cursor within the Cypher query.") else: QApplication.setOverrideCursor(Qt.WaitCursor) self.dataGrid.refreshGrid() QApplication.restoreOverrideCursor() # see if there was a syntax error and position cursor try: offset = self.dataGrid.neoCon.cypherLogDict["offset"] if offset > -1: self.editor.SendScintilla(QsciScintilla.SCI_GOTOPOS, offset + startOffset) except: pass finally: ### hack needed on mac os to force scintilla to show cursor and highlighted line self.helper.displayErrMsg("Run Query With Cursor", "Query Complete") def getSelectedCypher(self): ''' Build a list of cypher commands from the text in the editor ''' # get position of cursor which is a zero based offset, it seems to return zero if editor hasn't been clicked on yet try: position = self.editor.SendScintilla( QsciScintilla.SCI_GETCURRENTPOS, 0) except: position = 0 # initialize cypherList self.cypherList = [] self.cypherParms = [] parmList = [] currentCypherIndex = None # get the full text from the editor text = self.editor.text() # make sure there is something in the text if len(text) < 1: return currentCypherIndex # Walk through all the characters in text, and store start offset and end offset of each command startOffset = 0 endOffset = 0 foundCypher = False # tracks if we have found at least one character that is potentially a non-comment cypher command inComment = False # tracks if we're looking at comment characters inParm = False # tracks if we're looking at parameter characters inCypher = False # tracks if we've found a non comment character while scanning newParm = "" for chrCtr in range(0, len(text)): # print("before: chrCtr:{} char: {} ord:{} inComment:{} inParm:{} inCypher:{}".format(chrCtr, text[chrCtr], ord(text[chrCtr]), inComment, inParm, inCypher)) # see if we're in a comment ( this doesn't work for multiline comments) if chrCtr + 1 < len(text) and text[chrCtr] == '/': inParm = False if text[chrCtr + 1] == "/": inComment = True inCypher = False # see if end of line elif ord(text[chrCtr]) in [13, 10]: inParm = False if chrCtr + 1 < len(text): if not text[chrCtr + 1] in [13, 10]: # end of line ends the comment inComment = False elif text[chrCtr] == "$": if not inComment: foundCypher = True inParm = True elif text[chrCtr] == " ": if not inComment: foundCypher = True inParm = False elif (text[chrCtr] == ";" and inComment == False): foundCypher = True inParm = False endOffset = chrCtr # save each command in the list self.cypherList.append( [startOffset, text[startOffset:endOffset + 1]]) self.cypherParms.append([startOffset, parmList]) parmList = [] # HAPPY PATH - see if this is the command where the cursor is located if (position >= startOffset and position <= endOffset): currentCypherIndex = len(self.cypherList) - 1 # set the next starting offset startOffset = chrCtr + 1 endOffset = startOffset elif inComment == False: foundCypher = True inCypher = True if inParm: newParm = newParm + text[chrCtr] else: if len(newParm) > 0: # print("Parameter: {}".format(newParm)) parmList.append(newParm) newParm = "" # print("after: chrCtr:{} char: {} ord:{} inComment:{} inParm:{} inCypher:{}".format(chrCtr, text[chrCtr], ord(text[chrCtr]), inComment, inParm, inCypher)) # at this point all characters have been processed, must deal with edge cases, no final semicolon etc if len( self.cypherList ) == 0: # we never found a semi colon so the entire file is one cypher statement # return the entire text file self.cypherList.append([0, text]) self.cypherParms.append([0, parmList]) parmList = [] currentCypherIndex = 0 else: # we found some characters after the last semi colon. lastCypher = "" try: lastCypher = text[startOffset:len(text)] if lastCypher.isspace( ) == True: # if there is only whitespace after the last semicolon then return the last found cypher if currentCypherIndex is None: currentCypherIndex = len(self.cypherList) - 1 elif len( lastCypher ) < 1: # there are no characters after the last semicolon, but cursor is positioned past it then return the last found cypher if currentCypherIndex is None: currentCypherIndex = len(self.cypherList) - 1 elif inCypher == False and foundCypher == False: # none of the characters are outside a comment so return last found cypher if currentCypherIndex is None: currentCypherIndex = len(self.cypherList) - 1 else: self.cypherList.append( [startOffset, lastCypher] ) # since some characters are present, add them as the last cypher command self.cypherParms.append([startOffset, parmList]) parmList = [] if currentCypherIndex is None: currentCypherIndex = len(self.cypherList) - 1 except: if currentCypherIndex is None: currentCypherIndex = len( self.cypherList ) - 1 # return the last cypher command found if any error # print("cypher list: {}".format(self.cypherList)) return currentCypherIndex @pyqtSlot() def on_btnRunScript_clicked(self): """ this button will run all the cypher commands in the file one at a time. """ self.runFileAsScript() def runFileAsScript(self, ): ''' run each cypher command in the file one at a time. ''' QApplication.setOverrideCursor(Qt.WaitCursor) self.logMsg("User requests run Cypher file as a script") # parse the text editor into cypher commands, we don't care which one the cursor is in self.getSelectedCypher() if len(self.cypherList) < 1: self.helper.displayErrMsg( "Run File As Script", "The file has no cypher commands in it.") for cypherCmd in self.cypherList: # this is the starting offset of the cypher command in the entire file cypherOffset = cypherCmd[0] self.dataGrid.cypher = cypherCmd[1] # set editor selection to the cypher command self.editor.SendScintilla(QsciScintilla.SCI_SETSEL, cypherOffset, cypherOffset + len(self.dataGrid.cypher)) # skip any cypher is not just spaces, or nothing but a semicolon if (self.dataGrid.cypher.isspace() or len(self.dataGrid.cypher) == 0 or self.dataGrid.cypher.strip() == ";"): #self.helper.displayErrMsg("Run Query", "You must position cursor within the Cypher query.") pass else: self.dataGrid.refreshGrid() QApplication.processEvents() # see if there was a syntax error and position cursor try: offset = self.dataGrid.neoCon.cypherLogDict["offset"] if offset > -1: self.editor.SendScintilla(QsciScintilla.SCI_GOTOPOS, offset + cypherOffset) except: pass # set editor selection to the end of the file self.editor.SendScintilla(QsciScintilla.SCI_SETSEL, len(self.editor.text()), len(self.editor.text())) QApplication.restoreOverrideCursor() @pyqtSlot() def on_btnCommit_clicked(self): """ User clicks on the Commit button. Commit the TXN. """ self.doCommit() def doCommit(self): self.logMsg("User request Commit the transaction") if not self.neoDriver is None: rc, msg = self.neoDriver.commitTxn() self.logMsg("Commit Complete - {}".format(msg)) @pyqtSlot() def on_btnRollBack_clicked(self): """ User clicks on the Rollback button. Rollback the TXN. """ self.doRollBack() def doRollBack(self): self.logMsg("User request Rollback the transaction") if not self.neoDriver is None: rc, msg = self.neoDriver.rollbackTxn() self.logMsg("Rollback Complete - {}".format(msg)) def zoomIn(self, ): """ increase Font Size """ # self.editor.SendScintilla(QsciScintilla.SCI_ZOOMIN) # currentFontSize = self.editor.SendScintilla(QsciScintilla.SCI_STYLEGETSIZE, 0) # self.settings.setValue("Lexer/FontSize", currentFontSize) # get style 0 font size - all styles use same size currentFontSize = self.editor.SendScintilla( QsciScintilla.SCI_STYLEGETSIZE, 0) currentFontSize = currentFontSize + 2 if currentFontSize < 24: self.settings.setValue("Lexer/FontSize", currentFontSize) for style in range(255): self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, style, currentFontSize) # self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34, currentFontSize) # self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35, currentFontSize) def zoomOut(self, ): """ decrease font size """ # self.editor.SendScintilla(QsciScintilla.SCI_ZOOMOUT) # currentFontSize = self.editor.SendScintilla(QsciScintilla.SCI_STYLEGETSIZE, 0) # self.settings.setValue("Lexer/FontSize", currentFontSize) # get style 0 font size - all styles use same size currentFontSize = self.editor.SendScintilla( QsciScintilla.SCI_STYLEGETSIZE, 0) currentFontSize = currentFontSize - 2 if currentFontSize > 4: self.settings.setValue("Lexer/FontSize", currentFontSize) for style in range(255): # was 5 self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, style, currentFontSize) # self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 34, currentFontSize) # self.editor.SendScintilla(QsciScintilla.SCI_STYLESETSIZE, 35, currentFontSize) def checkOpenTxn(self): ''' check if current txn is still open. if autocommit is false then ask the user to commit or rollback if autocommit is true then do the commit ''' if not (self.neoDriver is None): if not (self.neoDriver.tx is None): if self.neoDriver.tx.closed() is False: if self.neoDriver.autoCommit is True: self.doCommit() else: # prompt user to commit or rollback the current transaction msgBox = QMessageBox() msgBox.setIcon(QMessageBox.Warning) msgBox.setText( "You have an uncommitted transaction. Do you want to commit? (click Yes to commit, No to rollback" ) msgBox.setWindowTitle("Commit or Rollback") msgBox.setStandardButtons(QMessageBox.Yes | QMessageBox.No) result = msgBox.exec_() if result == QMessageBox.Yes: self.doCommit() else: self.doRollBack() @pyqtSlot(int) def on_cmbAutoCommit_currentIndexChanged(self, index): """ User has changed the auto commit dropdown. @param index DESCRIPTION @type int """ self.logMsg("User request transaction mode changed to {}".format( self.cmbAutoCommit.currentText())) if self.cmbAutoCommit.currentText() == "Auto Commit On": self.checkOpenTxn() if not (self.neoDriver is None): self.neoDriver.setAutoCommit(True) self.btnCommit.setEnabled(False) self.btnRollBack.setEnabled(False) if self.cmbAutoCommit.currentText() == "Auto Commit Off": self.checkOpenTxn() if not (self.neoDriver is None): self.neoDriver.setAutoCommit(False) self.btnCommit.setEnabled(True) self.btnRollBack.setEnabled(True)
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, name, currentValue): super(QDialog, self).__init__() self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(currentValue) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) container0 = QWidget() container0.setLayout(hLayout0) verticalLayout = QVBoxLayout() verticalLayout.addWidget(container0) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout =QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) self.language = 'python' def cancel(self): self.close() def accept(self): self.codeChanged.emit(self.codeEdit.text()) self.close() def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class TransitionCodeDialog(QDialog): codeChanged = pyqtSignal('int', 'QString', 'QString') def __init__(self, name, transition): super(QDialog, self).__init__() self.transition = transition self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(self.transition.getCode()) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.language = 'python' self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) codeLanguageContainer = QWidget() hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) codeLanguageContainer.setLayout(hLayout0) self.temporalButton = QRadioButton('Temporal', self) self.temporalButton.toggled.connect(self.temporalToggled) self.conditionalButton = QRadioButton('Conditional', self) self.conditionalButton.toggled.connect(self.conditionalToggled) radioButtonContainer = QGroupBox() radioButtonContainer.setTitle('Transition Type') vLayout = QVBoxLayout() vLayout.addWidget(self.temporalButton) vLayout.addWidget(self.conditionalButton) radioButtonContainer.setLayout(vLayout) self.transitionTypeCode = QTextEdit() self.transitionTypeCode.setFont(fixedWidthFont) self.transitionGroupBox = QGroupBox() self.transitionGroupBox.setTitle('Temporal (number in ms)') h3Layout = QHBoxLayout() h3Layout.addWidget(self.transitionTypeCode) self.transitionGroupBox.setLayout(h3Layout) typeContainer = QWidget() h2Layout = QHBoxLayout() h2Layout.addWidget(radioButtonContainer) h2Layout.addWidget(self.transitionGroupBox) typeContainer.setLayout(h2Layout) verticalLayout = QVBoxLayout() verticalLayout.addWidget(typeContainer) verticalLayout.addWidget(codeLanguageContainer) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout =QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) if self.transition.getType() == TransitionType.CONDITIONAL: self.conditionalButton.setChecked(True) self.conditionalToggled() elif self.transition.getType() == TransitionType.TEMPORAL: self.temporalButton.setChecked(True) self.temporalToggled() def cancel(self): self.close() def accept(self): type = None typeValue = None if self.temporalButton.isChecked(): type = int(TransitionType.TEMPORAL) typeValue = self.transitionTypeCode.toPlainText() elif self.conditionalButton.isChecked(): type = int(TransitionType.CONDITIONAL) typeValue = self.transitionTypeCode.toPlainText() self.codeChanged.emit(type, typeValue, self.codeEdit.text()) self.close() def temporalToggled(self): if (self.temporalButton.isChecked()): self.transitionGroupBox.setTitle('Temporal (number in ms)') self.transitionTypeCode.setPlainText(str(self.transition.getTemporalTime())) # print('temporal toggled') def conditionalToggled(self): if (self.conditionalButton.isChecked()): self.transitionGroupBox.setTitle('Condition (evaluates to true or false)') self.transitionTypeCode.setPlainText(self.transition.getCondition()) # print('conditional toggled') def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class CodeDialog(QDialog): codeChanged = pyqtSignal('QString') def __init__(self, name, currentValue): super(QDialog, self).__init__() self.setWindowTitle(name) self.resize(800, 600) self.codeEdit = QsciScintilla() self.codeEdit.setText(currentValue) fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) self.codeEdit.setFont(fixedWidthFont) fontmetrics = QFontMetrics(fixedWidthFont) self.codeEdit.setMarginWidth(0, fontmetrics.width("000")) self.codeEdit.setMarginLineNumbers(0, True) self.codeEdit.setMarginsBackgroundColor(QColor("#cccccc")) self.codeEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch) self.codeEdit.setCaretLineVisible(True) self.codeEdit.setCaretLineBackgroundColor(QColor("#ffe4e4")) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.codeEdit.SendScintilla(QsciScintilla.SCI_SETHSCROLLBAR, 0) self.codeEdit.setUtf8(True) self.codeEdit.setTabWidth(4) self.codeEdit.setIndentationsUseTabs(True) self.codeEdit.setIndentationGuides(True) self.codeEdit.setTabIndents(True) self.codeEdit.setAutoIndent(True) self.cancelButton = QPushButton('Cancel') self.cancelButton.clicked.connect(self.cancel) self.acceptButton = QPushButton('Accept') self.acceptButton.clicked.connect(self.accept) self.pythonButton = QRadioButton('Python') self.pythonButton.setChecked(True) self.pythonButton.clicked.connect(self.pythonClicked) self.cppButton = QRadioButton('C++') self.cppButton.clicked.connect(self.cppClicked) hLayout0 = QHBoxLayout() hLayout0.addWidget(self.pythonButton) hLayout0.addWidget(self.cppButton) container0 = QWidget() container0.setLayout(hLayout0) verticalLayout = QVBoxLayout() verticalLayout.addWidget(container0) verticalLayout.addWidget(self.codeEdit) container = QWidget() hLayout = QHBoxLayout() hLayout.addWidget(self.cancelButton) hLayout.addWidget(self.acceptButton) container.setLayout(hLayout) verticalLayout.addWidget(container) self.setLayout(verticalLayout) self.language = 'python' def cancel(self): self.close() def accept(self): self.codeChanged.emit(self.codeEdit.text()) self.close() def pythonClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerPython() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'python' def cppClicked(self): fixedWidthFont = QFontDatabase.systemFont(QFontDatabase.FixedFont) lexer = QsciLexerCPP() lexer.setDefaultFont(fixedWidthFont) self.codeEdit.setLexer(lexer) self.language = 'cpp'
class MainWindow(QMainWindow): def __init__(self): super().__init__(flags=0) self.code = QsciScintilla() # self.code.setTabStopWidth(4) self.code.setTabWidth(4) self.code.setMarginWidth(1, 100) self.code.setMarginLineNumbers(1, True) self.code.setAutoIndent(True) self.font = QFont('Courier New', 18) self.code.setFont(self.font) self.code.setMinimumSize(1024, 768) self.locations = {} self.debug_mode = False self.setCentralWidget(self.code) self.pane_output = QDockWidget('Output', self) self.output = QTextEdit(self.pane_output) self.pane_memory = QDockWidget('Memory', self) self.memory_list = QListWidget(self.pane_memory) self.memory = [0] * 65536 self.setup_menu() self.setup_panes() self.cfg = Config() self.directory = self.cfg.get('directory') self.filename = self.cfg.get('filename') if self.filename: self.open_file(self.filename) self.mega = Mega() self.update_memory_list() self.load_settings() def load_settings(self): geom = self.cfg.get('geometry') if not isinstance(geom, str): self.restoreGeometry(geom) state = self.cfg.get('state') if not isinstance(state, str): self.restoreState(state) def closeEvent(self, e: QCloseEvent) -> None: self.cfg.set('geometry', self.saveGeometry()) self.cfg.set('state', self.saveState()) def setup_panes(self): self.pane_output.setObjectName('Output') self.pane_output.setAllowedAreas(Qt.BottomDockWidgetArea) self.output.setTextInteractionFlags(Qt.TextSelectableByMouse) self.output.setFont(self.font) self.pane_output.setWidget(self.output) self.addDockWidget(Qt.BottomDockWidgetArea, self.pane_output) self.pane_memory.setObjectName('Memory') self.pane_memory.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) self.pane_memory.setWidget(self.memory_list) self.memory_list.setFont(self.font) self.addDockWidget(Qt.RightDockWidgetArea, self.pane_memory) def setup_menu(self): mb = self.menuBar() m = mb.addMenu('&File') dir_open = QAction('Open &Dir', m) dir_open.triggered.connect(self.on_dir_open) m.addAction(dir_open) file_open = QAction('&Open', m) file_open.triggered.connect(self.on_file_open) file_open.setShortcut('Ctrl+O') m.addAction(file_open) file_save = QAction('&Save', m) file_save.triggered.connect(self.on_file_save) file_save.setShortcut('Ctrl+S') m.addAction(file_save) m = mb.addMenu('&Build') assemble = QAction('&Assemble', m) assemble.triggered.connect(self.on_assemble) assemble.setShortcut('F7') m.addAction(assemble) program = QAction('&Program', m) program.triggered.connect(self.on_program) program.setShortcut('F9') m.addAction(program) m = mb.addMenu('&Debug') start = QAction('&Mode', m) start.triggered.connect(self.on_toggle_debug) start.setShortcut('F5') m.addAction(start) clock = QAction('&Clock', m) clock.triggered.connect(self.on_clock) clock.setShortcut('F11') m.addAction(clock) clock = QAction('&AutoClock', m) clock.triggered.connect(self.on_auto_clock) m.addAction(clock) ram = QAction('&RAM Update', m) ram.triggered.connect(self.on_update_memory) ram.setShortcut('F6') m.addAction(ram) def on_dir_open(self): res = QFileDialog.getExistingDirectory(caption='Select Directory', directory=self.directory) print(res) def open_file(self, filename): try: self.code.setText(open(filename).read()) self.cfg.set('filename', filename) except IOError: QMessageBox.warning(self, title='Error', text=f'Cannot open {filename}') def on_file_open(self): res = QFileDialog.getOpenFileName(caption='Open', filter='*.asm') filename = res[0] if filename: self.open_file(filename) def on_file_save(self): if self.filename: code = self.code.text() with open(self.filename, 'w') as f: f.write(code) def set_output(self, text, default=''): if not text: text = default self.output.setText(text) def on_assemble(self): work_dir = os.path.dirname(self.filename) filename = os.path.basename(self.filename) try: res = subprocess.run(['zasm', filename, '0', '0'], capture_output=True, cwd=work_dir, check=True) self.set_output(res.stdout.decode('utf-8'), 'Done') except subprocess.CalledProcessError: self.set_output('Assembler failed') def on_program(self): bin_name = self.filename.replace('.asm', '.bin') try: data = open(bin_name, 'rb').read() self.mega.write_memory(0, data) except IOError: QMessageBox.warning(parent=self, title='Error', text='Failed to open binary') def on_toggle_debug(self): if self.debug_mode: self.on_stop_debug() else: self.on_start_debug() def on_stop_debug(self): self.debug_mode = False try: self.code.setText(open(self.filename).read()) self.code.setReadOnly(False) except IOError: QMessageBox.warning(parent=self, title="Error", text=f'File "{self.filename}" not found') def on_start_debug(self): self.debug_mode = True lst_name = self.filename.replace('.asm', '.lst') try: listing = open(lst_name).read() self.code.setText(listing) self.code.setReadOnly(True) i = 0 for line in listing.split('\n'): parts = line.split() if parts: address = int(parts[0], 0) self.addr2line[address] = i i += 1 except IOError: QMessageBox.warning(parent=self, title='Error', text='No listing found. Try assemble') def on_clock(self): count = 0 print("------------------------------------------------------") while True: address, data, flags = self.mega.clock_read_bus() print(f'{address:04x}:{data:02x} {flags:02x} {flag_text(flags)}') if (flags & 3) == 0: count += 1 if count >= 2: if address in self.addr2line: y = self.addr2line.get(address) self.code.setSelection(y, 0, y + 1, 0) break def on_auto_clock(self): self.mega.auto_clock() def update_memory_list(self): self.memory_list.clear() for address in range(0, 8192, 16): line = f'{address:04x}' for i in range(16): line = line + f' {self.memory[address + i]:02x}' self.memory_list.addItem(QListWidgetItem(line)) def update_memory(self, address: int, length: int): if address < 0 or (address + length) > len(self.memory): QMessageBox.warning(parent=self, title='Error', text='Invalid memory range') return data = self.mega.read_memory(address, length) self.memory[address:(address + length)] = data self.update_memory_list() def on_update_memory(self): self.update_memory(0, 8192)
class CustomMainWindow(QMainWindow): def __init__(self): super(CustomMainWindow, self).__init__() # -------------------------------- # # Window setup # # -------------------------------- # # 1. Define the geometry of the main window # ------------------------------------------ self.setGeometry(300, 300, 800, 400) self.setWindowTitle("QScintilla Test") # 2. Create frame and layout # --------------------------- self.__frm = QFrame(self) self.__frm.setStyleSheet("QWidget { background-color: #ffeaeaea }") self.__lyt = QVBoxLayout() self.__frm.setLayout(self.__lyt) self.setCentralWidget(self.__frm) self.__myFont = QFont() self.__myFont.setPointSize(14) # 3. Place a button # ------------------ self.__btn = QPushButton("Qsci") self.__btn.setFixedWidth(50) self.__btn.setFixedHeight(50) self.__btn.clicked.connect(self.__btn_action) self.__btn.setFont(self.__myFont) self.__lyt.addWidget(self.__btn) # -------------------------------- # # QScintilla editor setup # # -------------------------------- # # ! Make instance of QSciScintilla class! # ---------------------------------------- self.__editor = QsciScintilla() self.__editor.setText("This\n") # Line 1 self.__editor.append("is\n") # Line 2 self.__editor.append("a\n") # Line 3 self.__editor.append("QScintilla\n") # Line 4 self.__editor.append("test\n") # Line 5 self.__editor.append("program\n") # Line 6 self.__editor.append("to\n") # Line 7 self.__editor.append("illustrate\n") # Line 8 self.__editor.append("some\n") # Line 9 self.__editor.append("basic\n") # Line 10 self.__editor.append("functions.") # Line 11 self.__editor.setLexer(None) self.__editor.setUtf8(True) # Set encoding to UTF-8 self.__editor.setFont(self.__myFont) # 1. Text wrapping # ----------------- self.__editor.setWrapMode(QsciScintilla.WrapWord) self.__editor.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.__editor.setWrapIndentMode(QsciScintilla.WrapIndentIndented) # 2. End-of-line mode # -------------------- self.__editor.setEolMode(QsciScintilla.EolWindows) self.__editor.setEolVisibility(False) # 3. Indentation # --------------- self.__editor.setIndentationsUseTabs(False) self.__editor.setTabWidth(4) self.__editor.setIndentationGuides(True) self.__editor.setTabIndents(True) self.__editor.setAutoIndent(True) # 4. Caret # --------- self.__editor.setCaretForegroundColor(QColor("#ff0000ff")) self.__editor.setCaretLineVisible(True) self.__editor.setCaretLineBackgroundColor(QColor("#1f0000ff")) self.__editor.setCaretWidth(2) # 5. Margins # ----------- # Margin 0 = Line nr margin self.__editor.setMarginType(0, QsciScintilla.NumberMargin) self.__editor.setMarginWidth(0, "0000") self.__editor.setMarginsForegroundColor(QColor("#ff888888")) # Margin 1 = Symbol margin self.__editor.setMarginType(1, QsciScintilla.SymbolMargin) self.__editor.setMarginWidth(1, "00000") sym_0 = QImage("icons/sym_0.png").scaled(QSize(16, 16)) sym_1 = QImage("icons/sym_1.png").scaled(QSize(16, 16)) sym_2 = QImage("icons/sym_2.png").scaled(QSize(16, 16)) sym_3 = QImage("icons/sym_3.png").scaled(QSize(16, 16)) self.__editor.markerDefine(sym_0, 0) self.__editor.markerDefine(sym_1, 1) self.__editor.markerDefine(sym_2, 2) self.__editor.markerDefine(sym_3, 3) self.__editor.setMarginMarkerMask(1, 0b1111) # Display a few symbols, and keep their handles stored handle_01 = self.__editor.markerAdd(0, 0) # Green dot on line 0+1 handle_02 = self.__editor.markerAdd(4, 0) # Green dot on line 4+1 handle_03 = self.__editor.markerAdd(5, 0) # Green dot on line 5+1 handle_04 = self.__editor.markerAdd(8, 3) # Red arrow on line 8+1 handle_05 = self.__editor.markerAdd(9, 2) # Red dot on line 9+1 # ! Add editor to layout ! # ------------------------- self.__lyt.addWidget(self.__editor) self.show() '''''' def __btn_action(self): print("Hello World!") ''''''
class Interfaz(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(1349, 806) self.mw = MainWindow self.puntos_break = [] self.rutaTemp = "" self.pestañas = {} self.nombre = "" self.gc = False palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 128)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 128)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Window, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush) MainWindow.setPalette(palette) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.new_file = QtWidgets.QPushButton(self.centralwidget) self.new_file.setGeometry(QtCore.QRect(0, 0, 71, 61)) self.new_file.setObjectName("new_file") self.new_file.clicked.connect(self.agregar_tab) self.save_file = QtWidgets.QPushButton(self.centralwidget) self.save_file.setGeometry(QtCore.QRect(70, 0, 71, 61)) self.save_file.setObjectName("save_file") self.save_file.clicked.connect(self.guardar) self.save_file_as = QtWidgets.QPushButton(self.centralwidget) self.save_file_as.setGeometry(QtCore.QRect(140, 0, 71, 61)) self.save_file_as.setObjectName("save_file_as") self.save_file_as.clicked.connect(self.guardar_como) #boton ejecutar self.ejecutar = QtWidgets.QPushButton(self.centralwidget) self.ejecutar.setGeometry(QtCore.QRect(240, 0, 71, 61)) self.ejecutar.setObjectName("ejecutar") self.ejecutar.clicked.connect(self.Traducir_Alto_nivel) #end ejecutar #inico depurar self.depurar = QtWidgets.QPushButton(self.centralwidget) self.depurar.setGeometry(QtCore.QRect(310, 0, 71, 61)) self.depurar.setObjectName("depurar") self.depurar.clicked.connect(self.Depurar_Alto_nivel) #end depurar self.parar = QtWidgets.QPushButton(self.centralwidget) self.parar.setGeometry(QtCore.QRect(380, 0, 71, 61)) self.parar.setObjectName("parar") self.parar.clicked.connect(self.detenerEjecucion) #end parar self.step_step = QtWidgets.QPushButton(self.centralwidget) self.step_step.setGeometry(QtCore.QRect(450, 0, 71, 61)) self.step_step.setObjectName("step_step") self.step_step.clicked.connect(self.setStep) #end step self.continuar = QtWidgets.QPushButton(self.centralwidget) self.continuar.setGeometry(QtCore.QRect(520, 0, 71, 61)) self.continuar.setObjectName("continuar") self.continuar.clicked.connect(self.setContinuar) #end continuar self.tema = QtWidgets.QPushButton(self.centralwidget) self.tema.setGeometry(QtCore.QRect(640, 0, 71, 61)) self.tema.setObjectName("tema") self.tema.clicked.connect(self.setLines) self.lineas = QtWidgets.QPushButton(self.centralwidget) self.lineas.setGeometry(QtCore.QRect(710, 0, 71, 61)) self.lineas.setObjectName("lineas") self.lineas.clicked.connect(self.ms_help) self.editor = QtWidgets.QTabWidget(self.centralwidget) self.editor.setGeometry(QtCore.QRect(10, 80, 661, 421)) self.editor.setObjectName("editor") self.editor.setTabsClosable(True) self.editor.tabCloseRequested.connect(self.closeTab) self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.__myFont = QtGui.QFont() self.__myFont.setPointSize(11) #Principio self.plainTextEdit = QsciScintilla(self.tab) self.plainTextEdit.setGeometry(QtCore.QRect(10, 10, 631, 371)) self.plainTextEdit.setObjectName("plainTextEdit") self.plainTextEdit.setFont(self.__myFont) self.plainTextEdit.setMarginType(0, QsciScintilla.NumberMargin) self.plainTextEdit.setMarginWidth(0, "00000") self.plainTextEdit.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) self.plainTextEdit.markerDefine(QsciScintilla.RightArrow, 0) self.plainTextEdit.setMarginSensitivity(0, True) self.plainTextEdit.setWrapMode(QsciScintilla.WrapWord) self.plainTextEdit.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.plainTextEdit.setWrapIndentMode(QsciScintilla.WrapIndentIndented) self.plainTextEdit.setEolMode(QsciScintilla.EolWindows) self.plainTextEdit.setEolVisibility(False) self.plainTextEdit.setWrapVisualFlags(QsciScintilla.WrapFlagByText) self.plainTextEdit.marginClicked.connect(self.on_margin_clicked) self.__lexer = QsciLexerCPP(self.plainTextEdit) self.plainTextEdit.setLexer(self.__lexer) self.editor.addTab(self.tab, "") #end of de evangelion self.label = QtWidgets.QLabel(self.centralwidget) self.label.setGeometry(QtCore.QRect(690, 80, 171, 16)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label.setPalette(palette) self.label.setObjectName("label") self.codigo_3d = QtWidgets.QListWidget(self.centralwidget) self.codigo_3d.setGeometry(QtCore.QRect(680, 100, 211, 401)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush) self.codigo_3d.setPalette(palette) self.codigo_3d.setObjectName("codigo_3d") self.consola = PlainTextEdit(self.centralwidget) self.consola.setGeometry(QtCore.QRect(10, 530, 661, 221)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(29, 29, 29)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(29, 29, 29)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush) ########################### self.consola.setPalette(palette) self.consola.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAsNeeded) self.consola.setObjectName("consola") ########################### self.label_2 = QtWidgets.QLabel(self.centralwidget) self.label_2.setGeometry(QtCore.QRect(890, 80, 171, 16)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_2.setPalette(palette) self.label_2.setObjectName("label_2") self.tabla_cuadruplos = QtWidgets.QTableWidget(self.centralwidget) self.tabla_cuadruplos.setGeometry(QtCore.QRect(680, 530, 431, 221)) self.tabla_cuadruplos.setObjectName("tabla_cuadruplos") self.tabla_cuadruplos.setColumnCount(4) self.tabla_cuadruplos.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.tabla_cuadruplos.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tabla_cuadruplos.setHorizontalHeaderItem(1, item) item = QtWidgets.QTableWidgetItem() self.tabla_cuadruplos.setHorizontalHeaderItem(2, item) item = QtWidgets.QTableWidgetItem() self.tabla_cuadruplos.setHorizontalHeaderItem(3, item) self.label_3 = QtWidgets.QLabel(self.centralwidget) self.label_3.setGeometry(QtCore.QRect(690, 510, 71, 16)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_3.setPalette(palette) self.label_3.setObjectName("label_3") self.tabla_simbolos = QtWidgets.QTableWidget(self.centralwidget) self.tabla_simbolos.setGeometry(QtCore.QRect(1120, 100, 211, 651)) self.tabla_simbolos.setObjectName("tabla_simbolos") self.tabla_simbolos.setColumnCount(2) self.tabla_simbolos.setRowCount(0) item = QtWidgets.QTableWidgetItem() self.tabla_simbolos.setHorizontalHeaderItem(0, item) item = QtWidgets.QTableWidgetItem() self.tabla_simbolos.setHorizontalHeaderItem(1, item) self.label_4 = QtWidgets.QLabel(self.centralwidget) self.label_4.setGeometry(QtCore.QRect(10, 510, 47, 13)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(255, 255, 255)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.WindowText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.WindowText, brush) self.label_4.setPalette(palette) self.label_4.setObjectName("label_4") self.codigo_3d_optimizado = QtWidgets.QListWidget(self.centralwidget) self.codigo_3d_optimizado.setGeometry(QtCore.QRect(900, 100, 211, 401)) palette = QtGui.QPalette() brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.PlaceholderText, brush) brush = QtGui.QBrush(QtGui.QColor(120, 120, 120)) brush.setStyle(QtCore.Qt.SolidPattern) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Text, brush) brush = QtGui.QBrush(QtGui.QColor(0, 0, 0, 128)) brush.setStyle(QtCore.Qt.NoBrush) palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.PlaceholderText, brush) self.codigo_3d_optimizado.setPalette(palette) self.codigo_3d_optimizado.setObjectName("codigo_3d_optimizado") MainWindow.setCentralWidget(self.centralwidget) self.statusbar = QtWidgets.QStatusBar(MainWindow) self.statusbar.setObjectName("statusbar") MainWindow.setStatusBar(self.statusbar) self.menubar = QtWidgets.QMenuBar(MainWindow) self.menubar.setGeometry(QtCore.QRect(0, 0, 1349, 21)) self.menubar.setObjectName("menubar") self.menuFile = QtWidgets.QMenu(self.menubar) self.menuFile.setObjectName("menuFile") self.menuReporte = QtWidgets.QMenu(self.menubar) self.menuReporte.setObjectName("menuReporte") self.menuRun = QtWidgets.QMenu(self.menubar) self.menuRun.setObjectName("menuRun") self.menuayuda = QtWidgets.QMenu(self.menubar) self.menuayuda.setObjectName("menuayuda") self.menuAUGUS = QtWidgets.QMenu(self.menubar) self.menuAUGUS.setObjectName("menuAUGUS") MainWindow.setMenuBar(self.menubar) self.actionEjecutar = QtWidgets.QAction(MainWindow) self.actionEjecutar.setObjectName("actionEjecutar") self.actionEjecutar.triggered.connect(self.ejecutar_optimizado) self.actionDebug = QtWidgets.QAction(MainWindow) self.actionDebug.setObjectName("actionDebug") self.actionArbol_Ascendente = QtWidgets.QAction(MainWindow) self.actionArbol_Ascendente.setObjectName("actionArbol_Ascendente") ############ self.actionArbol_Ascendente.triggered.connect(self.show_ast) ############ self.actionDGA = QtWidgets.QAction(MainWindow) self.actionDGA.setObjectName("actionDGA") ############ self.actionDGA.triggered.connect(self.show_dga) ############ self.actionAbrir = QtWidgets.QAction(MainWindow) self.actionAbrir.setObjectName("actionAbrir") self.actionAbrir.triggered.connect(self.abrir_archivo) self.actionGuardar = QtWidgets.QAction(MainWindow) self.actionGuardar.setObjectName("actionGuardar") self.actionGuardar_como = QtWidgets.QAction(MainWindow) self.actionGuardar_como.setObjectName("actionGuardar_como") self.actionBuscar = QtWidgets.QAction(MainWindow) self.actionBuscar.setObjectName("actionBuscar") self.actionReemplazar = QtWidgets.QAction(MainWindow) self.actionReemplazar.setObjectName("actionReemplazar") self.actionTabla_de_Simbolos = QtWidgets.QAction(MainWindow) self.actionTabla_de_Simbolos.setObjectName("actionTabla_de_Simbolos") ############ self.actionTabla_de_Simbolos.triggered.connect(self.show_TS) ############ self.actionErrores_Lexicos_y_Sintacticos = QtWidgets.QAction( MainWindow) self.actionErrores_Lexicos_y_Sintacticos.setObjectName( "actionErrores_Lexicos_y_Sintacticos") ############ self.actionErrores_Lexicos_y_Sintacticos.triggered.connect( self.show_errores) ############ self.actionReporte_Gramatical = QtWidgets.QAction(MainWindow) self.actionReporte_Gramatical.setObjectName("actionReporte_Gramatical") ############ self.actionReporte_Gramatical.triggered.connect(self.show_RO) ############ self.actionLexicos_y_Sintacticos = QtWidgets.QAction(MainWindow) self.actionLexicos_y_Sintacticos.setObjectName( "actionLexicos_y_Sintacticos") self.actionSemanticos = QtWidgets.QAction(MainWindow) self.actionSemanticos.setObjectName("actionSemanticos") self.actionTabla_de_simbolos = QtWidgets.QAction(MainWindow) self.actionTabla_de_simbolos.setObjectName("actionTabla_de_simbolos") self.actionArbol = QtWidgets.QAction(MainWindow) self.actionArbol.setObjectName("actionArbol") self.actionGramatical = QtWidgets.QAction(MainWindow) self.actionGramatical.setObjectName("actionGramatical") self.actionGramatical.triggered.connect(self.show_RG) self.menuFile.addAction(self.actionAbrir) self.menuFile.addAction(self.actionGuardar) self.menuFile.addAction(self.actionGuardar_como) self.menuFile.addAction(self.actionBuscar) self.menuFile.addAction(self.actionReemplazar) self.menuReporte.addAction(self.actionArbol_Ascendente) self.menuReporte.addAction(self.actionDGA) self.menuReporte.addAction(self.actionTabla_de_Simbolos) self.menuReporte.addAction(self.actionErrores_Lexicos_y_Sintacticos) self.menuReporte.addAction(self.actionReporte_Gramatical) self.menuRun.addAction(self.actionEjecutar) self.menuRun.addAction(self.actionDebug) self.menuAUGUS.addAction(self.actionLexicos_y_Sintacticos) self.menuAUGUS.addAction(self.actionSemanticos) self.menuAUGUS.addAction(self.actionTabla_de_simbolos) self.menuAUGUS.addAction(self.actionArbol) self.menuReporte.addAction(self.actionGramatical) self.menubar.addAction(self.menuFile.menuAction()) self.menubar.addAction(self.menuReporte.menuAction()) self.menubar.addAction(self.menuRun.menuAction()) self.menubar.addAction(self.menuAUGUS.menuAction()) self.menubar.addAction(self.menuayuda.menuAction()) self.retranslateUi(MainWindow) self.editor.setCurrentIndex(0) QtCore.QMetaObject.connectSlotsByName(MainWindow) def on_margin_clicked(self, nmargin, nline, modifiers): tab = self.editor.widget(self.editor.currentIndex()) items = tab.children() if items[0].markersAtLine(nline) != 0: items[0].markerDelete(nline, 0) else: items[0].markerAdd(nline, 0) def Depurar_Alto_nivel(self): global traducir try: self.consola.clear() tab = self.editor.widget(self.editor.currentIndex()) items = tab.children() codigo = items[0].text() ast = Gramatica.parse(codigo) lst_errores = Gramatica.lst_errores errores = GraficarError(args=(lst_errores, "Errores"), daemon=True) errores.start() gda = GramaticaGDA.parse(codigo) nodo = GramaticaM.parse(codigo) g_ast = GraficarArbol(args=(nodo, "AST"), daemon=True) g_ast.start() g_gda = GraficarGDA(args=(gda, "GDA"), daemon=True) g_gda.start() self.codigo_3d.clear() self.codigo_3d_optimizado.clear() #self.tabla_cuadruplos.clear() traducir = Depurar(args=(ast, self.tabla_cuadruplos, self.codigo_3d, self.consola, self.tabla_simbolos, items[0], self.codigo_3d_optimizado), daemon=True) traducir.start() except: print("ERROR EN DEPURACION") def ms_help(self): msg = QtWidgets.QMessageBox(self.mw) msg.setIcon(QtWidgets.QMessageBox.Information) msg.setText("201408580") msg.setInformativeText("Andree Avalos") msg.setWindowTitle("Help") msg.setDetailedText( "Proyecto realizado para Compiladores 2 \n https://github.com/AndreeAvalos/OLC2-MINORC" ) msg.exec_() def setStep(self): try: traducir.step = True except: em = QtWidgets.QErrorMessage(self.mw) em.setWindowTitle("ERROR!!!") em.showMessage("No se ha iniciado ningun proceso") def setContinuar(self): try: traducir.continuar = True traducir.step = True except: em = QtWidgets.QErrorMessage(self.mw) em.setWindowTitle("ERROR!!!") em.showMessage("No se ha iniciado ningun proceso") def detenerEjecucion(self): try: traducir.stop() except: em = QtWidgets.QErrorMessage(self.mw) em.setWindowTitle("ERROR!!!") em.showMessage("No se ha iniciado ningun proceso") def setLines(self): 'cambiar color ide' def Traducir_Alto_nivel(self): global traducir try: self.consola.clear() #self.tabla_cuadruplos.clear() tab = self.editor.widget(self.editor.currentIndex()) items = tab.children() codigo = items[0].text() ast = Gramatica.parse(codigo) lst_errores = Gramatica.lst_errores errores = GraficarError(args=(lst_errores, "Errores"), daemon=True) errores.start() gda = GramaticaGDA.parse(codigo) nodo = GramaticaM.parse(codigo) g_ast = GraficarArbol(args=(nodo, "AST"), daemon=True) g_ast.start() g_gda = GraficarGDA(args=(gda, "GDA"), daemon=True) g_gda.start() self.codigo_3d.clear() self.codigo_3d_optimizado.clear() traducir = Traducir( args=(ast, self.tabla_cuadruplos, self.codigo_3d, self.consola, self.tabla_simbolos, self.codigo_3d_optimizado), daemon=True) traducir.start() except: print("ERROR EN EJECUCION NORMAL") def abrir_archivo(self): try: dialog = QtWidgets.QFileDialog().getOpenFileName( None, ' Open document', r"C:\Users\\", "All Files (*)") ruta = dialog[0] trozos = ruta.split("/") name = trozos[len(trozos) - 1] self.pestañas[name] = ruta file = open(ruta, 'r') codigo = file.read() tab = QtWidgets.QWidget() area = QsciScintilla(tab) area.setGeometry(QtCore.QRect(10, 10, 631, 371)) area.setObjectName("plainTextEdit") area.setFont(self.__myFont) area.setMarginType(0, QsciScintilla.NumberMargin) area.setMarginWidth(0, "00000") area.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) area.markerDefine(QsciScintilla.RightArrow, 0) area.setMarginSensitivity(0, True) area.setWrapMode(QsciScintilla.WrapWord) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.setWrapIndentMode(QsciScintilla.WrapIndentIndented) area.setEolMode(QsciScintilla.EolWindows) area.setEolVisibility(False) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.marginClicked.connect(self.on_margin_clicked) __lexer = QsciLexerCPP(area) area.setLexer(__lexer) self.editor.addTab(tab, "") area.setText(codigo) area.setObjectName("area") self.editor.addTab(tab, name) file.close() except: em = QtWidgets.QErrorMessage(self.mw) em.showMessage("Error al abrir {0}".format(name)) def agregar_tab(self): text, okPressed = QInputDialog.getText(self.centralwidget, "Nuevo archivo", "Nombre:", QLineEdit.Normal, "") if okPressed and text != '': tab = QtWidgets.QWidget() area = QsciScintilla(tab) area.setGeometry(QtCore.QRect(10, 10, 631, 371)) area.setObjectName("plainTextEdit") area.setFont(self.__myFont) area.setMarginType(0, QsciScintilla.NumberMargin) area.setMarginWidth(0, "00000") area.setMarginsForegroundColor(QtGui.QColor("#0C4B72")) area.markerDefine(QsciScintilla.RightArrow, 0) area.setMarginSensitivity(0, True) area.setWrapMode(QsciScintilla.WrapWord) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.setWrapIndentMode(QsciScintilla.WrapIndentIndented) area.setEolMode(QsciScintilla.EolWindows) area.setEolVisibility(False) area.setWrapVisualFlags(QsciScintilla.WrapFlagByText) area.marginClicked.connect(self.on_margin_clicked) __lexer = QsciLexerCPP(area) area.setLexer(__lexer) self.editor.addTab(tab, "") area.setObjectName("area") self.editor.addTab(tab, text + ".mc") def closeTab(self, index): tab = self.editor.widget(index) name = self.editor.tabText(self.editor.currentIndex()) tab.deleteLater() self.editor.removeTab(index) def guardar(self): indextab = self.editor.tabText(self.editor.currentIndex()) if indextab.split(".")[0] in self.pestañas: ruta = self.pestañas[indextab.split(".")[0]] trozos = ruta.split("/") name = indextab try: file = open(ruta, "w") tab = self.editor.widget(self.editor.currentIndex()) items = tab.children() codigo = items[0].text() file.write(codigo) file.close() except: em = QtWidgets.QErrorMessage(self.mw) em.showMessage("No fue posible guardar {0}".format(name)) else: self.gc = True self.nombre = indextab self.guardar_como() self.pestañas[self.nombre] = self.rutaTemp self.nombre = "" self.gc = False def guardar_como(self): if not self.gc: self.nombre, okPressed = QInputDialog.getText( self.centralwidget, "Nuevo archivo", "Nombre:", QLineEdit.Normal, "") carpeta = QtWidgets.QFileDialog().getExistingDirectory( self.centralwidget, "Seleccione carpeta") tname = self.nombre.split(".") name = tname[0] ruta = "{0}/{1}.mc".format(carpeta, name) self.nombre = name self.rutaTemp = ruta try: file = open(ruta, "w+") tab = self.editor.widget(self.editor.currentIndex()) items = tab.children() codigo = items[0].text() file.write(codigo) file.close() except: em = QtWidgets.QErrorMessage(self.mw) em.showMessage("No fue posible guardar {0}".format(name)) def show_ast(self): self.show("AST") def show_dga(self): self.show("GDA") def show_errores(self): self.show("Errores") def show_RO(self): self.show("reporteOptimizado") def show_TS(self): self.show("tabla_traducir") def show_RG(self): self.show("gramatical") def show(self, ruta): try: Dialog = QtWidgets.QDialog(self.mw) ui = Visor() ui.setupUi(Dialog, ruta + ".png") Dialog.show() except: em = QtWidgets.QErrorMessage(self.mw) em.setWindowTitle("ERROR!!!") em.showMessage("No se ha generado ningun reporte") def ejecutar_optimizado(self): global traducir try: file = open("codigo_optimizado.txt", "r") codigo = file.read() ast2 = GramaticaA.parse(codigo) ast3 = ast2.instruccion ts = TSA() recolector = Recolectar(ast3, ts, []) recolector.procesar() self.consola.clear() traducir = Ejecutor(args=(ast3, ts, [], "", self.consola, self.tabla_simbolos), daemon=True) traducir.start() except: print("ERROR EN EJECUCION DE OPTIMIZADO") def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MinorC")) self.new_file.setText(_translate("MainWindow", "Nuevo")) self.save_file.setText(_translate("MainWindow", "Save")) self.save_file_as.setText(_translate("MainWindow", "Save as..")) self.ejecutar.setText(_translate("MainWindow", "Ejecutar")) self.depurar.setText(_translate("MainWindow", "Depurar")) self.parar.setText(_translate("MainWindow", "Parar")) self.step_step.setText(_translate("MainWindow", "->")) self.continuar.setText(_translate("MainWindow", "|>")) self.tema.setText(_translate("MainWindow", "Lineas")) self.lineas.setText(_translate("MainWindow", "Help")) self.editor.setTabText(self.editor.indexOf(self.tab), _translate("MainWindow", "Tab 1")) self.label.setText(_translate("MainWindow", "Codigo AUGUS")) self.label_2.setText( _translate("MainWindow", "Codigo AUGUS optimizado")) item = self.tabla_cuadruplos.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "op")) item = self.tabla_cuadruplos.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "arg1")) item = self.tabla_cuadruplos.horizontalHeaderItem(2) item.setText(_translate("MainWindow", "arg2")) item = self.tabla_cuadruplos.horizontalHeaderItem(3) item.setText(_translate("MainWindow", "result")) self.label_3.setText(_translate("MainWindow", "Cuadruplos")) item = self.tabla_simbolos.horizontalHeaderItem(0) item.setText(_translate("MainWindow", "ID")) item = self.tabla_simbolos.horizontalHeaderItem(1) item.setText(_translate("MainWindow", "VALOR")) self.label_4.setText(_translate("MainWindow", "Consola")) self.menuFile.setTitle(_translate("MainWindow", "File")) self.menuReporte.setTitle(_translate("MainWindow", "Reporte")) self.menuRun.setTitle(_translate("MainWindow", "Run")) self.menuayuda.setTitle(_translate("MainWindow", "Help")) self.menuAUGUS.setTitle(_translate("MainWindow", "Augus")) self.actionEjecutar.setText(_translate("MainWindow", "Ejecutar")) self.actionDebug.setText(_translate("MainWindow", "Debug")) self.actionArbol_Ascendente.setText( _translate("MainWindow", "Arbol Ascendente")) self.actionDGA.setText(_translate("MainWindow", "GDA")) self.actionAbrir.setText(_translate("MainWindow", "Abrir")) self.actionGuardar.setText(_translate("MainWindow", "Guardar")) self.actionGuardar_como.setText( _translate("MainWindow", "Guardar como..")) self.actionBuscar.setText(_translate("MainWindow", "Buscar")) self.actionReemplazar.setText(_translate("MainWindow", "Reemplazar")) self.actionTabla_de_Simbolos.setText( _translate("MainWindow", "Tabla de Simbolos")) self.actionErrores_Lexicos_y_Sintacticos.setText( _translate("MainWindow", "Errores Lexicos y Sintacticos")) self.actionReporte_Gramatical.setText( _translate("MainWindow", "Reporte Optimizacion")) self.actionLexicos_y_Sintacticos.setText( _translate("MainWindow", "Lexicos y Sintacticos")) self.actionSemanticos.setText(_translate("MainWindow", "Semanticos")) self.actionTabla_de_simbolos.setText( _translate("MainWindow", "Tabla de simbolos")) self.actionArbol.setText(_translate("MainWindow", "Arbol")) self.actionGramatical.setText(_translate("MainWindow", "Gramatical")) self.consola.setHtml( _translate( "MainWindow", "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0//EN\" \"http://www.w3.org/TR/REC-html40/strict.dtd\">\n" "<html><head><meta name=\"qrichtext\" content=\"1\" /><style type=\"text/css\">\n" "p, li { white-space: pre-wrap; }\n" "</style></head><body style=\" font-family:\'MS Shell Dlg 2\'; font-size:8.25pt; font-weight:400; font-style:normal;\">\n" "<p style=\"-qt-paragraph-type:empty; margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; font-family:\'MS Shell Dlg 2\';\"><br /></p></body></html>" ))