Exemplo n.º 1
0
    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)
Exemplo n.º 2
0
 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)
Exemplo n.º 3
0
 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)
Exemplo n.º 4
0
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())
Exemplo n.º 5
0
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)
Exemplo n.º 6
0
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()
Exemplo n.º 7
0
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
Exemplo n.º 8
0
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)
Exemplo n.º 9
0
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'
Exemplo n.º 10
0
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'
Exemplo n.º 11
0
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'
Exemplo n.º 12
0
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'
Exemplo n.º 13
0
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)
Exemplo n.º 14
0
    def __init__(self):
        super().__init__()
        self.form_widget = FormWidget()
        self.setCentralWidget(self.form_widget)

        self.menubar = self.menuBar()
        self.toolbar = self.addToolBar("toolbar")

        self.file = self.menubar.addMenu("&File")
        self.edit = self.menubar.addMenu("&Edit")
        self.view = self.menubar.addMenu("&View")
        self.help = self.menubar.addMenu("&Help")

        self.helpOpen = QAction('Open')
        self.helpOpen.setShortcut('Ctrl+H')
        self.help.addAction(self.helpOpen)
        self.helpOpen.triggered.connect(lambda: os.startfile('help.pdf'))

        self.new = QAction(QIcon('newFile.png'), "New")
        self.new.setShortcut('Ctrl+N')
        self.open = QAction(QIcon('openFile.png'), "Open")
        self.open.setShortcut('Ctrl+O')
        self.save = QAction(QIcon('saveFile.png'), "Save")
        self.save.setShortcut('Ctrl+s')
        self.saveas = QAction(QIcon('saveasFile.png'), "Save As")

        self.print = QAction(QIcon('printFile.ico'), 'Print')
        self.print.setShortcut('Ctrl+P')
        self.exit = QAction('Exit')
        self.exit.setShortcut('Ctrl+Q')
        self.terminal = QAction(QIcon('terminal.png'), 'CMD')
        self.terminal.setShortcut('alt+r')

        self.file.addAction(self.new)
        self.file.addAction(self.open)
        self.file.addAction(self.save)
        self.file.addAction(self.saveas)
        self.file.addAction(self.print)
        self.file.addAction(self.exit)
        self.toolbar.addAction(self.new)
        self.toolbar.addAction(self.open)
        self.toolbar.addAction(self.save)
        self.toolbar.addAction(self.saveas)
        self.toolbar.addAction(self.print)
        self.toolbar.addAction(self.terminal)

        self.new.triggered.connect(self.newFile)
        self.open.triggered.connect(self.openFile)
        self.save.triggered.connect(self.saveFile)
        self.saveas.triggered.connect(self.saveasFile)
        self.print.triggered.connect(self.printFile)
        self.exit.triggered.connect(self.close)
        self.terminal.triggered.connect(self.Opencmd)

        self.undo = QAction('Undo')
        self.undo.setShortcut('Ctrl+Z')
        self.cut = QAction('Cut')
        self.cut.setShortcut('Ctrl+X')
        self.copy = QAction('Copy')
        self.copy.setShortcut('Ctrl+C')
        self.paste = QAction('Paste')
        self.paste.setShortcut('Ctrl+V')
        self.delete = QAction('Delete')
        self.delete.setShortcut('Delete')
        self.goto = QAction('Find')
        self.goto.setShortcut('Ctrl+F')
        self.find_and_replace = QAction('Replace')
        self.find_and_replace.setShortcut('Ctrl+R')

        self.edit.addAction(self.undo)
        self.edit.addAction(self.cut)
        self.edit.addAction(self.copy)
        self.edit.addAction(self.paste)
        self.edit.addAction(self.delete)
        self.edit.addAction(self.goto)
        self.edit.addAction(self.find_and_replace)

        self.undo.triggered.connect(self.undoText)
        self.cut.triggered.connect(self.cutText)
        self.copy.triggered.connect(self.copyText)
        self.paste.triggered.connect(self.pasteText)
        self.delete.triggered.connect(self.deleteText)
        self.goto.triggered.connect(self.findText)
        self.find_and_replace.triggered.connect(self.replaceText)

        self.Mtoolbar = QMenu('ToolBar')
        self.Mexplorer = QMenu("Explorer")
        self.Mnumbering = QMenu("Numbering")
        self.reset = QAction('Reset')

        self.reset.triggered.connect(self.resetWindow)

        self.view.addMenu(self.Mtoolbar)
        self.view.addMenu(self.Mexplorer)
        self.view.addMenu(self.Mnumbering)
        self.view.addAction(self.reset)

        self.thide = QAction("Hide")
        self.tshow = QAction("Show")

        self.ehide = QAction("Hide")
        self.eshow = QAction("Show")

        self.nhide = QAction("Hide")
        self.nshow = QAction("Show")

        self.Mtoolbar.addAction(self.thide)
        self.Mtoolbar.addAction(self.tshow)
        self.Mexplorer.addAction(self.ehide)
        self.Mexplorer.addAction(self.eshow)
        self.Mnumbering.addAction(self.nhide)
        self.Mnumbering.addAction(self.nshow)

        self.thide.triggered.connect(self.hide)
        self.tshow.triggered.connect(self.show)

        self.ehide.triggered.connect(self.hide)
        self.eshow.triggered.connect(self.show)

        self.nhide.triggered.connect(self.hide)
        self.nshow.triggered.connect(self.show)

        self.setWindowTitle("TextPad")
        self.setWindowIcon(QIcon('icon.png'))
        newEdit = QsciScintilla(self)
        newEdit.setFont(QFont('Times', 10))
        newEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        newEdit.setAutoCompletionCaseSensitivity(False)
        newEdit.setAutoCompletionReplaceWord(False)
        newEdit.setAutoCompletionSource(QsciScintilla.AcsDocument)
        newEdit.setAutoCompletionThreshold(1)
        self.form_widget.tab.addTab(newEdit, QIcon('icon.png'), "Untitled")
        self.form_widget.tab.currentWidget().setFocus()
        self.showMaximized()
        self.show()