Exemple #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)
Exemple #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)
Exemple #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)
Exemple #4
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
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)
Exemple #6
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()