예제 #1
0
    def __init__(self,
                 useData,
                 DATA,
                 colorScheme,
                 editorTabWidget,
                 encoding=None,
                 parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.encoding = encoding
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setFont(Global.getDefaultFont())
        self.setWrapMode(QsciScintilla.WrapWord)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 20, 20)
        mainLayout.addLayout(hbox)

        self.notify = Notification()
        hbox.addWidget(self.notify)
        self.notify.hide()

        #

        self.createContextMenu()

        self.setStyleSheet(StyleSheet.editorStyle)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # setup
        # define the font to use
        self.font = Global.getDefaultFont()
        self.font.setFixedPitch(True)
        self.font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(self.font)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        if self.encoding is None:
            self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, True)

        # Braces matching
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.DATA["fileType"] in self.useData.supportedFileTypes:
            if self.useData.SETTINGS["ShowCaretLine"] == 'True':
                self.setCaretLineVisible(True)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        self.setEdgeMode(QsciScintilla.EdgeNone)
        self.showWhiteSpaces()

        # Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QtGui.QColor("#FFFFFF"))
        self.setMarginsForegroundColor(QtGui.QColor("#666666"))

        # define markers

        self.markerDefine(
            QtGui.QPixmap(
                os.path.join("Resources", "images", "ui-button-navigation")),
            8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")),
            10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.showLineNumbers()
        self.setAutoCompletionSource(QsciScintilla.AcsDocument)

        self.setEolMode(QsciScintilla.EolUnix)

        self.matchIndicator = self.indicatorDefine(QsciScintilla.INDIC_BOX, 9)
        self.setIndicatorForegroundColor(QtGui.QColor("#FFCC00"),
                                         self.matchIndicator)
        self.setIndicatorDrawUnder(True, self.matchIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(QtGui.QColor("#FFDB4A"),
                                         self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.setAutoCompletion()

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        self.lexer = self.colorScheme.styleEditor(self)

        self.install_shortcuts()
예제 #2
0
    def __init__(self, useData, DATA, colorScheme, editorTabWidget,
                 encoding=None, parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.encoding = encoding
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setFont(Global.getDefaultFont())
        self.setWrapMode(QsciScintilla.WrapWord)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 20, 20)
        mainLayout.addLayout(hbox)

        self.notify = Notification()
        hbox.addWidget(self.notify)
        self.notify.hide()

        #

        self.createContextMenu()

        self.setStyleSheet(StyleSheet.editorStyle)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # setup
        # define the font to use
        self.font = Global.getDefaultFont()
        self.font.setFixedPitch(True)
        self.font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(self.font)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        if self.encoding is None:
            self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, True)

        # Braces matching
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.DATA["fileType"] in self.useData.supportedFileTypes:
            if self.useData.SETTINGS["ShowCaretLine"] == 'True':
                self.setCaretLineVisible(True)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        self.setEdgeMode(QsciScintilla.EdgeNone)
        self.showWhiteSpaces()

        # Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QtGui.QColor("#FFFFFF"))
        self.setMarginsForegroundColor(QtGui.QColor("#666666"))

        # define markers

        self.markerDefine(QtGui.QPixmap(
            os.path.join("Resources", "images", "ui-button-navigation")), 8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")), 10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.showLineNumbers()
        self.setAutoCompletionSource(QsciScintilla.AcsDocument)

        self.setEolMode(QsciScintilla.EolUnix)

        self.matchIndicator = self.indicatorDefine(QsciScintilla.INDIC_BOX, 9)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFCC00"), self.matchIndicator)
        self.setIndicatorDrawUnder(True, self.matchIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFDB4A"), self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.setAutoCompletion()

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        self.lexer = self.colorScheme.styleEditor(self)

        self.install_shortcuts()
예제 #3
0
class TextEditor(BaseScintilla):
    def __init__(self,
                 useData,
                 DATA,
                 colorScheme,
                 editorTabWidget,
                 encoding=None,
                 parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.encoding = encoding
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setFont(Global.getDefaultFont())
        self.setWrapMode(QsciScintilla.WrapWord)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 20, 20)
        mainLayout.addLayout(hbox)

        self.notify = Notification()
        hbox.addWidget(self.notify)
        self.notify.hide()

        #

        self.createContextMenu()

        self.setStyleSheet(StyleSheet.editorStyle)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # setup
        # define the font to use
        self.font = Global.getDefaultFont()
        self.font.setFixedPitch(True)
        self.font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(self.font)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        if self.encoding is None:
            self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, True)

        # Braces matching
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.DATA["fileType"] in self.useData.supportedFileTypes:
            if self.useData.SETTINGS["ShowCaretLine"] == 'True':
                self.setCaretLineVisible(True)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        self.setEdgeMode(QsciScintilla.EdgeNone)
        self.showWhiteSpaces()

        # Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QtGui.QColor("#FFFFFF"))
        self.setMarginsForegroundColor(QtGui.QColor("#666666"))

        # define markers

        self.markerDefine(
            QtGui.QPixmap(
                os.path.join("Resources", "images", "ui-button-navigation")),
            8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")),
            10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.showLineNumbers()
        self.setAutoCompletionSource(QsciScintilla.AcsDocument)

        self.setEolMode(QsciScintilla.EolUnix)

        self.matchIndicator = self.indicatorDefine(QsciScintilla.INDIC_BOX, 9)
        self.setIndicatorForegroundColor(QtGui.QColor("#FFCC00"),
                                         self.matchIndicator)
        self.setIndicatorDrawUnder(True, self.matchIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(QtGui.QColor("#FFDB4A"),
                                         self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.setAutoCompletion()

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        self.lexer = self.colorScheme.styleEditor(self)

        self.install_shortcuts()

    def updateLexer(self, lexer):
        self.lexer = lexer
        self.setLexer(lexer)

    def createContextMenu(self):
        self.cutAct = QtGui.QAction("Cut",
                                    self,
                                    shortcut=QtGui.QKeySequence.Cut,
                                    statusTip="Cut selected text",
                                    triggered=self.cut)

        self.copyAct = QtGui.QAction("Copy",
                                     self,
                                     shortcut=QtGui.QKeySequence.Copy,
                                     statusTip="Copy selected text",
                                     triggered=self.copy)

        self.pasteAct = QtGui.QAction("Paste",
                                      self,
                                      shortcut=QtGui.QKeySequence.Paste,
                                      statusTip="Paste text from clipboard",
                                      triggered=self.paste)

        self.deleteAct = QtGui.QAction("Delete",
                                       self,
                                       shortcut=QtGui.QKeySequence.Delete,
                                       statusTip="Delete Selection",
                                       triggered=self.removeSelectedText)

        self.selectAllAct = QtGui.QAction(
            "Select All",
            self,
            shortcut=QtGui.QKeySequence.SelectAll,
            statusTip="Select All",
            triggered=self.selectAllText)

        self.selectToMatchingBraceAct = \
            QtGui.QAction(
                QtGui.QIcon(
                    os.path.join("Resources", "images", "text_select")),
                "Select to Matching Brace", self,
                statusTip="Select to Matching Brace",
                          triggered=self.selectToMatchingBrace)

        self.zoomAct = QtGui.QAction(QtGui.QIcon(
            os.path.join("Resources", "images", "zoom")),
                                     "Zoom",
                                     self,
                                     statusTip="Zoom",
                                     triggered=self.showZoomWidget)

        self.contextMenu = QtGui.QMenu()
        self.contextMenu.addAction(self.cutAct)
        self.contextMenu.addAction(self.copyAct)
        self.contextMenu.addAction(self.pasteAct)
        self.contextMenu.addAction(self.deleteAct)
        self.contextMenu.addAction(self.selectAllAct)
        self.contextMenu.addAction(self.selectToMatchingBraceAct)
        self.contextMenu.addSeparator()
        self.viewMenu = self.contextMenu.addMenu("View")
        self.viewMenu.addAction(self.editorTabWidget.vSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.hSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.noSplitEditorAct)
        self.viewMenu.addSeparator()
        self.viewMenu.addAction(self.zoomAct)

    def setAutoCompletion(self):
        if self.useData.SETTINGS["EnableAutoCompletion"] == "True":
            self.setAutoCompletionSource(QsciScintilla.AcsDocument)
        else:
            self.setAutoCompletionSource(QsciScintilla.AcsNone)

    def contextMenuEvent(self, event):
        state = self.hasSelectedText()

        self.copyAct.setEnabled(state)
        self.cutAct.setEnabled(state)
        self.deleteAct.setEnabled(state)

        self.contextMenu.exec_(event.globalPos())

    def undoActModifier(self):
        state = self.isUndoAvailable()
        self.editorTabWidget.undoAct.setEnabled(state)

    def redoActModifier(self):
        state = self.isRedoAvailable()
        self.editorTabWidget.redoAct.setEnabled(state)

    def copyActModifier(self):
        state = self.hasSelectedText()
        self.editorTabWidget.copyAct.setEnabled(state)
        self.editorTabWidget.cutAct.setEnabled(state)

    def updateLineCount(self):
        lines = self.lines()
        self.editorTabWidget.updateLinesCount.emit(lines)

    def selectAllText(self):
        self.selectAll()

    def showZoomWidget(self):
        self.zoomWidget.show()

    def showLine(self, lineNum, highlight=True):
        if highlight:
            self.setSelection(lineNum, 0, lineNum,
                              self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def showWhiteSpaces(self):
        if self.useData.SETTINGS["ShowWhiteSpaces"] == 'True':
            self.setWhitespaceVisibility(QsciScintilla.WsVisible)
        else:
            self.setWhitespaceVisibility(QsciScintilla.WsInvisible)

    def findMarkerDown(self):
        lineNum = self.markerFindNext(self.getCursorPosition()[0] + 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindNext(0, 256)
        self.setSelection(lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def findMarkerUp(self):
        lineNum = self.markerFindPrevious(self.getCursorPosition()[0] - 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindPrevious(self.lines(), 256)
        self.setSelection(lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def removeMarkers(self):
        self.markerDeleteAll(8)

    def findNextBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindNext(cursorLine + 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindNext(0, 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def findPreviousBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindPrevious(cursorLine - 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindPrevious(self.lines(), 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def toggleBookmark(self, nmargin, nline, modifiers=None):
        if self.markersAtLine(nline) == 0:
            handle = self.markerAdd(nline, 8)
            self.DATA["bookmarkList"].append(handle)
        else:
            for handle in self.DATA["bookmarkList"]:
                if self.markerLine(handle) == nline:
                    self.DATA["bookmarkList"].remove(handle)
                    self.markerDeleteHandle(handle)

        markersExist = self.bookmarksExist()
        self.editorTabWidget.enableBookmarkButtons(markersExist)

    def bookmarksExist(self):
        markersExist = (len(self.DATA["bookmarkList"]) > 0)
        return markersExist

    def getBookmarks(self):
        bookmarkLines = []
        for handle in self.DATA["bookmarkList"]:
            line = self.markerLine(handle)
            bookmarkLines.append(line)

        return bookmarkLines

    def removeBookmarks(self):
        if len(self.DATA["bookmarkList"]) > 0:
            self.DATA["bookmarkList"] = []
            self.markerDeleteAll(8)

    def notify(self, mess):
        self.infoBar.showMessage(mess)

    def install_shortcuts(self):
        self.updateShortcuts(self.useData)

        shortcuts = self.useData.CUSTOM_DEFAULT_SHORTCUTS

        self.cutAct.setShortcut(shortcuts["Editor"]["Cut-Selection"][0])
        self.copyAct.setShortcut(shortcuts["Editor"]["Copy-Selection"][0])
        self.pasteAct.setShortcut(shortcuts["Editor"]["Paste"][0])

        self.shortNextBookmark = QtGui.QShortcut(
            shortcuts["Editor"]["Next-Bookmark"][0], self)
        self.shortNextBookmark.activated.connect(self.findNextBookmark)

        self.shortPreviousBookmark = QtGui.QShortcut(
            shortcuts["Editor"]["Previous-Bookmark"][0], self)
        self.shortPreviousBookmark.activated.connect(self.findPreviousBookmark)

        self.shortZoomIn = QtGui.QShortcut(shortcuts["Editor"]["Zoom-In"][0],
                                           self)
        self.shortZoomIn.activated.connect(self.zoomWidget.zoomIn)

        self.shortZoomOut = QtGui.QShortcut(shortcuts["Editor"]["Zoom-Out"][0],
                                            self)
        self.shortZoomOut.activated.connect(self.zoomWidget.zoomOut)
예제 #4
0
class TextEditor(BaseScintilla):

    def __init__(self, useData, DATA, colorScheme, editorTabWidget,
                 encoding=None, parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.encoding = encoding
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setFont(Global.getDefaultFont())
        self.setWrapMode(QsciScintilla.WrapWord)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 20, 20)
        mainLayout.addLayout(hbox)

        self.notify = Notification()
        hbox.addWidget(self.notify)
        self.notify.hide()

        #

        self.createContextMenu()

        self.setStyleSheet(StyleSheet.editorStyle)
        self.setAttribute(QtCore.Qt.WA_DeleteOnClose)

        # setup
        # define the font to use
        self.font = Global.getDefaultFont()
        self.font.setFixedPitch(True)
        self.font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(self.font)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        if self.encoding is None:
            self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
        # Clickable margin 1 for showing markers
        self.setMarginSensitivity(1, True)

        # Braces matching
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.DATA["fileType"] in self.useData.supportedFileTypes:
            if self.useData.SETTINGS["ShowCaretLine"] == 'True':
                self.setCaretLineVisible(True)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        self.setEdgeMode(QsciScintilla.EdgeNone)
        self.showWhiteSpaces()

        # Margins colors
        # line numbers margin
        self.setMarginsBackgroundColor(QtGui.QColor("#FFFFFF"))
        self.setMarginsForegroundColor(QtGui.QColor("#666666"))

        # define markers

        self.markerDefine(QtGui.QPixmap(
            os.path.join("Resources", "images", "ui-button-navigation")), 8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")), 10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.showLineNumbers()
        self.setAutoCompletionSource(QsciScintilla.AcsDocument)

        self.setEolMode(QsciScintilla.EolUnix)

        self.matchIndicator = self.indicatorDefine(QsciScintilla.INDIC_BOX, 9)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFCC00"), self.matchIndicator)
        self.setIndicatorDrawUnder(True, self.matchIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFDB4A"), self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.setAutoCompletion()

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        self.lexer = self.colorScheme.styleEditor(self)

        self.install_shortcuts()

    def updateLexer(self, lexer):
        self.lexer = lexer
        self.setLexer(lexer)

    def createContextMenu(self):
        self.cutAct = QtGui.QAction(
            "Cut", self, shortcut=QtGui.QKeySequence.Cut,
            statusTip="Cut selected text", triggered=self.cut)

        self.copyAct = QtGui.QAction(
            "Copy", self, shortcut=QtGui.QKeySequence.Copy,
            statusTip="Copy selected text", triggered=self.copy)

        self.pasteAct = QtGui.QAction(
            "Paste", self, shortcut=QtGui.QKeySequence.Paste,
            statusTip="Paste text from clipboard",
            triggered=self.paste)

        self.deleteAct = QtGui.QAction(
            "Delete", self, shortcut=QtGui.QKeySequence.Delete,
            statusTip="Delete Selection",
            triggered=self.removeSelectedText)

        self.selectAllAct = QtGui.QAction("Select All", self,
                                          shortcut=QtGui.QKeySequence.SelectAll,
                                          statusTip="Select All",
                                          triggered=self.selectAllText)

        self.selectToMatchingBraceAct = \
            QtGui.QAction(
                QtGui.QIcon(
                    os.path.join("Resources", "images", "text_select")),
                "Select to Matching Brace", self,
                statusTip="Select to Matching Brace",
                          triggered=self.selectToMatchingBrace)

        self.zoomAct = QtGui.QAction(
            QtGui.QIcon(os.path.join("Resources", "images", "zoom")),
            "Zoom", self,
            statusTip="Zoom", triggered=self.showZoomWidget)

        self.contextMenu = QtGui.QMenu()
        self.contextMenu.addAction(self.cutAct)
        self.contextMenu.addAction(self.copyAct)
        self.contextMenu.addAction(self.pasteAct)
        self.contextMenu.addAction(self.deleteAct)
        self.contextMenu.addAction(self.selectAllAct)
        self.contextMenu.addAction(self.selectToMatchingBraceAct)
        self.contextMenu.addSeparator()
        self.viewMenu = self.contextMenu.addMenu("View")
        self.viewMenu.addAction(self.editorTabWidget.vSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.hSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.noSplitEditorAct)
        self.viewMenu.addSeparator()
        self.viewMenu.addAction(self.zoomAct)

    def setAutoCompletion(self):
        if self.useData.SETTINGS["EnableAutoCompletion"] == "True":
            self.setAutoCompletionSource(QsciScintilla.AcsDocument)
        else:
            self.setAutoCompletionSource(QsciScintilla.AcsNone)

    def contextMenuEvent(self, event):
        state = self.hasSelectedText()

        self.copyAct.setEnabled(state)
        self.cutAct.setEnabled(state)
        self.deleteAct.setEnabled(state)

        self.contextMenu.exec_(event.globalPos())

    def undoActModifier(self):
        state = self.isUndoAvailable()
        self.editorTabWidget.undoAct.setEnabled(state)

    def redoActModifier(self):
        state = self.isRedoAvailable()
        self.editorTabWidget.redoAct.setEnabled(state)

    def copyActModifier(self):
        state = self.hasSelectedText()
        self.editorTabWidget.copyAct.setEnabled(state)
        self.editorTabWidget.cutAct.setEnabled(state)

    def updateLineCount(self):
        lines = self.lines()
        self.editorTabWidget.updateLinesCount.emit(lines)

    def selectAllText(self):
        self.selectAll()

    def showZoomWidget(self):
        self.zoomWidget.show()

    def showLine(self, lineNum, highlight=True):
        if highlight:
            self.setSelection(
                lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def showWhiteSpaces(self):
        if self.useData.SETTINGS["ShowWhiteSpaces"] == 'True':
            self.setWhitespaceVisibility(QsciScintilla.WsVisible)
        else:
            self.setWhitespaceVisibility(QsciScintilla.WsInvisible)

    def findMarkerDown(self):
        lineNum = self.markerFindNext(self.getCursorPosition()[0] + 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindNext(0, 256)
        self.setSelection(lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def findMarkerUp(self):
        lineNum = self.markerFindPrevious(self.getCursorPosition()[0] - 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindPrevious(self.lines(), 256)
        self.setSelection(lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def removeMarkers(self):
        self.markerDeleteAll(8)

    def findNextBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindNext(cursorLine + 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindNext(0, 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def findPreviousBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindPrevious(cursorLine - 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindPrevious(self.lines(), 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def toggleBookmark(self, nmargin, nline, modifiers=None):
        if self.markersAtLine(nline) == 0:
            handle = self.markerAdd(nline, 8)
            self.DATA["bookmarkList"].append(handle)
        else:
            for handle in self.DATA["bookmarkList"]:
                if self.markerLine(handle) == nline:
                    self.DATA["bookmarkList"].remove(handle)
                    self.markerDeleteHandle(handle)

        markersExist = self.bookmarksExist()
        self.editorTabWidget.enableBookmarkButtons(markersExist)

    def bookmarksExist(self):
        markersExist = (len(self.DATA["bookmarkList"]) > 0)
        return markersExist

    def getBookmarks(self):
        bookmarkLines = []
        for handle in self.DATA["bookmarkList"]:
            line = self.markerLine(handle)
            bookmarkLines.append(line)

        return bookmarkLines

    def removeBookmarks(self):
        if len(self.DATA["bookmarkList"]) > 0:
            self.DATA["bookmarkList"] = []
            self.markerDeleteAll(8)

    def notify(self, mess):
        self.infoBar.showMessage(mess)

    def install_shortcuts(self):
        self.updateShortcuts(self.useData)

        shortcuts = self.useData.CUSTOM_DEFAULT_SHORTCUTS

        self.cutAct.setShortcut(shortcuts["Editor"]["Cut-Selection"][0])
        self.copyAct.setShortcut(shortcuts["Editor"]["Copy-Selection"][0])
        self.pasteAct.setShortcut(shortcuts["Editor"]["Paste"][0])

        self.shortNextBookmark = QtGui.QShortcut(
            shortcuts["Editor"]["Next-Bookmark"][0], self)
        self.shortNextBookmark.activated.connect(self.findNextBookmark)

        self.shortPreviousBookmark = QtGui.QShortcut(
            shortcuts["Editor"]["Previous-Bookmark"][0], self)
        self.shortPreviousBookmark.activated.connect(self.findPreviousBookmark)

        self.shortZoomIn = QtGui.QShortcut(
            shortcuts["Editor"]["Zoom-In"][0], self)
        self.shortZoomIn.activated.connect(self.zoomWidget.zoomIn)

        self.shortZoomOut = QtGui.QShortcut(
            shortcuts["Editor"]["Zoom-Out"][0], self)
        self.shortZoomOut.activated.connect(self.zoomWidget.zoomOut)
예제 #5
0
    def __init__(self, useData, refactor, colorScheme,
                 DATA, editorTabWidget, parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.refactor = refactor
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setObjectName("editor")
        self.enableMarkOccurrence(useData)

        self.setMouseTracking(True)
        self.middleMousePressed = False
        self.mousePosition = QtCore.QPointF()

        self.autoCompletionThread = AutoCompletionThread()
        self.autoCompletionThread.completionsAvailable.connect(self.showCompletions)

        self.docThread = DocThread()
        self.docThread.docAvailable.connect(
            self.showDoc)

        self.docThreadTimer = QtCore.QTimer()
        self.docThreadTimer.setSingleShot(True)
        self.docThreadTimer.timeout.connect(self.getDoc)

        self.tokenizeThread = TokenizeThread()
        self.tokenizeThread.finished.connect(
            self.displayTokenLines)

        self.tokenizeTimer = QtCore.QTimer()
        self.tokenizeTimer.setSingleShot(True)
        self.tokenizeTimer.timeout.connect(self.getOperationTokens)

        self.completionThreadTimer = QtCore.QTimer()
        self.completionThreadTimer.setSingleShot(True)
        self.completionThreadTimer.timeout.connect(self.startCompletion)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 10, 20)
        mainLayout.addLayout(hbox)

        self.notification = Notification()
        hbox.addWidget(self.notification)
        self.notification.hide()

        #

        self.createActions()

        self.setAutoCompletion()

        " Initialises indicators "
        self.syntaxErrorIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_SQUIGGLE, 8)
        self.setIndicatorForegroundColor(QtGui.QColor(
            "#FF0000"), self.syntaxErrorIndicator)
        self.setIndicatorDrawUnder(True, self.syntaxErrorIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFDB4A"), self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.userListActivated.connect(self.insertText)

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.textChanged.connect(self.startTokenizeTimer)
        self.textChanged.connect(self.startCompletionTimer)

        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        # define the font to use
        font = QtGui.QFont("Courier New")
        font.setFixedPitch(True)
        font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(font)

        self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
#        self.setAnnotationDisplay(QsciScintilla.AnnotationStandard)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        if self.useData.SETTINGS["EnableFolding"] == "True":
            self.setFolding(QsciScintilla.BoxedTreeFoldStyle, 2)

        # Braces matching
        # TODO: Causes flicker when selecting text. I suspect it has
        # the layout and widgets placed on top of it
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.useData.SETTINGS["ShowEdgeLine"] == 'True':
            if self.useData.SETTINGS["EdgeMode"] == 'Line':
                self.setEdgeMode(QsciScintilla.EdgeLine)
            elif self.useData.SETTINGS["EdgeMode"] == 'Background':
                self.setEdgeMode(QsciScintilla.EdgeBackground)
                
        if self.useData.SETTINGS["LineWrap"] == 'True':
            if self.useData.SETTINGS["WrapMode"] == 'Word':
                self.setWrapMode(QsciScintilla.WrapWord)
            elif self.useData.SETTINGS["WrapMode"] == 'Character':
                self.setWrapMode(QsciScintilla.WrapCharacter)
            elif self.useData.SETTINGS["WrapMode"] == 'Whitespace':
                self.setWrapMode(QsciScintilla.WrapWhitespace)

        if self.useData.SETTINGS["ShowCaretLine"] == 'True':
            self.setCaretLineVisible(True)

        self.showWhiteSpaces()
        # set annotation display
        # the annotation font can be changed by changing the default lexer font
        self.setAnnotationDisplay(QsciScintilla.AnnotationBoxed)

        # Edge Mode shows a vetical bar at specific number of chars
        if self.useData.SETTINGS["ShowEdgeLine"] == 'True':
            if self.useData.SETTINGS['EdgeMode'] == "Line":
                self.setEdgeMode(QsciScintilla.EdgeLine)
            else:
                self.setEdgeMode(QsciScintilla.EdgeBackground)
        self.setEdgeColumn(int(self.useData.SETTINGS["EdgeColumn"]))

        # define markers
        # the background markers will not show until the editor has focus
        self.breakpointMarker = self.markerDefine(QsciScintilla.Background)
        self.setMarkerForegroundColor(QtGui.QColor("#000000"),
                                      self.breakpointMarker)
        self.setMarkerBackgroundColor(QtGui.QColor("#ffe1e1"),
                                      self.breakpointMarker)

        self.markerDefine(QtGui.QPixmap(
            os.path.join("Resources", "images", "ui-button-navigation")), 8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")), 10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.markerDefine(QsciScintilla.VerticalLine, 11)
        self.setMarkerBackgroundColor(QtGui.QColor("#EEEE11"), 11)
        self.setMarkerForegroundColor(QtGui.QColor("#EEEE11"), 11)
        self.setMarginWidth(3, self.fontMetrics.width("0"))

        mask = (1 << 8) | (1 << 9)
        self.setMarginMarkerMask(1, mask)
        self.setMarginSensitivity(1, True)
        mask = (1 << 11)
        self.setMarginMarkerMask(3, mask)

        self.showLineNumbers()
        self.setMarkOperationalLines()

        if self.useData.SETTINGS["ShowCaretLine"] == 'True':
            self.setCaretLineVisible(True)

        self.lexer = self.colorScheme.styleEditor(self)
        self.setStyleSheet(StyleSheet.editorStyle)

        self.setKeymap()
예제 #6
0
class CodeEditor(BaseScintilla):

    def __init__(self, useData, refactor, colorScheme,
                 DATA, editorTabWidget, parent=None):
        BaseScintilla.__init__(self, parent)

        self.useData = useData
        self.refactor = refactor
        self.DATA = DATA
        self.colorScheme = colorScheme
        self.editorTabWidget = editorTabWidget

        self.setObjectName("editor")
        self.enableMarkOccurrence(useData)

        self.setMouseTracking(True)
        self.middleMousePressed = False
        self.mousePosition = QtCore.QPointF()

        self.autoCompletionThread = AutoCompletionThread()
        self.autoCompletionThread.completionsAvailable.connect(self.showCompletions)

        self.docThread = DocThread()
        self.docThread.docAvailable.connect(
            self.showDoc)

        self.docThreadTimer = QtCore.QTimer()
        self.docThreadTimer.setSingleShot(True)
        self.docThreadTimer.timeout.connect(self.getDoc)

        self.tokenizeThread = TokenizeThread()
        self.tokenizeThread.finished.connect(
            self.displayTokenLines)

        self.tokenizeTimer = QtCore.QTimer()
        self.tokenizeTimer.setSingleShot(True)
        self.tokenizeTimer.timeout.connect(self.getOperationTokens)

        self.completionThreadTimer = QtCore.QTimer()
        self.completionThreadTimer.setSingleShot(True)
        self.completionThreadTimer.timeout.connect(self.startCompletion)

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setMargin(0)
        self.setLayout(mainLayout)

        mainLayout.addStretch(1)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(0, 0, 20, 0)
        mainLayout.addLayout(hbox)

        self.zoomWidget = ZoomWidget(self.useData, self)
        hbox.addWidget(self.zoomWidget)

        #

        hbox = QtGui.QHBoxLayout()
        hbox.addStretch(1)
        hbox.setContentsMargins(5, 0, 10, 20)
        mainLayout.addLayout(hbox)

        self.notification = Notification()
        hbox.addWidget(self.notification)
        self.notification.hide()

        #

        self.createActions()

        self.setAutoCompletion()

        " Initialises indicators "
        self.syntaxErrorIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_SQUIGGLE, 8)
        self.setIndicatorForegroundColor(QtGui.QColor(
            "#FF0000"), self.syntaxErrorIndicator)
        self.setIndicatorDrawUnder(True, self.syntaxErrorIndicator)

        self.searchIndicator = self.indicatorDefine(
            QsciScintilla.INDIC_ROUNDBOX, 10)
        self.setIndicatorForegroundColor(
            QtGui.QColor("#FFDB4A"), self.searchIndicator)
        self.setIndicatorDrawUnder(True, self.searchIndicator)

        self.userListActivated.connect(self.insertText)

        self.copyAvailableTimer = QtCore.QTimer()
        self.copyAvailableTimer.setSingleShot(True)
        self.copyAvailableTimer.setInterval(0)
        self.copyAvailableTimer.timeout.connect(self.copyActModifier)

        self.copyAvailable.connect(self.copyAvailableTimer.start)

        self.textChangedTimer = QtCore.QTimer()
        self.textChangedTimer.setSingleShot(True)
        self.textChangedTimer.setInterval(0)
        self.textChangedTimer.timeout.connect(self.undoActModifier)
        self.textChangedTimer.timeout.connect(self.redoActModifier)

        self.textChanged.connect(self.textChangedTimer.start)
        self.textChanged.connect(self.startTokenizeTimer)
        self.textChanged.connect(self.startCompletionTimer)

        self.linesChanged.connect(self.updateLineCount)
        self.marginClicked.connect(self.toggleBookmark)

        # define the font to use
        font = QtGui.QFont("Courier New")
        font.setFixedPitch(True)
        font.setPointSize(10)
        # the font metrics here will help
        # building the margin width later
        self.fontMetrics = QtGui.QFontMetrics(font)

        self.setUtf8(True)
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setBackspaceUnindents(True)
        self.setIndentationWidth(4)
        self.setTabWidth(4)
#        self.setAnnotationDisplay(QsciScintilla.AnnotationStandard)

        # Line numbers
        # conventionnaly, margin 0 is for line numbers
        self.setMarginWidth(0, self.fontMetrics.width("0000") + 5)

        self.setAutoCompletionReplaceWord(True)
        # minimum number of letters to be typed before list is displayed
        self.setAutoCompletionThreshold(2)

        if self.useData.SETTINGS["EnableFolding"] == "True":
            self.setFolding(QsciScintilla.BoxedTreeFoldStyle, 2)

        # Braces matching
        # TODO: Causes flicker when selecting text. I suspect it has
        # the layout and widgets placed on top of it
        if self.useData.SETTINGS["MatchBraces"] == "True":
            self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        if self.useData.SETTINGS["ShowEdgeLine"] == 'True':
            if self.useData.SETTINGS["EdgeMode"] == 'Line':
                self.setEdgeMode(QsciScintilla.EdgeLine)
            elif self.useData.SETTINGS["EdgeMode"] == 'Background':
                self.setEdgeMode(QsciScintilla.EdgeBackground)
                
        if self.useData.SETTINGS["LineWrap"] == 'True':
            if self.useData.SETTINGS["WrapMode"] == 'Word':
                self.setWrapMode(QsciScintilla.WrapWord)
            elif self.useData.SETTINGS["WrapMode"] == 'Character':
                self.setWrapMode(QsciScintilla.WrapCharacter)
            elif self.useData.SETTINGS["WrapMode"] == 'Whitespace':
                self.setWrapMode(QsciScintilla.WrapWhitespace)

        if self.useData.SETTINGS["ShowCaretLine"] == 'True':
            self.setCaretLineVisible(True)

        self.showWhiteSpaces()
        # set annotation display
        # the annotation font can be changed by changing the default lexer font
        self.setAnnotationDisplay(QsciScintilla.AnnotationBoxed)

        # Edge Mode shows a vetical bar at specific number of chars
        if self.useData.SETTINGS["ShowEdgeLine"] == 'True':
            if self.useData.SETTINGS['EdgeMode'] == "Line":
                self.setEdgeMode(QsciScintilla.EdgeLine)
            else:
                self.setEdgeMode(QsciScintilla.EdgeBackground)
        self.setEdgeColumn(int(self.useData.SETTINGS["EdgeColumn"]))

        # define markers
        # the background markers will not show until the editor has focus
        self.breakpointMarker = self.markerDefine(QsciScintilla.Background)
        self.setMarkerForegroundColor(QtGui.QColor("#000000"),
                                      self.breakpointMarker)
        self.setMarkerBackgroundColor(QtGui.QColor("#ffe1e1"),
                                      self.breakpointMarker)

        self.markerDefine(QtGui.QPixmap(
            os.path.join("Resources", "images", "ui-button-navigation")), 8)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 8)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "err_mark")), 9)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 9)

        self.markerDefine(
            QtGui.QPixmap(os.path.join("Resources", "images", "brk_point")), 10)
        self.setMarkerBackgroundColor(QtGui.QColor("#ee1111"), 10)

        self.markerDefine(QsciScintilla.VerticalLine, 11)
        self.setMarkerBackgroundColor(QtGui.QColor("#EEEE11"), 11)
        self.setMarkerForegroundColor(QtGui.QColor("#EEEE11"), 11)
        self.setMarginWidth(3, self.fontMetrics.width("0"))

        mask = (1 << 8) | (1 << 9)
        self.setMarginMarkerMask(1, mask)
        self.setMarginSensitivity(1, True)
        mask = (1 << 11)
        self.setMarginMarkerMask(3, mask)

        self.showLineNumbers()
        self.setMarkOperationalLines()

        if self.useData.SETTINGS["ShowCaretLine"] == 'True':
            self.setCaretLineVisible(True)

        self.lexer = self.colorScheme.styleEditor(self)
        self.setStyleSheet(StyleSheet.editorStyle)

        self.setKeymap()
        
    def startTokenizeTimer(self):
        self.tokenizeTimer.start(1000)
        
    def startDocTimer(self):
        self.docThreadTimer.start(500)
        
    def startCompletionTimer(self):
        self.completionThreadTimer.start(500)

    def getOperationTokens(self):
        if self.useData.SETTINGS['MarkOperationalLines'] == 'True':
            self.tokenizeThread.tokenize(self.text())

    def displayTokenLines(self):
        self.markerDeleteAll(11)

        for line in self.tokenizeThread.tokenList:
            self.markerAdd(line, 11)

    def showDoc(self, doc, pos):
        if self.isListActive():
            return
        if doc is not None:
            QtGui.QToolTip.showText(self.lastHoverPos, doc, self)

    def getDoc(self):
        self.docThread.doc(
            self.refactor.getProject(), self.text(), self.hoverOffset)

    def mouseReleaseEvent(self, event):
        self.middleMousePressed = False
        super(CodeEditor, self).mouseReleaseEvent(event)

    def mousePressEvent(self, event):
        button = event.button()
        if button == QtCore.Qt.MidButton or button == QtCore.Qt.MiddleButton:
            self.middleMousePressed = True
        else:
            self.middleMousePressed = False

        super(CodeEditor, self).mousePressEvent(event)

    def mouseMoveEvent(self, event):
        if self.useData.SETTINGS["DocOnHover"] == "True":
            self.lastHoverPos = event.globalPos()
            self.hoverOffset = self.positionFromPoint(event.pos())

            QtGui.QToolTip.hideText()
            self.startDocTimer()

        # resize view if middle mouse button is held down
        if self.middleMousePressed:
            pos = event.pos()
            delta = pos - self.mousePosition

            x = delta.x()
            y = delta.y()
            if x > 0:
                x = 1
            elif x < 0:
                x = -1
            if y > 0:
                y = 1
            elif y < 0:
                y = -1

            self.editorTabWidget.resizeView(x, y)

        self.mousePosition = event.posF()
        super(CodeEditor, self).mouseMoveEvent(event)

    def createActions(self):
        self.cutAct = QtGui.QAction(
            "Cut", self,
            statusTip="Cut selected text", triggered=self.cut)

        self.copyAct = QtGui.QAction(
            "Copy", self,
            statusTip="Copy selected text", triggered=self.copy)

        self.pasteAct = QtGui.QAction(
            "Paste", self,
            statusTip="Paste text from clipboard",
            triggered=self.paste)

        self.selectToMatchingBraceAct = \
            QtGui.QAction(
                "Select to Matching Brace", self,
                statusTip="Select to Matching Brace",
                          triggered=self.selectToMatchingBrace)

        self.snippetsAct = \
            QtGui.QAction(
                QtGui.QIcon(os.path.join("Resources", "images", "edit2")),
                "Insert Snippet...", self,
                statusTip="Insert Snippet...",
                          triggered=self.showSnippets)

        self.toggleBookmarkAct = \
            QtGui.QAction(
                "Toggle Bookmark", self,
                statusTip="Toggle Bookmark",
                triggered=self._toggleBookmark)

        self.toggleBreakpointAct = \
            QtGui.QAction(
                "Toggle Line Breakpoint", self,
                statusTip="Toggle Line Breakpoint",
                triggered=self.toggleLineBreakpoint)

        self.takeSnapshotAct = \
            QtGui.QAction("Take Snapshot", self,
                          statusTip="Take Snapshot",
                          triggered=self.takeSnapshot)

        self.zoomAct = QtGui.QAction(
            QtGui.QIcon(os.path.join("Resources", "images", "zoom")),
            "Zoom", self,
            statusTip="Zoom", triggered=self.showZoomWidget)

        self.indentationGuideAct = \
            QtGui.QAction(
                "Indentation Guide", self,
                statusTip="Indentation Guide",
                          triggered=self.showIndentationGuide)
        self.indentationGuideAct.setCheckable(True)

        self.contextMenu = QtGui.QMenu()
        self.contextMenu.addAction(self.snippetsAct)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.cutAct)
        self.contextMenu.addAction(self.copyAct)
        self.contextMenu.addAction(self.pasteAct)
        self.contextMenu.addAction(self.selectToMatchingBraceAct)
        self.contextMenu.addAction(self.toggleBookmarkAct)
#        self.contextMenu.addAction(self.toggleBreakpointAct)

        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.refactor.findDefAct)
        self.contextMenu.addAction(self.refactor.findOccurrencesAct)

        self.contextMenu.addMenu(self.refactor.refactorMenu)

        self.viewMenu = self.contextMenu.addMenu("View")
        self.viewMenu.addAction(self.editorTabWidget.vSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.hSplitEditorAct)
        self.viewMenu.addAction(self.editorTabWidget.noSplitEditorAct)
        self.viewMenu.addSeparator()
        self.viewMenu.addAction(self.indentationGuideAct)
        self.viewMenu.addSeparator()
        self.viewMenu.addAction(self.zoomAct)
        self.contextMenu.addSeparator()
        self.contextMenu.addAction(self.takeSnapshotAct)

    def contextMenuEvent(self, event):
        filePath = self.DATA['filePath']
        isProjectFile = self.editorTabWidget.isProjectFile(filePath)
        self.refactor.refactorMenu.setEnabled(isProjectFile)
        self.refactor.findOccurrencesAct.setEnabled(isProjectFile)

        hasSelection = self.hasSelectedText()
        self.copyAct.setEnabled(hasSelection)
        self.cutAct.setEnabled(hasSelection)

        self.contextMenu.exec_(event.globalPos())

    def undoActModifier(self):
        state = self.isUndoAvailable()
        self.editorTabWidget.undoAct.setEnabled(state)

    def redoActModifier(self):
        state = self.isRedoAvailable()
        self.editorTabWidget.redoAct.setEnabled(state)

    def copyActModifier(self):
        state = self.hasSelectedText()
        self.editorTabWidget.copyAct.setEnabled(state)
        self.editorTabWidget.cutAct.setEnabled(state)

    def updateLineCount(self):
        lines = self.lines()
        self.editorTabWidget.updateLinesCount.emit(lines)

    def startCompletion(self):
        if self.useData.SETTINGS["EnableAutoCompletion"] == "True":
            if self.useData.SETTINGS["AutoCompletion"] == "Api":
                lineno, col = self.getCursorPosition()
                self.completionCallPos = self.getCursorPosition()
                lineText = self.text(lineno)[:col]

                ropeProject = self.refactor.getProject()
                offset = self.getOffset()

                self.autoCompletionThread.complete(
                    self.refactor.root,
                        ropeProject, offset, self.text(), lineText, col)

    def showCompletions(self, result):
        if len(result) > 0:
            if self.hasFocus():
                self.showUserList(
                    self.autoCompletionThread.completionType, result)
        else:
            self.cancelList()

    def insertText(self, id, text):
        word = self.get_current_word()
        if not word:
            pass
        else:
            self.deleteWordToLeft()
        self.removeSelectedText()
        if id == 1:
            file = open(os.path.join(self.useData.appPathDict[
                        "snippetsdir"], text), 'r')
            cmpl = file.readlines()
            file.close()
            line, col = self.getCursorPosition()
            if self.text(line).strip() == '':
                padding = ' ' * col
                paddedText = ''
                for i in range(len(cmpl)):
                    textLine = padding + cmpl[i]
                    paddedText += textLine
                self.setCursorPosition(line, 0)
                self.insert(paddedText)
            else:
                self.insert(cmpl[0])
        elif id == 2:
            # TODO: Insert must check for brackets after inserting functions.
            x = text.split()
            cmpl = x[0]
            type = x[2].strip(")")
            self.insert(cmpl)
        elif id == 3:
            cmpl = text.rstrip(os.path.sep)
            self.insert(cmpl)
        self.moveCursorWordRight()

    def takeSnapshot(self):
        reply = QtGui.QMessageBox.warning(self, "Snapshot",
                                          "Take a snapshot of the current module state?",
                                          QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            subStack = self.editorTabWidget.currentWidget()
            subStack.widget(1).setText(self.text())
        else:
            return

    def toggleLineBreakpoint(self):
        line, index = self.getCursorPosition()
        if self.markersAtLine(line) != 0:
            self.markerDelete(line, self.breakpointMarker)
        else:
            self.markerAdd(line, self.breakpointMarker)
        self.ensureLineVisible(line - 1)

    def updateLexer(self, lexer):
        self.lexer = lexer
        self.setLexer(lexer)

    def _toggleBookmark(self):
        nmargin = 0
        nline = self.getCursorPosition()[0]

        self.toggleBookmark(nmargin, nline)

    def toggleBookmark(self, nmargin, nline, modifiers=None):
        for handle in self.DATA["bookmarkList"]:
            if self.markerLine(handle) == nline:
                self.DATA["bookmarkList"].remove(handle)
                self.markerDeleteHandle(handle)

                markersExist = self.bookmarksExist()
                self.editorTabWidget.enableBookmarkButtons(markersExist)
                return
        handle = self.markerAdd(nline, 8)
        self.DATA["bookmarkList"].append(handle)

        markersExist = self.bookmarksExist()
        self.editorTabWidget.enableBookmarkButtons(markersExist)

    def bookmarksExist(self):
        markersExist = (len(self.DATA["bookmarkList"]) > 0)
        return markersExist

    def getBookmarks(self):
        bookmarkLines = []
        for handle in self.DATA["bookmarkList"]:
            line = self.markerLine(handle)
            bookmarkLines.append(line)

        return bookmarkLines

    def showSnippets(self):
        try:
            snippetList = os.listdir(
                self.useData.appPathDict["snippetsdir"])
        except:
            self.notification.showMessage("Could not fetch snippets.")
            return
        if len(snippetList) > 0:
            self.showUserList(1, snippetList)
        else:
            self.notification.showMessage("No snippets available.")

    def clearErrorMarkerAndIndicator(self):
        self.clearAllIndicators(self.syntaxErrorIndicator)
        self.clearAnnotations()
        self.markerDeleteAll(9)

    def setAutoCompletion(self):
        if self.useData.SETTINGS["EnableAutoCompletion"] == "False":
            self.setAutoCompletionSource(QsciScintilla.AcsNone)
            return
        if self.useData.SETTINGS["AutoCompletion"] == "Api":
            self.setAutoCompletionSource(QsciScintilla.AcsNone)
        elif self.useData.SETTINGS["AutoCompletion"] == "Document":
            self.setAutoCompletionSource(QsciScintilla.AcsDocument)

    def setMarkOperationalLines(self):
        if self.useData.SETTINGS["MarkOperationalLines"] == 'True':
            self.setMarginWidth(3, self.fontMetrics.width("0"))
            self.getOperationTokens()
        else:
            self.markerDeleteAll(11)
            self.setMarginWidth(3, 0)

    def getOffset(self):
        offset = self.currentPosition()
        return offset

    def showLine(self, lineNum, highlight=True):
        if highlight:
            self.setSelection(
                lineNum, 0, lineNum, self.lineLength(lineNum) - 1)
        self.ensureLineVisible(lineNum)

    def showIndentationGuide(self):
        if self.indentationGuides():
            self.setIndentationGuides(False)
        else:
            self.setIndentationGuides(True)

    def showZoomWidget(self):
        self.zoomWidget.show()

    def showWhiteSpaces(self):
        if self.useData.SETTINGS["ShowWhiteSpaces"] == 'True':
            self.setWhitespaceVisibility(QsciScintilla.WsVisible)
        else:
            self.setWhitespaceVisibility(QsciScintilla.WsInvisible)

    def findNextBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindNext(cursorLine + 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindNext(0, 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def findPreviousBookmark(self):
        cursorLine = self.getCursorPosition()[0]
        lineNum = self.markerFindPrevious(cursorLine - 1, 256)
        if lineNum == -1:
            lineNum = self.markerFindPrevious(self.lines(), 256)
            if lineNum == -1:
                return
        self.showLine(lineNum)

    def removeBookmarks(self):
        if len(self.DATA["bookmarkList"]) > 0:
            self.DATA["bookmarkList"] = []
            self.markerDeleteAll(8)

    def addCommentPrefix(self, line):
        if self.text(line).strip().startswith('#'):
            pass
        else:
            self.insertAt('#', line, 0)

    def removeCommentPrefix(self, line):
        if self.text(line).strip().startswith('#'):
            lineText = self.text(line)
            commentIndex = lineText.find('#')
            self.setSelection(line, commentIndex, line, commentIndex + 1)
            self.replaceSelectedText('')
        else:
            pass

    def comment(self):
        if self.hasSelectedText():
            lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
            if lineFrom == lineTo:
                self.addCommentPrefix(lineFrom)
            else:
                self.beginUndoAction()
                for i in range(lineFrom, lineTo + 1):
                    self.addCommentPrefix(i)
                self.endUndoAction()
            self.setSelection(lineFrom, indexFrom, lineTo, indexTo)
        else:
            line, index = self.getCursorPosition()
            self.addCommentPrefix(line)

    def unComment(self):
        if self.hasSelectedText():
            lineFrom, indexFrom, lineTo, indexTo = self.getSelection()
            if lineFrom == lineTo:
                self.removeCommentPrefix(lineFrom)
            else:
                self.beginUndoAction()
                for i in range(lineFrom, lineTo + 1):
                    self.removeCommentPrefix(i)
                self.endUndoAction()
            self.setSelection(lineFrom, indexFrom, lineTo, indexTo)
        else:
            line, index = self.getCursorPosition()
            self.removeCommentPrefix(line)

    def replaceTabsWithSpaces(self):
        text = self.text()
        text = text.replace('\t', ' ' * 4)
        self.selectAll()
        self.replaceSelectedText(text)

    def removeTrailingWhitespaces(self):
        self.beginUndoAction()
        for i in range(self.lines()):
            text = self.text(i)
            white_len = len(text) - len(text.rstrip())
            if white_len > 1:
                self.setSelection(i, self.lineLength(i) - white_len, i,
                                  self.lineLength(i) - 1)
                self.removeSelectedText()
        self.endUndoAction()

    def setKeymap(self):
        self.updateKeymap(self.useData)

        shortcuts = self.useData.CUSTOM_SHORTCUTS

        self.cutAct.setShortcut(shortcuts["Editor"]["Cut-Selection"][0])
        self.copyAct.setShortcut(shortcuts["Editor"]["Copy-Selection"][0])
        self.pasteAct.setShortcut(shortcuts["Editor"]["Paste"][0])

        self.shortSnippets = QtGui.QShortcut(
            shortcuts["Ide"]["Snippets"], self)
        self.shortSnippets.activated.connect(self.showSnippets)

        self.shortIndentationGuide = QtGui.QShortcut(
            shortcuts["Ide"]["Toggle-Indentation-Guide"], self)
        self.shortIndentationGuide.activated.connect(self.showIndentationGuide)

        self.shortShowCompletion = QtGui.QShortcut(
            shortcuts["Ide"]["Show-Completion"], self)
        self.shortShowCompletion.activated.connect(self.startCompletion)

        self.shortToggleBreakpoint = QtGui.QShortcut(
            shortcuts["Ide"]["Toggle-Breakpoint"], self)
        self.shortToggleBreakpoint.activated.connect(self.toggleLineBreakpoint)

        self.shortNextBookmark = QtGui.QShortcut(
            shortcuts["Ide"]["Next-Bookmark"], self)
        self.shortNextBookmark.activated.connect(self.findNextBookmark)

        self.shortPreviousBookmark = QtGui.QShortcut(
            shortcuts["Ide"]["Previous-Bookmark"], self)
        self.shortPreviousBookmark.activated.connect(self.findPreviousBookmark)

        self.shortComment = QtGui.QShortcut(
            shortcuts["Ide"]["Comment"], self)
        self.shortComment.activated.connect(self.comment)

        self.shortUncomment = QtGui.QShortcut(
            shortcuts["Ide"]["Uncomment"], self)
        self.shortUncomment.activated.connect(self.unComment)

        self.shortZoomIn = QtGui.QShortcut(
            shortcuts["Editor"]["Zoom-In"][0], self)
        self.shortZoomIn.activated.connect(self.zoomWidget.zoomIn)

        self.shortZoomOut = QtGui.QShortcut(
            shortcuts["Editor"]["Zoom-Out"][0], self)
        self.shortZoomOut.activated.connect(self.zoomWidget.zoomOut)
예제 #7
0
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent, QtCore.Qt.Window |
                                  QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint |
                                  QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)

        self.setWindowIcon(QtGui.QIcon("Icons\\Icon.png"))
        self.setFixedSize(492, 515)
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width())
                  / 2, (screen.height() - size.height()) / 2)
        self.setWindowTitle('RedCenter - Standard Edition')

        mainBackgroundLabel = QtGui.QLabel(self)
        mainBackgroundLabel.setStyleSheet(
            "background: rgba(0, 0, 0, 220); border: 1px solid grey; border-radius: 0px;")
        mainBackgroundLabel.setScaledContents(True)
        mainBackgroundLabel.setGeometry(0, 0, 492, 515)

        frame = FrameLabel(self)

        self.createTrayIcon()

        self.mainWidget = QtGui.QWidget(self)
        self.mainWidget.setGeometry(5, 25, 492, 555)

        # load configuration from file
        tempList = []
        file = open("settings.ini", "r")
        for i in file.readlines():
            if i.strip() == '':
                pass
            else:
                tempList.append(tuple(i.strip().split('=')))
        file.close()
        self.SETTINGS = dict(tempList)

        # *************************** Main Interface *************************

        separator = QtGui.QFrame(self.mainWidget)
        separator.setFrameShape(separator.HLine)
        separator.setFrameShadow(separator.Raised)
        separator.setGeometry(0, 0, 488, 1)

        self.homeDirPathLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirPathLabel.setStyleSheet("color: white;")
        self.homeDirPathLabel.setGeometry(5, 2, 470, 15)

        self.homeDirCountLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirCountLabel.setStyleSheet("color: white;")
        self.homeDirCountLabel.setGeometry(0, 470, 90, 15)

        self.homeDirNameLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirNameLabel.setStyleSheet("color: white;")
        self.homeDirNameLabel.setGeometry(110, 470, 370, 15)

        self.driveIconLabel = QtGui.QLabel(self.mainWidget)
        self.driveIconLabel.setGeometry(403, 150, 80, 80)
        self.driveIconLabel.setScaledContents(True)

        self.prevButton = QtGui.QPushButton(self.mainWidget)
        self.prevButton.setGeometry(405, 48, 38, 25)
        self.prevButton.setIcon(QtGui.QIcon("Icons\\Previous"))
        self.prevButton.setToolTip("Previous")
        self.prevButton.setDisabled(True)
        self.prevButton.clicked.connect(self.prevItem)

        self.nextButton = QtGui.QPushButton(self.mainWidget)
        self.nextButton.setGeometry(444, 48, 36, 25)
        self.nextButton.setIcon(QtGui.QIcon("Icons\\Next"))
        self.nextButton.setToolTip("Next")
        self.nextButton.setDisabled(True)
        self.nextButton.clicked.connect(self.nextItem)

        self.lockButton = QtGui.QPushButton("Lock", self.mainWidget)
        self.lockButton.setGeometry(405, 255, 75, 25)
        self.lockButton.setDisabled(True)
        self.lockButton.clicked.connect(self.lockItem_init)

        self.unhideButton = QtGui.QPushButton("Unhide", self.mainWidget)
        self.unhideButton.setGeometry(405, 285, 75, 25)
        self.unhideButton.setDisabled(True)
        self.unhideButton.clicked.connect(self.unhideItems)

        separator = QtGui.QFrame(self.mainWidget)
        separator.setFrameShape(separator.VLine)
        separator.setFrameShadow(separator.Raised)
        separator.setGeometry(100, 470, 1, 15)

        self.browseButton = QtGui.QPushButton("Browse", self.mainWidget)
        self.browseButton.setGeometry(405, 20, 75, 25)
        self.browseButton.clicked.connect(self.selectPath)

        self.backShortcut = QtGui.QShortcut(self.prevButton)
        self.backShortcut.setKey(QtGui.QKeySequence("Backspace"))
        self.backShortcut.activated.connect(self.prevItem)

        self.backShortcut_2 = QtGui.QShortcut(self.prevButton)
        self.backShortcut_2.setKey(QtGui.QKeySequence("Alt+Left"))
        self.backShortcut_2.activated.connect(self.prevItem)

        self.nextShortcut = QtGui.QShortcut(self.nextButton)
        self.nextShortcut.setKey(QtGui.QKeySequence("Alt+Right"))
        self.nextShortcut.activated.connect(self.nextItem)

        self.homeButton = QtGui.QPushButton("Home", self.mainWidget)
        self.homeButton.setGeometry(405, 76, 75, 25)
        self.homeButton.clicked.connect(self.goHome)

        self.vaultButton = QtGui.QPushButton("Vault", self.mainWidget)
        self.vaultButton.setGeometry(405, 350, 75, 25)
        self.vaultButton.setCheckable(True)
        self.vaultButton.clicked.connect(self.changeView)

        self.aboutButton = QtGui.QPushButton("About", self.mainWidget)
        self.aboutButton.setGeometry(405, 410, 75, 25)
        self.aboutButton.setCheckable(True)
        self.aboutButton.toggled.connect(self.about)

        self.closeButton = QtGui.QPushButton("Close", self.mainWidget)
        self.closeButton.setGeometry(405, 440, 75, 25)
        self.closeButton.clicked.connect(self.close)

    #************************* Vault Interface Elements ***********************

        self.vaultNameLabel = QtGui.QLabel("Vault", self.mainWidget)
        self.vaultNameLabel.setGeometry(5, 2, 533, 15)
        self.vaultNameLabel.setStyleSheet("color: white;")
        self.vaultNameLabel.hide()

        self.vaultItemCountLabel = QtGui.QLabel(self.mainWidget)
        self.vaultItemCountLabel.setGeometry(0, 470, 90, 15)
        self.vaultItemCountLabel.setStyleSheet("color: white;")
        self.vaultItemCountLabel.hide()

        self.selectAllButton = QtGui.QPushButton("Select All", self.mainWidget)
        self.selectAllButton.setGeometry(405, 20, 75, 25)
        self.selectAllButton.clicked.connect(self.selectAll)
        self.selectAllButton.hide()

        self.clearSelectionButton = QtGui.QPushButton(
            "Deselect All", self.mainWidget)
        self.clearSelectionButton.setGeometry(405, 50, 75, 25)
        self.clearSelectionButton.clicked.connect(self.clearSelection)
        self.clearSelectionButton.hide()

        self.vaultIconLabel = QtGui.QLabel(self.mainWidget)
        self.vaultIconLabel.setGeometry(403, 150, 80, 80)
        self.vaultIconLabel.setScaledContents(True)
        self.vaultIconLabel.setPixmap(
            QtGui.QPixmap("Icons\\driveIcons\\security"))
        self.vaultIconLabel.hide()

        self.deleteButton = QtGui.QPushButton("Delete", self.mainWidget)
        self.deleteButton.setGeometry(405, 255, 75, 25)
        self.deleteButton.clicked.connect(self.delete)
        self.deleteButton.setDisabled(True)
        self.deleteButton.hide()

        self.unlockButton = QtGui.QPushButton("Unlock", self.mainWidget)
        self.unlockButton.setGeometry(405, 285, 75, 25)
        self.unlockButton.clicked.connect(self.unlockItem_init)
        self.unlockButton.setDisabled(True)
        self.unlockButton.hide()

        self.sizeLabel = QtGui.QLabel(self.mainWidget)
        self.sizeLabel.setGeometry(110, 470, 430, 15)
        self.sizeLabel.setStyleSheet("color: white;")
        self.sizeLabel.hide()

        self.pagesStack = QtGui.QStackedWidget(self.mainWidget)
        self.pagesStack.setGeometry(0, 20, 400, 445)

        self.notification = Notification(self.mainWidget)
        self.notification.setGeometry(0, 410, 400, 50)
        self.notification.hide()

        self.busyIndicatorWidget = ProgressWidget(self.mainWidget)
        self.busyIndicatorWidget.move(0, 20)
        self.busyIndicatorWidget.hide()

        #---------------------------------------------------------------------

        self.fileManager = FileManager(self, self.busyIndicatorWidget)
        self.pagesStack.addWidget(self.fileManager)

        self.vaultListWidget = VaultManager(self.vaultItemCountLabel,
                                           self.sizeLabel, self.busyIndicatorWidget, self)
        self.pagesStack.addWidget(self.vaultListWidget)

        self.itemLock = Lock(self.busyIndicatorWidget,
                            self.fileManager, self)
        self.itemUnlock = Unlock(self.busyIndicatorWidget,
                                self.vaultListWidget,
                                                    self.fileManager, self)
        self.itemDelete = Delete(self.busyIndicatorWidget,
                                self.vaultListWidget, self)
        #--------------------------------------------------------------------
        self.aboutLabel = AboutLabel()
        self.pagesStack.addWidget(self.aboutLabel)
        #---------------------------------------------------------------------
        self.messageStack = QtGui.QStackedWidget(self.mainWidget)
        self.messageStack.setGeometry(0, 20, 400, 80)

        lockMessage = MessageBox.MessageBox(
            "Send the selected files to vault?",
            self.messageStack)
        lockMessage.acceptButton.clicked.connect(self.itemLock.lock)
        self.messageStack.addWidget(lockMessage)

        unlockMessage = MessageBox.MessageBox(
            "Restore the selected files to a specified location?",
            self.messageStack)
        unlockMessage.acceptButton.clicked.connect(self.itemUnlock.unlock)
        self.messageStack.addWidget(unlockMessage)

        deleteMessage = MessageBox.MessageBox(
            "Permanently remove the selected files from the vault?",
            self.messageStack)
        deleteMessage.acceptButton.clicked.connect(self.itemDelete.delete)
        self.messageStack.addWidget(deleteMessage)

        lockReplyMessage = MessageBox.ReplyBox("Failed to complete lock!",
                                              self.messageStack)
        lockReplyMessage.retryButton.clicked.connect(self.itemLock.retryLock)
        self.messageStack.addWidget(lockReplyMessage)

        unlockReplyMessage = MessageBox.ReplyBox(
            "Failed to complete unlock! \nFile will not be unlocked if it already exists.",
            self.messageStack)
        unlockReplyMessage.retryButton.clicked.connect(
            self.itemUnlock.retryUnlock)
        self.messageStack.addWidget(unlockReplyMessage)

        deleteReplyMessage = MessageBox.ReplyBox("Failed to complete delete!",
                                                self.messageStack)
        deleteReplyMessage.retryButton.clicked.connect(
            self.itemDelete.retryDelete)
        self.messageStack.addWidget(deleteReplyMessage)

        self.messageStack.hide()
예제 #8
0
class RedCenter(QtGui.QMainWindow):

    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent, QtCore.Qt.Window |
                                  QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowSystemMenuHint |
                                  QtCore.Qt.WindowMinimizeButtonHint | QtCore.Qt.WindowCloseButtonHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground, True)

        self.setWindowIcon(QtGui.QIcon("Icons\\Icon.png"))
        self.setFixedSize(492, 515)
        screen = QtGui.QDesktopWidget().screenGeometry()
        size = self.geometry()
        self.move((screen.width() - size.width())
                  / 2, (screen.height() - size.height()) / 2)
        self.setWindowTitle('RedCenter - Standard Edition')

        mainBackgroundLabel = QtGui.QLabel(self)
        mainBackgroundLabel.setStyleSheet(
            "background: rgba(0, 0, 0, 220); border: 1px solid grey; border-radius: 0px;")
        mainBackgroundLabel.setScaledContents(True)
        mainBackgroundLabel.setGeometry(0, 0, 492, 515)

        frame = FrameLabel(self)

        self.createTrayIcon()

        self.mainWidget = QtGui.QWidget(self)
        self.mainWidget.setGeometry(5, 25, 492, 555)

        # load configuration from file
        tempList = []
        file = open("settings.ini", "r")
        for i in file.readlines():
            if i.strip() == '':
                pass
            else:
                tempList.append(tuple(i.strip().split('=')))
        file.close()
        self.SETTINGS = dict(tempList)

        # *************************** Main Interface *************************

        separator = QtGui.QFrame(self.mainWidget)
        separator.setFrameShape(separator.HLine)
        separator.setFrameShadow(separator.Raised)
        separator.setGeometry(0, 0, 488, 1)

        self.homeDirPathLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirPathLabel.setStyleSheet("color: white;")
        self.homeDirPathLabel.setGeometry(5, 2, 470, 15)

        self.homeDirCountLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirCountLabel.setStyleSheet("color: white;")
        self.homeDirCountLabel.setGeometry(0, 470, 90, 15)

        self.homeDirNameLabel = QtGui.QLabel(self.mainWidget)
        self.homeDirNameLabel.setStyleSheet("color: white;")
        self.homeDirNameLabel.setGeometry(110, 470, 370, 15)

        self.driveIconLabel = QtGui.QLabel(self.mainWidget)
        self.driveIconLabel.setGeometry(403, 150, 80, 80)
        self.driveIconLabel.setScaledContents(True)

        self.prevButton = QtGui.QPushButton(self.mainWidget)
        self.prevButton.setGeometry(405, 48, 38, 25)
        self.prevButton.setIcon(QtGui.QIcon("Icons\\Previous"))
        self.prevButton.setToolTip("Previous")
        self.prevButton.setDisabled(True)
        self.prevButton.clicked.connect(self.prevItem)

        self.nextButton = QtGui.QPushButton(self.mainWidget)
        self.nextButton.setGeometry(444, 48, 36, 25)
        self.nextButton.setIcon(QtGui.QIcon("Icons\\Next"))
        self.nextButton.setToolTip("Next")
        self.nextButton.setDisabled(True)
        self.nextButton.clicked.connect(self.nextItem)

        self.lockButton = QtGui.QPushButton("Lock", self.mainWidget)
        self.lockButton.setGeometry(405, 255, 75, 25)
        self.lockButton.setDisabled(True)
        self.lockButton.clicked.connect(self.lockItem_init)

        self.unhideButton = QtGui.QPushButton("Unhide", self.mainWidget)
        self.unhideButton.setGeometry(405, 285, 75, 25)
        self.unhideButton.setDisabled(True)
        self.unhideButton.clicked.connect(self.unhideItems)

        separator = QtGui.QFrame(self.mainWidget)
        separator.setFrameShape(separator.VLine)
        separator.setFrameShadow(separator.Raised)
        separator.setGeometry(100, 470, 1, 15)

        self.browseButton = QtGui.QPushButton("Browse", self.mainWidget)
        self.browseButton.setGeometry(405, 20, 75, 25)
        self.browseButton.clicked.connect(self.selectPath)

        self.backShortcut = QtGui.QShortcut(self.prevButton)
        self.backShortcut.setKey(QtGui.QKeySequence("Backspace"))
        self.backShortcut.activated.connect(self.prevItem)

        self.backShortcut_2 = QtGui.QShortcut(self.prevButton)
        self.backShortcut_2.setKey(QtGui.QKeySequence("Alt+Left"))
        self.backShortcut_2.activated.connect(self.prevItem)

        self.nextShortcut = QtGui.QShortcut(self.nextButton)
        self.nextShortcut.setKey(QtGui.QKeySequence("Alt+Right"))
        self.nextShortcut.activated.connect(self.nextItem)

        self.homeButton = QtGui.QPushButton("Home", self.mainWidget)
        self.homeButton.setGeometry(405, 76, 75, 25)
        self.homeButton.clicked.connect(self.goHome)

        self.vaultButton = QtGui.QPushButton("Vault", self.mainWidget)
        self.vaultButton.setGeometry(405, 350, 75, 25)
        self.vaultButton.setCheckable(True)
        self.vaultButton.clicked.connect(self.changeView)

        self.aboutButton = QtGui.QPushButton("About", self.mainWidget)
        self.aboutButton.setGeometry(405, 410, 75, 25)
        self.aboutButton.setCheckable(True)
        self.aboutButton.toggled.connect(self.about)

        self.closeButton = QtGui.QPushButton("Close", self.mainWidget)
        self.closeButton.setGeometry(405, 440, 75, 25)
        self.closeButton.clicked.connect(self.close)

    #************************* Vault Interface Elements ***********************

        self.vaultNameLabel = QtGui.QLabel("Vault", self.mainWidget)
        self.vaultNameLabel.setGeometry(5, 2, 533, 15)
        self.vaultNameLabel.setStyleSheet("color: white;")
        self.vaultNameLabel.hide()

        self.vaultItemCountLabel = QtGui.QLabel(self.mainWidget)
        self.vaultItemCountLabel.setGeometry(0, 470, 90, 15)
        self.vaultItemCountLabel.setStyleSheet("color: white;")
        self.vaultItemCountLabel.hide()

        self.selectAllButton = QtGui.QPushButton("Select All", self.mainWidget)
        self.selectAllButton.setGeometry(405, 20, 75, 25)
        self.selectAllButton.clicked.connect(self.selectAll)
        self.selectAllButton.hide()

        self.clearSelectionButton = QtGui.QPushButton(
            "Deselect All", self.mainWidget)
        self.clearSelectionButton.setGeometry(405, 50, 75, 25)
        self.clearSelectionButton.clicked.connect(self.clearSelection)
        self.clearSelectionButton.hide()

        self.vaultIconLabel = QtGui.QLabel(self.mainWidget)
        self.vaultIconLabel.setGeometry(403, 150, 80, 80)
        self.vaultIconLabel.setScaledContents(True)
        self.vaultIconLabel.setPixmap(
            QtGui.QPixmap("Icons\\driveIcons\\security"))
        self.vaultIconLabel.hide()

        self.deleteButton = QtGui.QPushButton("Delete", self.mainWidget)
        self.deleteButton.setGeometry(405, 255, 75, 25)
        self.deleteButton.clicked.connect(self.delete)
        self.deleteButton.setDisabled(True)
        self.deleteButton.hide()

        self.unlockButton = QtGui.QPushButton("Unlock", self.mainWidget)
        self.unlockButton.setGeometry(405, 285, 75, 25)
        self.unlockButton.clicked.connect(self.unlockItem_init)
        self.unlockButton.setDisabled(True)
        self.unlockButton.hide()

        self.sizeLabel = QtGui.QLabel(self.mainWidget)
        self.sizeLabel.setGeometry(110, 470, 430, 15)
        self.sizeLabel.setStyleSheet("color: white;")
        self.sizeLabel.hide()

        self.pagesStack = QtGui.QStackedWidget(self.mainWidget)
        self.pagesStack.setGeometry(0, 20, 400, 445)

        self.notification = Notification(self.mainWidget)
        self.notification.setGeometry(0, 410, 400, 50)
        self.notification.hide()

        self.busyIndicatorWidget = ProgressWidget(self.mainWidget)
        self.busyIndicatorWidget.move(0, 20)
        self.busyIndicatorWidget.hide()

        #---------------------------------------------------------------------

        self.fileManager = FileManager(self, self.busyIndicatorWidget)
        self.pagesStack.addWidget(self.fileManager)

        self.vaultListWidget = VaultManager(self.vaultItemCountLabel,
                                           self.sizeLabel, self.busyIndicatorWidget, self)
        self.pagesStack.addWidget(self.vaultListWidget)

        self.itemLock = Lock(self.busyIndicatorWidget,
                            self.fileManager, self)
        self.itemUnlock = Unlock(self.busyIndicatorWidget,
                                self.vaultListWidget,
                                                    self.fileManager, self)
        self.itemDelete = Delete(self.busyIndicatorWidget,
                                self.vaultListWidget, self)
        #--------------------------------------------------------------------
        self.aboutLabel = AboutLabel()
        self.pagesStack.addWidget(self.aboutLabel)
        #---------------------------------------------------------------------
        self.messageStack = QtGui.QStackedWidget(self.mainWidget)
        self.messageStack.setGeometry(0, 20, 400, 80)

        lockMessage = MessageBox.MessageBox(
            "Send the selected files to vault?",
            self.messageStack)
        lockMessage.acceptButton.clicked.connect(self.itemLock.lock)
        self.messageStack.addWidget(lockMessage)

        unlockMessage = MessageBox.MessageBox(
            "Restore the selected files to a specified location?",
            self.messageStack)
        unlockMessage.acceptButton.clicked.connect(self.itemUnlock.unlock)
        self.messageStack.addWidget(unlockMessage)

        deleteMessage = MessageBox.MessageBox(
            "Permanently remove the selected files from the vault?",
            self.messageStack)
        deleteMessage.acceptButton.clicked.connect(self.itemDelete.delete)
        self.messageStack.addWidget(deleteMessage)

        lockReplyMessage = MessageBox.ReplyBox("Failed to complete lock!",
                                              self.messageStack)
        lockReplyMessage.retryButton.clicked.connect(self.itemLock.retryLock)
        self.messageStack.addWidget(lockReplyMessage)

        unlockReplyMessage = MessageBox.ReplyBox(
            "Failed to complete unlock! \nFile will not be unlocked if it already exists.",
            self.messageStack)
        unlockReplyMessage.retryButton.clicked.connect(
            self.itemUnlock.retryUnlock)
        self.messageStack.addWidget(unlockReplyMessage)

        deleteReplyMessage = MessageBox.ReplyBox("Failed to complete delete!",
                                                self.messageStack)
        deleteReplyMessage.retryButton.clicked.connect(
            self.itemDelete.retryDelete)
        self.messageStack.addWidget(deleteReplyMessage)

        self.messageStack.hide()

    def showMessage(self, mess):
        self.notification.showMessage(mess)

    def hideMessage(self):
        self.notification.hide()

    def saveSettings(self):
        file = open("settings.ini", "w")
        for key, value in self.SETTINGS.items():
            file.write('\n' + key + '=' + value)
        file.close()

    def createTrayIcon(self):
        self.restoreAction = QtGui.QAction(QtGui.QIcon("Icons\\restore.png"),
                                          "Show", self, triggered=self.showNormal)

        self.hideAction = QtGui.QAction("Hide", self, triggered=self.hide)

        self.closeAction = QtGui.QAction(QtGui.QIcon("Icons\\close.png"),
                                        "Exit", self, triggered=self.shutdown)

        self.trayIconMenu = QtGui.QMenu(self)
        self.trayIconMenu.addAction(self.restoreAction)
        self.trayIconMenu.addAction(self.hideAction)
        self.trayIconMenu.addSeparator()
        self.trayIconMenu.addAction(self.closeAction)

        self.trayIcon = QtGui.QSystemTrayIcon(self)
        self.trayIcon.setContextMenu(self.trayIconMenu)
        self.trayIcon.setIcon(QtGui.QIcon("Icons\\Icon.png"))
        self.trayIcon.setToolTip("RedCenter - Standard Edition")
        self.trayIcon.messageClicked.connect(self.messageClicked)
        self.trayIcon.activated.connect(self.iconActivated)

        self.trayIcon.show()

    def closeEvent(self, event):
        self.hide()
        self.fileManager.loadDirectory("c:\\")
        if self.SETTINGS['NotificationClicked'] == "False":
            self.trayIcon.showMessage("RedCenter - Standard Edition",
                                     "Program is still running in the background. Disable this notification by clicking on this balloon.", 1)
        else:
            pass
        event.ignore()

    def reload_homeDir(self):
        self.fileManager.reload_homeDir()

    def selectPath(self):
        self.fileManager.setParentDirectory()

    def prevItem(self):
        self.fileManager.prevDir()

    def nextItem(self):
        self.fileManager.nextDir()

    def goHome(self):
        self.fileManager.goHome()

    def unhideItems(self):
        self.fileManager.unhideItems()

    def delete(self):
        self.itemDelete.loadDeleteList()
        self.messageStack.setCurrentIndex(2)
        self.messageStack.show()

    def loadDirectory(self, directory):
        self.fileManager.loadDirectory(directory)

    def selectAll(self):
        self.vaultListWidget.selectAll()

    def clearSelection(self):
        self.vaultListWidget.clearSelection()

    def lockItem_init(self):
        self.itemLock.loadLockList()
        self.messageStack.setCurrentIndex(0)
        self.messageStack.show()

    def unlockItem_init(self):
        self.itemUnlock.loadUnlockList()
        self.messageStack.setCurrentIndex(1)
        self.messageStack.show()

    def messageClicked(self):
        self.SETTINGS['NotificationClicked'] = 'True'
        self.saveSettings()

    def iconActivated(self, reason):
        if reason in (QtGui.QSystemTrayIcon.Trigger,
                     QtGui.QSystemTrayIcon.DoubleClick):
            self.setHidden(False)
        else:
            pass

    def about(self, show):
        if show:
            self.currentWidget = self.pagesStack.currentWidget()
            self.vaultButton.setDisabled(True)
            self.pagesStack.setCurrentWidget(self.aboutLabel)
        else:
            self.pagesStack.setCurrentWidget(self.currentWidget)
            self.vaultButton.setDisabled(False)

    def sound(self, soundType):
        if soundType == "open":
            sound = QtGui.QSound("Sounds\\Open.wav")
        elif soundType == "deleted":
            sound = QtGui.QSound("Sounds\\Trash Empty.wav")
        sound.play()

    def shutdown(self):
        self.saveSettings()
        sys.exit(0)

    def showBusy(self, view):
        self.busyIndicatorWidget.show()
        if view == "directory":
            self.browseButton.setDisabled(True)
            self.prevButton.setDisabled(True)
            self.nextButton.setDisabled(True)
            self.homeButton.setDisabled(True)
            self.lockButton.setDisabled(True)
            self.unhideButton.setDisabled(True)
            self.vaultButton.setDisabled(True)
            self.aboutButton.setDisabled(True)
        elif view == "vault":
            self.selectAllButton.setDisabled(True)
            self.clearSelectionButton.setDisabled(True)
            self.deleteButton.setDisabled(True)
            self.unlockButton.setDisabled(True)
            self.vaultButton.setDisabled(True)
            self.aboutButton.setDisabled(True)

    def showReady(self, view):
        self.busyIndicatorWidget.hide()
        self.busyIndicatorWidget.currentItemLabel.clear()
        self.busyIndicatorWidget.updateProgress(0)
        if view == "directory":
            self.setHidden(False)
            self.browseButton.setDisabled(False)
            self.homeButton.setDisabled(False)
            self.lockButton.setDisabled(False)
            self.unhideButton.setDisabled(False)
            self.vaultButton.setDisabled(False)
            self.aboutButton.setDisabled(False)
        elif view == "vault":
            self.setHidden(False)
            self.selectAllButton.setDisabled(False)
            self.clearSelectionButton.setDisabled(False)
            self.deleteButton.setDisabled(False)
            self.unlockButton.setDisabled(False)
            self.vaultButton.setDisabled(False)
            self.aboutButton.setDisabled(False)

    def changeView(self):
        if self.vaultButton.isChecked() == True:
            # hide directory widgets
            self.homeDirPathLabel.hide()
            self.homeDirCountLabel.hide()
            self.homeDirNameLabel.hide()
            self.browseButton.hide()
            self.prevButton.hide()
            self.nextButton.hide()
            self.homeButton.hide()
            self.driveIconLabel.hide()
            self.lockButton.hide()
            self.unhideButton.hide()

            # show vault widgets
            self.vaultNameLabel.setHidden(False)
            self.pagesStack.setCurrentWidget(self.vaultListWidget)
            self.vaultItemCountLabel.setHidden(False)
            self.selectAllButton.setHidden(False)
            self.clearSelectionButton.setHidden(False)
            self.vaultIconLabel.setHidden(False)
            self.deleteButton.setHidden(False)
            self.unlockButton.setHidden(False)
            self.sizeLabel.setHidden(False)
            self.vaultButton.setText("Back")
            self.vaultListWidget.loadVault()
        else:
            # hide vault widgets
            self.vaultNameLabel.hide()
            self.vaultItemCountLabel.hide()
            self.selectAllButton.hide()
            self.clearSelectionButton.hide()
            self.vaultIconLabel.hide()
            self.deleteButton.hide()
            self.unlockButton.hide()
            self.sizeLabel.hide()

            # show directory widgets
            self.homeDirPathLabel.setHidden(False)
            self.pagesStack.setCurrentWidget(self.fileManager)
            self.homeDirCountLabel.setHidden(False)
            self.homeDirNameLabel.setHidden(False)
            self.browseButton.setHidden(False)
            self.prevButton.setHidden(False)
            self.nextButton.setHidden(False)
            self.homeButton.setHidden(False)
            self.driveIconLabel.setHidden(False)
            self.lockButton.setHidden(False)
            self.unhideButton.setHidden(False)
            self.vaultButton.setText("Vault")