Esempio n. 1
0
    def get_editor(self):
        """
        Return an editor object based on QScintilla if available.
        Else, return a standard editor.
        """

        try:
            from PyQt4.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs
            
            textedit = QsciScintilla(self)
            textedit.setAutoIndent(True)
            textedit.setAutoCompletionThreshold(2)
            textedit.setAutoCompletionSource(QsciScintilla.AcsDocument)

            # API
            lex = QsciLexerPython(textedit)
            textedit.setLexer(lex)

#             apis = QsciAPIs(lex)
#             apis.prepare()
            
            textedit.setMinimumWidth(250)
            textedit.setMinimumHeight(250)
            
        except ImportError:
            textedit = qt.QtGui.QTextEdit(self)
            textedit.setLineWrapMode(qt.QtGui.QTextEdit.NoWrap)
            textedit.setMinimumWidth(200)
            textedit.setMinimumHeight(200)

        return textedit
Esempio n. 2
0
 def setLexer(self, lex=None):
     """ Sets the new lexer or resets if None """
     QsciScintilla.setLexer(self, lex)
     if lex is None:
         self.clearStyles()
     self._charWidth = -1
     self._lineHeight = -1
     return
Esempio n. 3
0
 def setLexer( self, lex = None ):
     """ Sets the new lexer or resets if None """
     QsciScintilla.setLexer( self, lex )
     if lex is None:
         self.clearStyles()
     self._charWidth = -1
     self._lineHeight = -1
     return
Esempio n. 4
0
 def setLexer(self, lex = None):
     """
     Public method to set the lexer.
     
     @param lex the lexer to be set or None to reset it.
     """
     QsciScintilla.setLexer(self, lex)
     if lex is None:
         self.clearStyles()
Esempio n. 5
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle("Custom Lexer For Config Files")
        self.setGeometry(50, 200, 400, 400)
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setCentralWidget(self.editor)
        self.lexer = ConfigLexer(self.editor)
        self.editor.setLexer(self.lexer)
        self.editor.setText(_sample)
Esempio n. 6
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Custom Lexer For Config Files')
        self.setGeometry(50, 200, 400, 400)
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setCentralWidget(self.editor)
        self.lexer = ConfigLexer(self.editor)
        self.editor.setLexer(self.lexer)
        self.editor.setText(_sample)
Esempio n. 7
0
class MainWindow(QMainWindow):
     def __init__(self):
         QMainWindow.__init__(self)
         self.setWindowTitle('Custom Lexer For Config Files')
         self.setGeometry(50, 200, 400, 400)
         self.editor = QsciScintilla(self)
         self.editor.setUtf8(True)
         self.editor.setMarginWidth(2, 15)
         self.editor.setFolding(True)
         self.setCentralWidget(self.editor)
         self.lexer = ConfigLexer(self.editor)
         self.editor.setLexer(self.lexer)
         self.editor.setText(_sample)
Esempio n. 8
0
    def newtab(self, tw, tname):
        newtab = QtGui.QWidget()
        vlayout = QtGui.QVBoxLayout()
        vlayout.setMargin(0)

        neweditor = QsciScintilla(newtab)
        neweditor.setStyleSheet("border:0")
        self.setupui(neweditor, self.font)
        neweditor.setLexer(self.lexer)

        vlayout.addWidget(neweditor)
        newtab.setLayout(vlayout)

        return tw.addTab(newtab, os.path.basename(str(tname))), neweditor
    def newtab(self, tw, tname):
        newtab = QtGui.QWidget()
        vlayout = QtGui.QVBoxLayout()
        vlayout.setMargin(0)

        neweditor = QsciScintilla(newtab)
        neweditor.setStyleSheet("border:0")
        self.setupui(neweditor, self.font)
        neweditor.setLexer(self.lexer)

        vlayout.addWidget(neweditor)
        newtab.setLayout(vlayout)

        return tw.addTab(newtab, os.path.basename(str(tname))), neweditor
Esempio n. 10
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Custom Lexer For Config Files')
        self.setGeometry(50, 200, 400, 400)

        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle) # + OR - TO FOLD OR UNFOLD
        self.editor.setMarginLineNumbers(1, True) # LINES' NUMBER IN THE MARGIN
        self.editor.setMarginWidth(1, QString("-------")) # OK for 3 digits. This was found by direct tests...
        self.editor.setLexer(ConfigLexer(self.editor))
        self.editor.setText(_sample)

        self.setCentralWidget(self.editor)
Esempio n. 11
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Custom Lexer For Config Files')
        self.setGeometry(50, 200, 400, 400)
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)

# LINES' NUMBER IN THE MARGIN
        self.editor.setMarginLineNumbers(1,True)
        self.editor.setMarginWidth(1, QString("-------"))
                # OK for 3 digits. This was found by direct tests...
# WRAPING
        self.editor.setWrapMode(True)

        self.setCentralWidget(self.editor)
        self.lexer = ConfigLexer(self.editor)
        self.editor.setLexer(self.lexer)
        self.editor.setText(_sample)
Esempio n. 12
0
class MainWindow(QMainWindow):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setWindowTitle('Custom Lexer For Config Files')
        self.setGeometry(50, 200, 400, 400)
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)

        # LINES' NUMBER IN THE MARGIN
        self.editor.setMarginLineNumbers(1, True)
        self.editor.setMarginWidth(1, QString("-------"))
        # OK for 3 digits. This was found by direct tests...
        # WRAPING
        self.editor.setWrapMode(True)

        self.setCentralWidget(self.editor)
        self.lexer = ConfigLexer(self.editor)
        self.editor.setLexer(self.lexer)
        self.editor.setText(_sample)
Esempio n. 13
0
class ScriptEditor(QWidget):
    '''
    classdocs
    '''
    def __init__(self, filename='', parent=None):
        '''
        Constructor
        '''
        QWidget.__init__(self, parent)

        self.filename = filename
        self.label = 'untitled'
        self.modified = False

        self.layout = QVBoxLayout(self)
        self.editor = QsciScintilla()
        self.layout.addWidget(self.editor, stretch=1)

        # Give the editor its content
        if len(filename) > 0:
            # Open the file and read in its contents
            f = open(filename, 'r')
            contents = f.read()
            self.editor.setText(contents)
            f.close()

            self.label = os.path.basename(filename)

        # Setup the features of the editor
        lexer = QsciLexerJavaScript()
        self.editor.setLexer(lexer)

        # Connect signals
        self.editor.textChanged.connect(self.onTextChanged)

    def hasFile(self):
        return len(self.filename) > 0

    def onTextChanged(self):
        self.modified = True
Esempio n. 14
0
File: main.py Progetto: obmarg/pyvis
    def Setup( self, parentWidget ):
        editor = QsciScintilla( parentWidget )
        size = parentWidget.size()
        editor.resize( size.width() / 2, size.height() ) 
        
        # Set up the font
        font = QtGui.QFont()
        font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(13)
        fm = QtGui.QFontMetrics(font)

        editor.setFont( font )
        editor.setMarginsFont( font )

        # Add in line numbers
        editor.setMarginWidth( 0, fm.width("000") + 5 )
        editor.setMarginLineNumbers( 0, True )

        editor.setBraceMatching( QsciScintilla.SloppyBraceMatch )

        # Set up a python lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont( font )
        editor.setLexer( lexer )

        # Set up indentation
        editor.setAutoIndent( True )
        editor.setIndentationsUseTabs( False )
        editor.setTabWidth( 4 )

        self.editor = editor

        self.editor.linesChanged.connect( self.OnLineChange )
        self.editor.textChanged.connect( self.OnChange )

        timer = QtCore.QTimer( self )
        timer.timeout.connect( self.OnTick )
        timer.start( 500 )
Esempio n. 15
0
    def initEditor(self):
        editor = QsciScintilla()

        ## define the font to use
        font = QtGui.QFont()
        #font.setFamily("Consolas")
        font.setFixedPitch(True)
        font.setPointSize(9)
        # the font metrics here will help
        # building the margin width later
        fm = QtGui.QFontMetrics(font)

        ## set the default font of the editor
        ## and take the same font for line numbers
        editor.setFont(font)
        editor.setMarginsFont(font)

        ## Line numbers
        # conventionnaly, margin 0 is for line numbers
        editor.setMarginWidth(0, fm.width("0000"))
        editor.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vetical bar at 80 chars
        editor.setEdgeMode(QsciScintilla.EdgeLine)
        editor.setEdgeColumn(80)
        editor.setEdgeColor(QtGui.QColor("#FF0000"))

        ## Folding visual : we will use boxes
        editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        editor.setCaretLineVisible(True)
        #editor.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

        ## Margins colors
        # line numbers margin
        #editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        #editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        #editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(font)
        editor.setLexer(lexer)

        ## Render on screen
        #editor.show()

        ## Show this file in the editor
        #editor.setText(open("examples\charriot_obj.txt").read())

        # Show all the methods of the editor
        #methods = sorted(QsciScintilla.__dict__.keys())
        #for m in methods :
        #    print m
        #editor.setWidth(400)

        editor.setEolMode(QsciScintilla.EolUnix)
        return editor
Esempio n. 16
0
class ScriptManager(MDialog):
    def __init__(self, _parent):
        MDialog.__init__(self, _parent)
        from PyQt4.Qsci import QsciScintilla, QsciLexerPython, QsciAPIs

        if isActivePyKDE4:
            self.setButtons(MDialog.NoDefault)
        self.sciCommand = QsciScintilla()
        self.sciCommand.setUtf8(True)
        self.sciCommand.setAutoIndent(True)
        self.sciCommand.setIndentationGuides(True)
        self.sciCommand.setIndentationsUseTabs(True)
        self.sciCommand.setCaretLineVisible(True)
        self.sciCommand.setAutoCompletionThreshold(2)
        self.sciCommand.setAutoCompletionSource(QsciScintilla.AcsDocument)
        self.sciCommand.setLexer(QsciLexerPython(self))
        self.sciCommand.setMarginLineNumbers(1, True)
        self.sciCommand.setMarginWidth(1, '0000')
        self.sciCommand.setEolMode(QsciScintilla.EolUnix)
        self.sciCommand.setWrapMode(QsciScintilla.WrapWord)
        lblScriptList = MLabel(translate("ScriptManager", "Script List : "))
        self.currentScriptFileName = None
        self.lwScriptList = Options.MyListWidget(self, [], _currentRowChanged=self.getFromScriptList)
        self.refreshScriptList()
        pbtnCreate = MPushButton(translate("ScriptManager", "Create"))
        pbtnDelete = MPushButton(translate("ScriptManager", "Delete"))
        pbtnSave = MPushButton(translate("ScriptManager", "Save"))
        pbtnScriptManagerAndClose = MPushButton(translate("ScriptManager", "Run And Close"))
        pbtnScriptManager = MPushButton(translate("ScriptManager", "Run"))
        pbtnClose = MPushButton(translate("ScriptManager", "Close"))
        pbtnClear = MPushButton(translate("ScriptManager", "Clear"))
        self.cckbIsAutoSaveScripts = Options.MyCheckBox(self, translate("ScriptManager", "Auto Save"), 2,
                                                        "isAutoSaveScripts")
        self.connect(pbtnCreate, SIGNAL("clicked()"), self.create)
        self.connect(pbtnDelete, SIGNAL("clicked()"), self.delete)
        self.connect(pbtnSave, SIGNAL("clicked()"), self.save)
        self.connect(pbtnScriptManagerAndClose, SIGNAL("clicked()"), self.runScriptAndClose)
        self.connect(pbtnScriptManager, SIGNAL("clicked()"), self.runScript)
        self.connect(pbtnClose, SIGNAL("clicked()"), self.close)
        self.connect(pbtnClear, SIGNAL("clicked()"), self.clear)
        pnlMain = MWidget(self)
        vblMain = MVBoxLayout(pnlMain)
        vbox = MVBoxLayout()
        vbox.addWidget(lblScriptList)
        vbox.addWidget(self.lwScriptList)
        hbox2 = MHBoxLayout()
        hbox2.addWidget(pbtnCreate)
        hbox2.addWidget(pbtnDelete)
        vbox.addLayout(hbox2)
        hbox0 = MHBoxLayout()
        hbox0.addLayout(vbox)
        hbox0.addWidget(self.sciCommand)
        hbox1 = MHBoxLayout()
        hbox1.addWidget(self.cckbIsAutoSaveScripts)
        hbox1.addStretch(1)
        hbox1.addWidget(pbtnClear, 1)
        hbox1.addWidget(pbtnSave, 1)
        hbox1.addWidget(pbtnScriptManager, 1)
        hbox1.addWidget(pbtnScriptManagerAndClose, 1)
        hbox1.addWidget(pbtnClose, 1)
        vblMain.addLayout(hbox0)
        vblMain.addLayout(hbox1)
        if isActivePyKDE4:
            self.setMainWidget(pnlMain)
        else:
            self.setLayout(vblMain)
        self.setWindowTitle(translate("ScriptManager", "Script Manager"))
        self.setWindowIcon(MIcon("Images:scriptManager.png"))
        self.lwScriptList.setMaximumWidth(150)
        self.setMinimumWidth(650)
        self.setMinimumHeight(450)
        self.show()

    def closeEvent(self, _event):
        if self.checkForSave() is False:
            _event.ignore()

    @staticmethod
    def checkScriptManager(_isAlertIfNotAvailable=True):
        try:
            from PyQt4.Qsci import QsciScintilla

            return True
        except:
            if _isAlertIfNotAvailable:
                Dialogs.showError(translate("MenuBar", "Qsci Is Not Installed"),
                                  translate("MenuBar",
                                            "Qsci is not installed on your systems.<br>Please install Qsci on your system and try again."))
            return False

    def getFromScriptList(self, _index=None):
        try:
            if self.checkForSave():
                self.currentScriptFileName = self.scriptList[self.lwScriptList.currentRow()]
                codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                self.sciCommand.setText(str(codes))
        except:
            ReportBug.ReportBug()

    def runScriptAndClose(self):
        try:
            if self.runScript():
                self.close()
        except:
            ReportBug.ReportBug()

    def runScript(self):
        try:
            return Scripts.runScript(str(self.sciCommand.text()))
        except:
            ReportBug.ReportBug()

    def checkForSave(self):
        try:
            if self.currentScriptFileName is not None:
                if fu.isFile(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName)):
                    codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                    if str(codes) != str(self.sciCommand.text()):
                        if self.cckbIsAutoSaveScripts.checkState() == Mt.Checked:
                            self.save()
                        else:
                            answer = Dialogs.ask(translate("ScriptManager", "Do You Wish To Save Your Codes?"),
                                                 translate("ScriptManager",
                                                           "Do you wish to save your codes so that you can continue later?"),
                                                 True)
                            if answer == Dialogs.Yes:
                                self.save()
                            elif answer == Dialogs.Cancel:
                                return False
            return True
        except:
            ReportBug.ReportBug()

    def save(self):
        try:
            codes = Scripts.getScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
            Scripts.saveScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName),
                               str(self.sciCommand.text()))
        except:
            ReportBug.ReportBug()

    def clear(self):
        try:
            answer = Dialogs.ask(translate("ScriptManager", "Your Codes Will Be Deleted!.."),
                                 translate("ScriptManager",
                                           "Your codes will be deleted and the default codes will be installed. Do you wish to clear the current codes?"))
            if answer == Dialogs.Yes:
                Scripts.clearScript(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
        except:
            ReportBug.ReportBug()

    def delete(self):
        try:
            answer = Dialogs.ask(translate("ScriptManager", "Your Script Will Be Deleted!.."),
                                 translate("ScriptManager",
                                           "Your script will be deleted. Are you sure you want to delete current script?"))
            if answer == Dialogs.Yes:
                fu.removeFile(fu.joinPath(Scripts.pathOfScripsDirectory, self.currentScriptFileName))
                self.refreshScriptList()
        except:
            ReportBug.ReportBug()

    def create(self):
        try:
            newScriptFileName = Scripts.createNewScript()
            self.refreshScriptList()
            self.lwScriptList.setCurrentRow(self.scriptList.index(newScriptFileName))
        except:
            ReportBug.ReportBug()

    def refreshScriptList(self):
        try:
            self.scriptList = Scripts.getScriptList()
            self.lwScriptList.refresh(self.scriptList)
            scriptFileName = None
            if len(self.scriptList) > 0:
                scriptFileName = self.scriptList[self.lwScriptList.currentRow()]
            self.currentScriptFileName = scriptFileName
        except:
            ReportBug.ReportBug()
Esempio n. 17
0
    def setupViews(self):
        self.tableViews = {'left': self.tableView_revisions_left,
                           'right': self.tableView_revisions_right}
        # viewers are Scintilla editors
        self.viewers = {}
        # block are diff-block displayers
        self.block = {}
        self.diffblock = blockmatcher.BlockMatch(self.frame)
        lay = QHBoxLayout(self.frame)
        lay.setSpacing(0)
        lay.setContentsMargins(0, 0, 0, 0)

        try:
            contents = open(self.repo.wjoin(self.filename), "rb").read(1024)
            lexer = lexers.get_lexer(self.filename, contents, self)
        except Exception:
            lexer = None

        for side, idx  in (('left', 0), ('right', 3)):
            sci = QsciScintilla(self.frame)
            sci.verticalScrollBar().setFocusPolicy(Qt.StrongFocus)
            sci.setFocusProxy(sci.verticalScrollBar())
            sci.verticalScrollBar().installEventFilter(self)
            sci.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
            sci.setFrameShape(QFrame.NoFrame)
            sci.setMarginLineNumbers(1, True)
            sci.SendScintilla(sci.SCI_SETSELEOLFILLED, True)

            sci.setLexer(lexer)
            if lexer is None:
                sci.setFont(qtlib.getfont('fontdiff').font())

            sci.setReadOnly(True)
            sci.setUtf8(True)
            lay.addWidget(sci)

            # hide margin 0 (markers)
            sci.SendScintilla(sci.SCI_SETMARGINTYPEN, 0, 0)
            sci.SendScintilla(sci.SCI_SETMARGINWIDTHN, 0, 0)
            # setup margin 1 for line numbers only
            sci.SendScintilla(sci.SCI_SETMARGINTYPEN, 1, 1)
            sci.SendScintilla(sci.SCI_SETMARGINWIDTHN, 1, 20)
            sci.SendScintilla(sci.SCI_SETMARGINMASKN, 1, 0)

            # define markers for colorize zones of diff
            self.markerplus = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markerplus, 0xB0FFA0)
            self.markerminus = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markerminus, 0xA0A0FF)
            self.markertriangle = sci.markerDefine(QsciScintilla.Background)
            sci.SendScintilla(sci.SCI_MARKERSETBACK, self.markertriangle, 0xFFA0A0)

            self.viewers[side] = sci
            blk = blockmatcher.BlockList(self.frame)
            blk.linkScrollBar(sci.verticalScrollBar())
            self.diffblock.linkScrollBar(sci.verticalScrollBar(), side)
            lay.insertWidget(idx, blk)
            self.block[side] = blk
        lay.insertWidget(2, self.diffblock)

        for side in sides:
            table = getattr(self, 'tableView_revisions_%s' % side)
            table.setTabKeyNavigation(False)
            #table.installEventFilter(self)
            table.revisionSelected.connect(self.onRevisionSelected)
            table.revisionActivated.connect(self.onRevisionActivated)

            self.viewers[side].verticalScrollBar().valueChanged.connect(
                    lambda value, side=side: self.vbar_changed(value, side))

        self.setTabOrder(table, self.viewers['left'])
        self.setTabOrder(self.viewers['left'], self.viewers['right'])

        # timer used to fill viewers with diff block markers during GUI idle time
        self.timer = QTimer()
        self.timer.setSingleShot(False)
        self.timer.timeout.connect(self.idle_fill_files)
Esempio n. 18
0
    editor = QsciScintilla()

    ## Choose a lexer
    ## This can be any Scintilla lexer, but the original example used Python
    lexer = QsciLexerPython()

    ## Create an API for us to populate with our autocomplete terms
    api = Qsci.QsciAPIs(lexer)
    ## Add autocompletion strings
    api.add("aLongString")
    api.add("aLongerString")
    api.add("aDifferentString")
    api.add("sOmethingElse")
    ## Compile the api for use in the lexer
    api.prepare()

    editor.setLexer(lexer)

    ## Set the length of the string before the editor tries to autocomplete
    ## In practise this would be higher than 1
    ## But its set lower here to make the autocompletion more obvious
    editor.setAutoCompletionThreshold(1)
    ## Tell the editor we are using a QsciAPI for the autocompletion
    editor.setAutoCompletionSource(QsciScintilla.AcsAPIs)

    ## Render on screen
    editor.show()

    ## Show this file in the editor
    editor.setText(open("simple_editor.py").read())
    sys.exit(app.exec_())
Esempio n. 19
0
class Ui_py_de(object):
    def setupUi(self, py_de):
        self.printer = QPrinter()
        self.imagesDir = "images/"

        ####################################
        ## Set up our initial window object
        ####################################

        py_de.setObjectName("py_de")
        py_de.resize(QtCore.QSize(QtCore.QRect(0, 0, 800, 570).size()).expandedTo(py_de.minimumSizeHint()))

        self.centralwidget = QtGui.QTabWidget(py_de)
        self.centralwidget.setObjectName("centralwidget")

        self.centralwidget.setGeometry(QtCore.QRect(50,50,200,200))

	    ####################################
       	## Set up tabs
       	####################################

        self.tab = QtGui.QWidget()
        self.tab.setObjectName("tab")

        self.tablayout = QtGui.QGridLayout(self.tab)

	    ####################################
        ## The actual text box.
        ####################################

        self.textEdit = QsciScintilla(self.tab)

        #####################################
        ### Set the syntax highlighting.
        #####################################

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

        ## set the default font of the editor
        ## and take the same font for line numbers
        self.textEdit.setFont(self.font)
        self.textEdit.setMarginsFont(self.font)

        ## Line numbers
        # conventionaly, margin 0 is for line numbers
        self.textEdit.setMarginWidth(0, self.fm.width( "00000" ) + 5)
        self.textEdit.setMarginLineNumbers(0, True)

        ## Edge Mode shows a red vertical bar at 80 chars
        self.textEdit.setEdgeMode(QsciScintilla.EdgeLine)
        self.textEdit.setEdgeColumn(80)
        self.textEdit.setEdgeColor(QtGui.QColor("#FF0000"))

        ## Folding visual : we will use boxes
        self.textEdit.setFolding(QsciScintilla.BoxedTreeFoldStyle)

        ## Braces matching
        self.textEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        ## Editing line color
        self.textEdit.setCaretLineVisible(True)
        self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

        ## Margins colors
        # line numbers margin
        self.textEdit.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        self.textEdit.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

        # folding margin colors (foreground,background)
        self.textEdit.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

        ## Choose a lexer
        lexer = QsciLexerPython()
        lexer.setDefaultFont(self.font)
        self.textEdit.setLexer(lexer)

        ## Render on screen
        self.textEdit.show()

        ## Show this file in the self.textEdit

        #####################################
        ## end of syntax highlighting.
        #####################################

	    ####################################
        ## Set up the sizes of everything
        ####################################

        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(1))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)
        self.textEdit.setObjectName("textEdit")

        self.tablayout.addWidget(self.textEdit, 0, 0, 1, 1)

        self.centralwidget.addTab(self.tab,"")
        self.centralwidget.setCurrentIndex(0)

        py_de.setCentralWidget(self.centralwidget)

        self.createMenus(py_de)
        self.createActions(py_de)
        self.createToolBar(py_de)

        self.retranslateUi(py_de)

        #self.createTab(py_de)

        conn = QtCore.QObject.connect
        conn(self.actionNewTemplate,QtCore.SIGNAL("activated()"),self.newTemplate)
        conn(self.actionClose,QtCore.SIGNAL("triggered()"),self.closeTab)
        conn(self.actionQuit,QtCore.SIGNAL("activated()"),py_de.close)
        conn(self.actionOpen,QtCore.SIGNAL("activated()"),self.openFile)
        conn(self.actionPrint,QtCore.SIGNAL("activated()"),self.printFile)
        conn(self.actionSave,QtCore.SIGNAL("activated()"),self.saveFile)
        conn(self.actionSave_As,QtCore.SIGNAL("activated()"),self.saveAsFile)
        conn(self.actionSelect_All,QtCore.SIGNAL("activated()"),self.textEdit.selectAll)
        conn(self.actionGoToLine,QtCore.SIGNAL("activated()"),self.goToLine)
        conn(self.actionCopy,QtCore.SIGNAL("activated()"),self.textEdit.copy)
        conn(self.actionCut,QtCore.SIGNAL("activated()"),self.textEdit.cut)
        conn(self.actionPaste,QtCore.SIGNAL("activated()"),self.textEdit.paste)
        conn(self.actionPython_File,QtCore.SIGNAL("activated()"),self.newPythonFile)
        conn(self.actionC,QtCore.SIGNAL("activated()"),self.newCFile)
        conn(self.actionC_Header_File_h,QtCore.SIGNAL("activated()"),self.newCHeaderFile)
        conn(self.actionFortran,QtCore.SIGNAL("activated()"),self.newFortranFile)
        conn(self.actionPython_File,QtCore.SIGNAL("activated()"),lambda x="py":self.template(x))
        conn(self.actionC,QtCore.SIGNAL("activated()"),lambda x="cpp":self.template(x))
        conn(self.actionFortran,QtCore.SIGNAL("activated()"),lambda x="f":self.template(x))


        QtCore.QMetaObject.connectSlotsByName(py_de)


	    ####################################
        ## Method for creating a tab
        ####################################

    def createTab(self, py_de, ext, filename=""):
        newTabName = "tab" + str(self.centralwidget.count())
        newTextEditName = "textEdit" + str(self.centralwidget.count())
        print "createTab(): creating tab %s" % (newTabName)
        self.tab = QtGui.QWidget()
        self.tab.setObjectName(newTabName)
        self.tablayout = QtGui.QGridLayout(self.tab)
        self.centralwidget.addTab(self.tab,"")
        newTabIndex = self.centralwidget.indexOf(self.tab)
        if filename == "":
            filename = "Untitled" + str((newTabIndex + 1))
        newTabTitle = str(filename) + str(ext)
        self.centralwidget.setCurrentIndex(self.centralwidget.indexOf(self.tab))
        self.centralwidget.setTabText(newTabIndex, QtGui.QApplication.translate("py_de", newTabTitle, None, QtGui.QApplication.UnicodeUTF8))
        self.textEdit = QsciScintilla(self.tab)
        self.textEdit.setFont(self.font)
        self.textEdit.setMarginsFont(self.font)
        self.textEdit.setMarginWidth(0, self.fm.width( "00000" ) + 5)
        self.textEdit.setMarginLineNumbers(0, True)
        self.textEdit.setEdgeMode(QsciScintilla.EdgeLine)
        self.textEdit.setEdgeColumn(80)
        self.textEdit.setEdgeColor(QtGui.QColor("#FF0000"))
        self.textEdit.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.textEdit.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.textEdit.setCaretLineVisible(True)
        self.textEdit.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))
        self.textEdit.setMarginsBackgroundColor(QtGui.QColor("#333333"))
        self.textEdit.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))
        self.textEdit.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))
        lexer = QsciLexerPython()
        lexer.setDefaultFont(self.font)
        self.textEdit.setLexer(lexer)
        self.textEdit.show()
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Policy(1),QtGui.QSizePolicy.Policy(1))
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.textEdit.sizePolicy().hasHeightForWidth())
        self.textEdit.setSizePolicy(sizePolicy)
        self.textEdit.setObjectName(newTextEditName)
        self.tablayout.addWidget(self.textEdit, 0, 0, 1, 1)


	#####################################
	## Functions for menu button actions
	#####################################

    def openFile(self):
        fileName = QFileDialog.getOpenFileName()
        print fileName
        index = fileName.lastIndexOf("/")
        newFileName = fileName[index+1:]
        print newFileName
        self.createTab(py_de, "", newFileName)
        self.textEdit.setText(open(fileName).read())

    def printFile(self): # Needs some work...
        printDialog = QPrintDialog(self.printer, py_de)
        if printDialog.exec_() == QDialog.Accepted:
            margin = 10
            pageNum = 1
            yPos = 0
            printJob = QPainter()
            printJob.begin(self.printer)
            printJob.setFont(self.font)
            fm = printJob.fontMetrics()

            for i in range(self.textEdit.lines()):
                if margin + yPos > self.printer.height() - margin:
                    pageNum += 1
                    self.printer.newPage()
                    yPos = 0
                printJob.drawText(margin,               # X
                                  margin + yPos,        # Y
                                  self.printer.width(), # Width
                                  self.printer.height(),# Height
                                  QtCore.Qt.AlignTop,       # Alignment
                                  self.textEdit.text(i - 1)# The text to print
                                  )
                yPos += fm.lineSpacing()
            printJob.end

    def saveFile(self):
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def saveAsFile(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+Shft+S", "File|Save As"))
        fileName = QFileDialog.getSaveFileName()
        f = open(fileName, "w")
        f.write(self.textEdit.text())

    def goToLine(self):
        maxLine = str(self.textEdit.lines())
        newLineNumber, ok = QInputDialog.getInteger(self.centralwidget,
                                                    "Go to line",
                                                    "Line number: (1, " + maxLine+")")
        if ok:
            newLineNumber -= 1  # Convert from 1-based to 0-based
            self.textEdit.ensureLineVisible(newLineNumber)
            self.textEdit.setCursorPosition(newLineNumber, 0)
            # TODO: Find docs on qscintilla's gotoline(int)


    def cut(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+X", "Edit|Cut"))

    def copy(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+C", "Edit|Copy"))

    def paste(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+V", "Edit|Paste"))

    def find(self):
        QKeySequence(self.textEdit.trUtf8("Ctrl+F", "Edit|Find"))

    def newPythonFile(self):
        ext = ".py"
        self.createTab(py_de, ext)

    def newCFile(self):
        ext = ".cpp"
        self.createTab(py_de, ext)

    def newCHeaderFile(self):
        ext = ".h"
        self.createTab(py_de, ext)

    def newFortranFile(self):
        ext = ".f"
        self.createTab(py_de, ext)

    def closeTab(self):
        self.centralwidget.removeTab(self.centralwidget.currentIndex())


	    ##################################
        ## Function for adding actions to
	    ## various menu items.
        ##################################

    # Generates python code to create menu items then execs it
    # Should never be passed any input from a user or a file.
    def initAction(self, actionName, menus = None, shortCutKeys = None, iconFileName = None):
        assert actionName[0:6] == "action"
        commands = list()
        commands.append("self." + actionName + "=QtGui.QAction(py_de)")
        if shortCutKeys:
            commands.append("self." + actionName + ".setShortcut('" + shortCutKeys + "')")
        if iconFileName:
           commands.append("self." + actionName + ".setIcon(QtGui.QIcon('" + self.imagesDir + iconFileName + "'))")
        commands.append("self." + actionName + ".setObjectName('" + actionName + "')" )
        if menus:
            assert type(menus) == type(()) or type(menus) == type("string")
            if type(menus) == type("string"): # Add action to only one menu
                commands.append("self." + menus + ".addAction(self." + actionName + ")")
            else: # Menus is a tuple of menus on which to add this action
                for menu in menus:
                    commands.append("self." + menu + ".addAction(self." + actionName + ")")
        for command in commands:
            exec(command, globals(), locals())

    def createActions(self, py_de):
        self.menuFile.addAction(self.menuNew.menuAction())
        self.initAction("actionCopy","menuEdit", "Ctrl+C", "edit-copy.png")
        self.initAction("actionCut", "menuEdit", "Ctrl+X", "edit-cut.png")
        self.initAction("actionPaste", "menuEdit", "Ctrl+V", "edit-paste.png")
        self.initAction("actionSelect_All", "menuEdit", "Ctrl+A", "edit-select-all.png")
        self.initAction("actionFind", "menuEdit", "Ctrl+F", "edit-find.png")
        self.initAction("actionReplace", "menuEdit", "Ctrl+H")
        self.initAction("actionGoToLine", "menuEdit", "Ctrl+G")
        self.initAction("actionOpen", "menuFile", "Ctrl+O", "document-open.png")
        self.initAction("actionSave", "menuFile", "Ctrl+S", "document-save.png")
        self.initAction("actionSave_As", "menuFile", "Ctrl+Shift+S", "document-save-as.png")
        self.initAction("actionPrint", "menuFile", "Ctrl+P", "document-print.png")
        self.initAction("actionClose", "menuFile", "Ctrl+W", "dialog-close.png")
        self.initAction("actionQuit", "menuFile", None, "application-exit.png")
        self.initAction("actionBuild", "menuBuild", "F7", "run-build-file.png")
        self.initAction("actionBuild_All", "menuBuild", "Ctrl+Alt+F7", "run-build.png")
        self.initAction("actionRun", "menuBuild", "F5", "arrow-right.png")
        self.initAction("actionClean", "menuBuild", "Ctrl+Shift+C", "edit-clear.png")
        self.initAction("actionAbout", "menuHelp", None, "help-about.png")
        self.initAction("actionSelect_Language", None, None, None)
        self.initAction("actionFortran", "menuNew", None, "file-fortran.png")
        self.initAction("actionC", "menuNew", None, "file-cpp.png")
        self.initAction("actionPython_File", "menuNew", "file-python.png")
        self.initAction("actionC_Header_File_h", "menuNew", None, "file-header.png")
        self.initAction("actionNewTemplate", ("menuNew", "menuTools"), None, "document-new.png")

        self.menuNew.setIcon(QtGui.QIcon(self.imagesDir + "document-new.png"))
        self.menuTools.addAction(self.menuFormat.menuAction())

        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())
        self.menubar.addAction(self.menuBuild.menuAction())
        self.menubar.addAction(self.menuTools.menuAction())
        self.menubar.addAction(self.menuHelp.menuAction())

	    ####################################
        ## Method for creating a toolbar
        ####################################

    def createToolBar(self, py_de):
        self.toolBar = QtGui.QToolBar(py_de)
        self.toolBar.setObjectName("toolBar")
        py_de.addToolBar(QtCore.Qt.TopToolBarArea,self.toolBar)

        self.toolBar.addAction(self.actionBuild)


	    ####################################
        ## Method for creating menus
        ####################################

    def createMenus(self, py_de):
        self.menubar = QtGui.QMenuBar(py_de)
        self.menubar.setGeometry(QtCore.QRect(0,0,502,26))
        self.menubar.setObjectName("menubar")

        self.menuFile = QtGui.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")

        self.menuNew = QtGui.QMenu(self.menuFile)
        self.menuNew.setObjectName("menuNew")

        self.menuEdit = QtGui.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")

        self.menuBuild = QtGui.QMenu(self.menubar)
        self.menuBuild.setObjectName("menuBuild")

        self.menuTools = QtGui.QMenu(self.menubar)
        self.menuTools.setObjectName("menuTools")

        self.menuFormat = QtGui.QMenu(self.menuTools)
        self.menuFormat.setObjectName("menuFormat")

        self.menuHelp = QtGui.QMenu(self.menubar)
        self.menuHelp.setObjectName("menuHelp")
        py_de.setMenuBar(self.menubar)

    def retranslateUi(self, py_de):
        py_de.setWindowTitle(QtGui.QApplication.translate("py_de", "py_de", None, QtGui.QApplication.UnicodeUTF8))
        self.menuFile.setTitle(QtGui.QApplication.translate("py_de", "File", None, QtGui.QApplication.UnicodeUTF8))
        self.menuNew.setTitle(QtGui.QApplication.translate("py_de", "New", None, QtGui.QApplication.UnicodeUTF8))
        self.menuEdit.setTitle(QtGui.QApplication.translate("py_de", "Edit", None, QtGui.QApplication.UnicodeUTF8))
        self.menuBuild.setTitle(QtGui.QApplication.translate("py_de", "Build", None, QtGui.QApplication.UnicodeUTF8))
        self.menuTools.setTitle(QtGui.QApplication.translate("py_de", "Tools", None, QtGui.QApplication.UnicodeUTF8))
        self.menuFormat.setTitle(QtGui.QApplication.translate("py_de", "Format", None, QtGui.QApplication.UnicodeUTF8))
        self.menuHelp.setTitle(QtGui.QApplication.translate("py_de", "Help", None, QtGui.QApplication.UnicodeUTF8))
        self.toolBar.setWindowTitle(QtGui.QApplication.translate("py_de", "py_de", None, QtGui.QApplication.UnicodeUTF8))
        self.actionCopy.setText(QtGui.QApplication.translate("py_de", "Copy", None, QtGui.QApplication.UnicodeUTF8))
        self.actionCut.setText(QtGui.QApplication.translate("py_de", "Cut", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPaste.setText(QtGui.QApplication.translate("py_de", "Paste", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSelect_All.setText(QtGui.QApplication.translate("py_de", "Select All", None, QtGui.QApplication.UnicodeUTF8))
        self.actionFind.setText(QtGui.QApplication.translate("py_de", "Find", None, QtGui.QApplication.UnicodeUTF8))
        self.actionReplace.setText(QtGui.QApplication.translate("py_de", "Replace", None, QtGui.QApplication.UnicodeUTF8))
        self.actionGoToLine.setText(QtGui.QApplication.translate("py_de", "Go To Line", None, QtGui.QApplication.UnicodeUTF8))
        self.actionOpen.setText(QtGui.QApplication.translate("py_de", "Open", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSave.setText(QtGui.QApplication.translate("py_de", "Save", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSave_As.setText(QtGui.QApplication.translate("py_de", "Save As", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPrint.setText(QtGui.QApplication.translate("py_de", "Print", None, QtGui.QApplication.UnicodeUTF8))
        self.actionClose.setText(QtGui.QApplication.translate("py_de", "Close", None, QtGui.QApplication.UnicodeUTF8))
        self.actionQuit.setText(QtGui.QApplication.translate("py_de", "Quit Py-DE", None, QtGui.QApplication.UnicodeUTF8))
        self.actionBuild.setText(QtGui.QApplication.translate("py_de", "Build", None, QtGui.QApplication.UnicodeUTF8))
        self.actionBuild_All.setText(QtGui.QApplication.translate("py_de", "Build All", None, QtGui.QApplication.UnicodeUTF8))
        self.actionRun.setText(QtGui.QApplication.translate("py_de", "Run", None, QtGui.QApplication.UnicodeUTF8))
        self.actionClean.setText(QtGui.QApplication.translate("py_de", "Clean", None, QtGui.QApplication.UnicodeUTF8))
        self.actionAbout.setText(QtGui.QApplication.translate("py_de", "About Py-DE", None, QtGui.QApplication.UnicodeUTF8))
        self.actionSelect_Language.setText(QtGui.QApplication.translate("py_de", "Select Language", None, QtGui.QApplication.UnicodeUTF8))
        self.actionFortran.setText(QtGui.QApplication.translate("py_de", "Fortran File (.f)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionC.setText(QtGui.QApplication.translate("py_de", "C++ Implementation File (.cpp)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionPython_File.setText(QtGui.QApplication.translate("py_de", "Python File (.py)", None, QtGui.QApplication.UnicodeUTF8))
        self.actionC_Header_File_h.setText(QtGui.QApplication.translate("py_de", "C++ Header File (.h)", None, QtGui.QApplication.UnicodeUTF8))
        self.centralwidget.setTabText(self.centralwidget.indexOf(self.tab), QtGui.QApplication.translate("py_de", "Untitled 1", None, QtGui.QApplication.UnicodeUTF8))
        self.actionNewTemplate.setText(QtGui.QApplication.translate("py_de", "Add file as new template", None, QtGui.QApplication.UnicodeUTF8))

    def newTemplate(self):
      o = pydeTemplates.pydeTemplates("templates")

      listLanguage = QtCore.QStringList()
      listLanguage.append("Fortran")
      listLanguage.append("Python")
      listLanguage.append("C++")

      language, res = QtGui.QInputDialog.getItem(self.centralwidget,
           QtGui.QApplication.translate("py_de", "Language templates", None, QtGui.QApplication.UnicodeUTF8),
           QtGui.QApplication.translate("py_de", "Choose language", None, QtGui.QApplication.UnicodeUTF8),
           listLanguage)
      if res:
        templateName, res = QtGui.QInputDialog.getText(self.centralwidget,
            QtGui.QApplication.translate("py_de", "Template name", None, QtGui.QApplication.UnicodeUTF8),
            QtGui.QApplication.translate("py_de", "Template name", None, QtGui.QApplication.UnicodeUTF8))
        if res:
          lang=""
          if language == "Fortran":
            lang="f"
          elif language == "C++":
            lang="cpp"
          elif language == "Python":
            lang="py"
        o.newTemplate(self.textEdit.text(), lang, templateName)

    def template(self, language):
      # Upgrade: in tools menu, add some functionalities for templates (add/remove template...) -

      #load list of templates for language selected
      o = pydeTemplates.pydeTemplates("templates")
      templates  = QtCore.QStringList(o.getTemplatesListOf(language))
      templates.prepend("Empty")

      #display dialogbox with a listbox containing list of templates
      template, res = QtGui.QInputDialog.getItem(self.centralwidget,
           QtGui.QApplication.translate("py_de", "Language templates", None, QtGui.QApplication.UnicodeUTF8),
           QtGui.QApplication.translate("py_de", "Choose template", None, QtGui.QApplication.UnicodeUTF8),
           templates)
      if res:
        #load template in the editor
        self.textEdit.setText(o.loadTemplate(language, template))
Esempio n. 20
0
class EditorWidget(QtGui.QWidget):
    def __init__(self, parent, main, arduino_mode=False):
        QtGui.QWidget.__init__(self)

        self.main = main
        self.current_file_path = None
        self.board = "board_name"
        self.port = "Sanderman"

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setContentsMargins(0, 0, 0, 0)
        mainLayout.setSpacing(0)
        self.setLayout(mainLayout)

        ##############################################################
        ### File Info Bar at the top
        ##############################################################
        fileInfoBox = QtGui.QHBoxLayout()
        mainLayout.addLayout(fileInfoBox, 0)

        self.lblFileName = QtGui.QLabel(self)
        self.lblFileName.setText("Filename")
        style_grad = "background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #efefef, stop: 1 %s);" % "#6A7885"
        style_grad += "font-weight: bold; border: 1px outset #41484E; padding: 3px;"
        self.lblFileName.setStyleSheet(style_grad)
        fileInfoBox.addWidget(self.lblFileName, 4)

        #########################################
        ## Save Button
        self.buttonSave = QtGui.QPushButton(self)
        self.buttonSave.setText("Save")
        self.buttonSave.setIcon(Icon(Ico.Save))
        fileInfoBox.addWidget(self.buttonSave)
        self.connect(self.buttonSave, QtCore.SIGNAL("clicked()"),
                     self.on_save_button_clicked)

        ###########################################
        ## Actions button with dropdown menu
        buttActions = QtGui.QPushButton(self)
        buttActions.setText("Actions")
        buttActions.setIcon(Icon(Ico.Green))
        fileInfoBox.addWidget(buttActions)

        fileActionsMenu = QtGui.QMenu(buttActions)
        buttActions.setMenu(fileActionsMenu)
        self.fileActionsGroup = QtGui.QActionGroup(self)
        self.connect(self.fileActionsGroup,
                     QtCore.SIGNAL("triggered(QAction*)"), self.on_file_action)
        for act in [['rename', 'Rename'], ['copy', 'Copy'],
                    ['commit', 'Commit']]:
            nuAction = fileActionsMenu.addAction(act[1])
            nuAction.setProperty('action_name', act[0])
            # TODO - maybe this should be in button group

        ####################################################
        ## Scintilla Editor
        ####################################################
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.editor.setMarginLineNumbers(1, True)
        self.editor.setMarginWidth(1, 30)
        self.editor.setAutoIndent(True)
        mainLayout.addWidget(self.editor, 200)

        bottomStatusBar = QtGui.QStatusBar(self)
        mainLayout.addWidget(bottomStatusBar, 0)

        #########################################
        ## File Size and Modified info
        self.lblFileSize = GenericWidgets.StatusLabel(self, "Size")
        bottomStatusBar.addPermanentWidget(self.lblFileSize)

        self.lblFileModified = GenericWidgets.StatusLabel(self, "Modified")
        bottomStatusBar.addPermanentWidget(self.lblFileModified)

        ##############################################################
        ### Arduino Compiler With compile and board selector
        ##############################################################
        """if arduino_mode:
			self.arduinoBar = ArduinoCompilerBar(self, self.main)
			self.connect(self.arduinoBar, QtCore.SIGNAL("compile_action"), self.on_compile_action)
			self.editorCompilerSplitter.addWidget(self.arduinoBar)
			pass

		
		self.terminalWidget = None
		if arduino_mode:
			self.terminalWidget = TerminalWidget(self, self.main)
			self.editorTerminalSplitter.addWidget(self.terminalWidget)

			self.editorCompilerSplitter.setStretchFactor(0, 2)
			self.editorCompilerSplitter.setStretchFactor(1, 0)
	
			self.editorTerminalSplitter.setStretchFactor(0, 5)
			self.editorTerminalSplitter.setStretchFactor(1, 2)
		"""

    def on_save_button_clicked(self):
        self.write_file()
        self.emit(QtCore.SIGNAL("file_saved"), "file_name")  # TODO

    def on_file_action(self, butt):
        print "on_file_action", butt  # TODO

    ##########################################
    ## Extensions
    ##########################################
    ## TODO - make this a list of allowed extension, we also need png and image viewer, xml etc in browser ?
    ## nick what u think ?
    def supported(self):
        """returns a list of supportes extensions"""
        extensions = [
            'pde', 'c', 'h', 'cpp', 'cxx', 'java', 'py', 'pyw', 'pl', 'sh',
            'html', 'yaml', 'txt'
        ]
        return extensions

    def ignored(self):
        """returns a list of ignored extensions"""  ## TODO - image viewer
        extensions = ['pyc', 'png', 'gif', 'jpeg']
        return extensions

    def DEADload_keywords(self):
        words_file = settings.keywords_path().absoluteFilePath(
            "/keywords_ripped.txt")
        words_str = app.utils.get_file_contents(words_file)
        word_lines = words_str.split("\n")
        for line in word_lines:
            #print line
            line = line.trimmed()
            #print "..", line
            if line.length() > 0:
                if not line.startsWith("#"):
                    line = str(line)
                    parts = line.split(" ")
                    #print parts
                    for p in parts:
                        print "==", p
                    keyword = parts[0]
                    print "#%s#" % keyword
                    self.arduinoFunctionsAPI.add(keyword)

    def find_lexer(self, extension):
        extension = extension.toLower()
        #TODO: This is horrible and evil. Fix it.
        for extensions, lexer in extension_map:
            if extension in extensions:
                return lexer()
        # Fallback
        return QsciLexerCPP()

    def set_source(self, source, extension=None):
        self.editor.setText(source)
        self.lexer = self.find_lexer(extension)
        print "lex=", self.lexer
        self.editor.setLexer(self.lexer)

    ########################################################
    ## Load file, detects extension and ignores pyc etc
    ########################################################
    def load_file(self, file_path, tabIndex=None):
        fileInfo = QtCore.QFileInfo(file_path)

        if fileInfo.isDir():
            #self.emit(QtCore.SIGNAL("open_file"), None)
            self.editor.setText("")
            self.lblFileName.setText("")
            self.lblFileSize.setText("")
            self.lblFileModified.setText("")
            self.current_file_path = None
            return

        self.current_file_path = fileInfo.filePath()
        file_name_string = QtCore.QString("<b>").append(
            fileInfo.fileName()).append("</b>")
        self.lblFileName.setText(file_name_string)
        self.lblFileSize.setText("%sB" % fileInfo.size())
        self.lblFileModified.setText(
            "%s" %
            fileInfo.lastModified().toString(QtCore.Qt.SystemLocaleShortDate))
        source = app.utils.get_file_contents(fileInfo.filePath())

        ## unique Files
        if fileInfo.fileName() == 'Makefile':
            self.set_source(source, 'Makefile')
            return

        ## Ignored extension
        if fileInfo.suffix() in self.ignored():
            file_name_string.append("  <small> *** ignored ***</small>")
            self.lblFileName.setText(file_name_string)
            self.editor.setText("")
            return

        if not fileInfo.suffix() in self.supported():
            file_name_string.append("  <small> *** not supported ***</small>")
            self.lblFileName.setText(file_name_string)
            self.editor.setText("")
            return

        ## load file
        txt = app.utils.get_file_contents(fileInfo.filePath())
        self.emit(QtCore.SIGNAL("open_file"), fileInfo.filePath())
        #self.editor.set_source(txt)
        ## QsciLexerCPP, QsciLexerMakefile, QsciLexerJava, QsciLexerHTML, QsciLexerPerl, QsciLexerPython, QsciLexerYAML
        ## TODO MAkefile and show images
        #print "YES>>", fileInfo.suffix(), fileInfo.fileName(), fileInfo.filePath()

        self.set_source(txt, fileInfo.suffix())

    ######################################################################
    ## Write File
    ######################################################################
    def save_file(self):
        #print self.current_file_path
        file2Write = QtCore.QFile(self.current_file_path)
        if not file2Write.open(QtCore.QIODevice.WriteOnly
                               | QtCore.QIODevice.Text):
            print "TODO: error writing file"
            return False
        stream_out = QtCore.QTextStream(file2Write)
        stream_out << self.editor.text()
        file2Write.close()
        return True
Esempio n. 21
0
class FromWidget(QWidget):

    def __init__(self, parent):
        super(FromWidget, self).__init__(parent)
        
        #add the text editor to the widget.        
        self.text = QsciScintilla(self)
        self.text.setGeometry(10,100,500,500)
        
        #set the code to be read to Python code        
        self.lexer = QsciLexerPython()

        ## Create an API for us to populate with our autocomplete terms
        self.generate_code = Qsci.QsciAPIs(self.lexer)
        
        ## Add autocompletion strings
        self.generate_code.add("set_image")
        self.generate_code.add("draw_actor")

        # Compile the api for use in the lexer
        self.generate_code.prepare()

        #sets the program code in the text editor to the generated code        
        self.open_generated_code()

        #set the lext         
        self.text.setLexer(self.lexer)

        #Set the length of the string before the editor tries to autocomplete
        self.text.setAutoCompletionThreshold(1)
        
        #Tell the editor we are using a QsciAPI for the autocompletion
        self.text.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        #set the background and foreground colour of the margin        
        self.text.setMarginsBackgroundColor(QColor(34,139,34))
        self.text.setMarginsForegroundColor(QColor(0,0,0))
        
        #set the line numbers from 1        
        self.text.setMarginLineNumbers(1,True) 
        self.text.setAutoIndent(True)
        self.text.setIndentationsUseTabs(False)
       
        #allow the user to collapse code        
        self.text.setFolding(1)

        self.create_buttons()
        self.buttons_controler()

    #function to creat buttons    
    def create_buttons(self):
        #create runcode button and add it to the widget              
        self.runcodebutton = QtGui.QPushButton("Run Code",self)
        self.runcodebutton.setGeometry(100,610,70,30)
        
        #create generatecode button and add it to the widget
        self.generatecodebutton = QtGui.QPushButton("Generate Template",self)
        self.generatecodebutton.setGeometry(400,5,100,30)

        #create savecode button and add it to the widget
        self.savecodebutton = QtGui.QPushButton("Save Code",self)
        self.savecodebutton.setGeometry(10,610,70,30)

    #signals which connects buttons to actions     
    def buttons_controler(self):
        self.runcodebutton.clicked.connect(self.run_code_button_clicked)
        self.generatecodebutton.clicked.connect(self.gen_code_button_clicked)
        self.savecodebutton.clicked.connect(self.askQuestion)

    #opens the generated program code    
    def open_generated_code(self):
        self.filename ='marioexample2.py'
        f = open(self.filename, 'r')
        filedata = f.read()
        self.text.setText(filedata)
        f.close()

    #performs action for run code button        
    def run_code_button_clicked(self):
        interpreter = InteractiveInterpreter()
        interpreter.runcode(self.text.text())

    #perfoms action for generate code button
    def gen_code_button_clicked(self):
        #ask if user is sure theu could like to regenerate code, in dialogue
        quit_msg = "Are you sure you would like to regenerate your program code, your current\ncode will be overidden unless you save your code."
        answer = QtGui.QMessageBox.question(self, 'Pygame Simplfied message', 
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        #if the users answer is yes, regenerate the code       
        if answer == QtGui.QMessageBox.Yes:
            self.filename ='marioexample2.py'
            f = open(self.filename, 'r')
            filedata = f.read()
            self.text.setText(filedata)
            f.close()

    #if the user clicks the save button, the code is saved    
    def save(self):
        f = open('mygame.py', 'w')
        #gets the text from the text editor        
        filedata = self.text.text()
        f.write(filedata)
        f.close()

    #check if user wants to save their program    
    def askQuestion(self, event):
        quit_msg = "Are you would like to save your program?\nthis will save as mygame.py"
        answer = QtGui.QMessageBox.question(self, 'Pygame Simplfied message', 
                     quit_msg, QtGui.QMessageBox.Yes, QtGui.QMessageBox.No)

        if answer == QtGui.QMessageBox.Yes:
            self.save()
Esempio n. 22
0
from PyQt4 import QtGui,QtCore
from PyQt4.Qsci import QsciScintilla, QsciLexerCPP
import sys

app = QtGui.QApplication(sys.argv)
window = QtGui.QWidget()

scint = QsciScintilla(window)
lex = QsciLexerCPP(window,False)
scint.setLexer(lex)
window.show()

sys.exit( app.exec_() )
Esempio n. 23
0
    def createNewTab(self, filename, msg, lexer):
        if type(msg) is bytes:
            msg = msg.decode(encoding='utf-8')
        if str(msg).find("\r\n") >= 0:
            msg = msg.replace('\n', '')
        elif str(msg).find("\n") >= 0 and str(msg).find("\r") < 0:
            msg = msg.replace("\n", "\r")
        else:
            print("creatNewTab has other endswith.")

        editor = QsciScintilla()
        editor.setUtf8(True)
        editor.setLexer(lexer)
        editor.setMarginsBackgroundColor(QColor(220, 220, 220))
        editor.setAutoCompletionThreshold(2)
        editor.setAutoCompletionSource(QsciScintilla.AcsAll)
        editor.setEolMode(QsciScintilla.EolUnix)

        if str(filename).find("/") >= 0:
            tabname = filename.split("/")
            tabname = tabname[-1]
        elif str(filename) == "untitled":
            tabname = "untitled"
        else:
            tabname = filename

        self.addTab(editor, tabname)
        self.setTabToolTip(self.count() - 1, filename)

        if filename == "untitled":
            self.tabBar().setTabTextColor(self.count() - 1, QColor(Qt.red))
            self.setTabIcon(self.count() - 1, QIcon(':/pc.png'))
            if self.ui.currentBoard == "microbit":
                msg = "from microbit import *\r#write your program:\r"
        elif str(filename).find(":") > 0:
            self.tabBar().setTabTextColor(self.count() - 1, QColor(Qt.red))
            self.setTabIcon(self.count() - 1, QIcon(':/pc.png'))
        else:
            self.tabBar().setTabTextColor(self.count() - 1, QColor(Qt.blue))
            self.setTabIcon(self.count() - 1, QIcon(':/ic.png'))

        editor.setText(msg)

        editor.setContextMenuPolicy(Qt.CustomContextMenu)
        self.connect(editor,
                     SIGNAL("customContextMenuRequested(const QPoint&)"),
                     self.slotEditorRightClickMenu)

        if self.editorRightMenu == None:
            self.editorRightMenu = QMenu(self)
            self.editorRightMenu.setStyleSheet(
                "QMenu::item{padding:4px 16px;}"
                "QMenu::item::selected{background-color:rgb(135,206,255);}")

            undo = QAction(self.tr("Undo"), self)
            undo.setShortcut("Ctrl+Z")
            self.connect(undo, SIGNAL("triggered()"), self.slotUndo)

            redo = QAction(self.tr("Redo"), self)
            redo.setShortcut("Ctrl+Y")
            self.connect(redo, SIGNAL("triggered()"), self.slotRedo)

            cut = QAction(self.tr("Cut"), self)
            cut.setShortcut("Ctrl+X")
            self.connect(cut, SIGNAL("triggered()"), self.slotCut)

            copy = QAction(self.tr("Copy"), self)
            copy.setShortcut("Ctrl+C")
            self.connect(copy, SIGNAL("triggered()"), self.slotCopy)

            paste = QAction(self.tr("Paste"), self)
            paste.setShortcut("Ctrl+V")
            self.connect(paste, SIGNAL("triggered()"), self.slotPaste)

            self.editorRightMenu.addAction(undo)
            self.editorRightMenu.addAction(redo)
            self.editorRightMenu.addAction(cut)
            self.editorRightMenu.addAction(copy)
            self.editorRightMenu.addAction(paste)

        #set brace match
        editor.setBraceMatching(editor.StrictBraceMatch)

        #set indent replace 4 space
        editor.setIndentationsUseTabs(False)
        editor.setTabWidth(2)

        #The line number display area
        editor.setMarginType(0, QsciScintilla.NumberMargin)
        editor.setMarginLineNumbers(0, True)
        editor.setMarginWidth(0, 30)

        #set auto indentation
        editor.setAutoIndent(True)

        #syntax check
        editor.setMarginType(1, QsciScintilla.SymbolMargin)
        editor.setMarginLineNumbers(1, False)
        editor.setMarginWidth(1, 5)
        editor.setMarginSensitivity(1, False)
        editor.setMarginMarkerMask(1, 0x1FFFFFF)
        editor.markerDefine(QsciScintilla.Background, 1)

        #Automatic folding area
        editor.setFolding(QsciScintilla.CircledFoldStyle)

        #set tab's stylesheet
        editor.setStyleSheet(
            "QWidget{font-size:20px;border: 1px solid white;border-radius:1px}"
        )

        self.setCurrentWidget(editor)
        if filename != "untitled":
            self.fileitem.size += 1
            self.fileitem.list.append(filename)

        self.connect(editor, SIGNAL("textChanged()"), self.editorTextChange)
        self.connect(editor, SIGNAL("selectionChanged()"),
                     self.selectionChanged)
        self.connect(editor, SIGNAL("linesChanged()"), self.linesChanged)
        self.connect(editor, SIGNAL("cursorPositionChanged(int,int)"),
                     self.cursorPositionChanged)
        self.connect(editor, SIGNAL("userListActivated(int,const QString)"),
                     self.userListActivated)
Esempio n. 24
0
 def setLexer(self, lexer):
     QsciScintilla.setLexer(self, lexer)
     # store the lexer locally to avoid garbage collection killing it
     self.__lexer = lexer
     self.updateConfig()
Esempio n. 25
0
 def setLexer(self, lexer):
     QsciScintilla.setLexer(self, lexer)
     # store the lexer locally to avoid garbage collection killing it
     self.__lexer = lexer
     self.updateConfig()
Esempio n. 26
0
  def initEditor(self):
    editor = QsciScintilla()

    ## define the font to use
    font = QtGui.QFont()
    #font.setFamily("Consolas")
    font.setFixedPitch(True)
    font.setPointSize(9)
    # the font metrics here will help
    # building the margin width later
    fm = QtGui.QFontMetrics(font)

    ## set the default font of the editor
    ## and take the same font for line numbers
    editor.setFont(font)
    editor.setMarginsFont(font)

    ## Line numbers
    # conventionnaly, margin 0 is for line numbers
    editor.setMarginWidth(0, fm.width( "0000"))
    editor.setMarginLineNumbers(0, True)

    ## Edge Mode shows a red vetical bar at 80 chars
    editor.setEdgeMode(QsciScintilla.EdgeLine)
    editor.setEdgeColumn(80)
    editor.setEdgeColor(QtGui.QColor("#FF0000"))

    ## Folding visual : we will use boxes
    editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)

    ## Braces matching
    editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)

    ## Editing line color
    editor.setCaretLineVisible(True)
    #editor.setCaretLineBackgroundColor(QtGui.QColor("#F5F5DC"))

    ## Margins colors
    # line numbers margin
    #editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    #editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    #editor.setFoldMarginColors(QtGui.QColor("#99CC66"),QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython()
    lexer.setDefaultFont(font)
    editor.setLexer(lexer)

    ## Render on screen
    #editor.show()

    ## Show this file in the editor
    #editor.setText(open("examples\charriot_obj.txt").read())
    
    # Show all the methods of the editor
    #methods = sorted(QsciScintilla.__dict__.keys())
    #for m in methods :
    #    print m
    #editor.setWidth(400)
    
    editor.setEolMode(QsciScintilla.EolUnix)
    return editor
Esempio n. 27
0
class EditorWidget(QtGui.QWidget):
    def __init__(self, parent, main, arduino_mode=False):
        QtGui.QWidget.__init__(self)

        self.main = main
        self.current_file_path = None

        mainLayout = QtGui.QVBoxLayout()
        mainLayout.setContentsMargins(0, 0, 0, 0)
        mainLayout.setSpacing(0)
        self.setLayout(mainLayout)

        ##############################################################
        ### File Info Bar
        ##############################################################
        hbox = QtGui.QHBoxLayout()
        mainLayout.addLayout(hbox)

        self.lblFileName = QtGui.QLabel(self)
        self.lblFileName.setText("Filename")
        style_grad = "background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #efefef, stop: 1 %s);" % "#6A7885"
        style_grad += "font-weight: bold; border: 1px outset #41484E; padding: 3px;"
        self.lblFileName.setStyleSheet(style_grad)
        hbox.addWidget(self.lblFileName, 4)

        self.lblFileSize = GenericWidgets.StatusLabel(self, "Size")
        hbox.addWidget(self.lblFileSize, 1)

        self.lblFileModified = GenericWidgets.StatusLabel(self, "Modified")
        hbox.addWidget(self.lblFileModified, 2)

        ##############################################################
        ### Arduino Compiler
        ##############################################################
        if arduino_mode:
            toolbar = QtGui.QToolBar()
            toolbar.setToolButtonStyle(QtCore.Qt.ToolButtonTextBesideIcon)
            mainLayout.addWidget(toolbar)

            ## spacer for right
            toolbar.addWidget(GenericWidgets.ToolBarSpacer(self))

            ### Action Buttons
            buttz = []
            buttz.append(['Compile', Ico.Compile])
            buttz.append(['Upload', Ico.Upload])
            buttz.append(['Compile Upload', Ico.CompileUpload])
            self.buttCompileGroup = QtGui.QButtonGroup()
            self.connect(self.buttCompileGroup,
                         QtCore.SIGNAL("buttonClicked (QAbstractButton *)"),
                         self.on_compile_group_button)
            ## TODO connect
            for caption, ico in buttz:
                butt = QtGui.QPushButton()
                butt.setText(caption)
                butt.setIcon(Icon(ico))
                toolbar.addWidget(butt)
                self.buttCompileGroup.addButton(butt)
            toolbar.addSeparator()

        ####################################################
        ## Source Editor
        ####################################################
        self.editor = QsciScintilla(self)
        self.editor.setUtf8(True)
        self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.editor.setMarginLineNumbers(1, True)
        self.editor.setAutoIndent(True)
        mainLayout.addWidget(self.editor, 3)

        ## The Syntax Higlighter = standard CPP atmo = cish
        #self.lexer = ArduinoLexer(self)
        #self.editor.setLexer(self.lexer)

        ## Aarduino API Functions
        #self.arduinoFunctionsAPI = QsciAPIs(self.lexer)
        #keywords_file = self.main.settings.api_path().append("/autocomplete.txt")

        #self.arduinoFunctionsAPI.load(keywords_file)
        #self.arduinoFunctionsAPI.prepare()
        #self.lexer.setAPIs(self.arduinoFunctionsAPI)

        #self.editor.setAutoCompletionThreshold(1);
        #self.editor.setAutoCompletionSource(QsciScintilla.AcsAPIs);

        if arduino_mode:
            self.terminalWidget = TerminalWidget(self, self.main)
            mainLayout.addWidget(self.terminalWidget, 1)

    ##########################################
    ## Extensions
    ##########################################
    def supported(self):
        """returns a list of supportes extensions"""
        extensions = [
            'pde', 'c', 'h', 'cpp', 'cxx', 'java', 'py', 'pl', 'sh', 'html',
            'yaml', 'txt'
        ]
        return extensions

    def ignored(self):
        """returns a list of ignored extensions"""  ## TODO - image viewer
        extensions = ['pyc', 'png', 'gif', 'jpeg']
        return extensions

    ##########################################
    ## Compile Upload Buttons
    ##########################################
    def on_compile_group_button(self, butt):
        print "COMP", butt.text()
        if butt.text() == "Compile":
            self.write_file()
            self.compile_file()
        else:
            self.main.status.showMessage("Not recognised", 4000)

    def compile_file(self):
        self.terminalWidget.compile(self.current_file_path)

    def on_upload(self):
        print "upload"

    def load_keywords(self):
        words_file = self.main.settings.keywords_path().append(
            "/keywords_ripped.txt")
        words_str = self.main.ut.get_file_contents(words_file)
        word_lines = words_str.split("\n")
        for line in word_lines:
            #print line
            line = line.trimmed()
            #print "..", line
            if line.length() > 0:
                if not line.startsWith("#"):
                    line = str(line)
                    parts = line.split(" ")
                    #print parts
                    for p in parts:
                        print "==", p
                    keyword = parts[0]
                    print "#%s#" % keyword
                    self.arduinoFunctionsAPI.add(keyword)

    def find_lexer(self, extension):
        extension = extension.toLower()
        #TODO: This is horrible and evil. Fix it.
        for extensions, lexer in extension_map:
            if extension in extensions:
                return lexer()
        # Fallback
        return QsciLexerCPP()

    def set_source(self, source, extension=None):

        self.editor.setText(source)
        self.lexer = self.find_lexer(extension)
        self.editor.setLexer(self.lexer)

    def load_file(self, file_path, tabIndex=None):
        print "file_path", file_path
        fileInfo = QtCore.QFileInfo(file_path)

        if fileInfo.isDir():
            #self.emit(QtCore.SIGNAL("open_file"), None)
            self.editor.setText("")
            self.lblFileName.setText("")
            self.lblFileSize.setText("")
            self.lblFileModified.setText("")
            self.current_file_path = None
            return

        self.current_file_path = fileInfo.filePath()
        file_name_string = QtCore.QString("<b>").append(
            fileInfo.fileName()).append("</b>")
        self.lblFileName.setText(file_name_string)
        self.lblFileSize.setText("%s" % fileInfo.size())
        self.lblFileModified.setText(
            "%s" %
            fileInfo.lastModified().toString(QtCore.Qt.SystemLocaleShortDate))
        source = self.main.ut.get_file_contents(fileInfo.filePath())

        ## unique Files
        if fileInfo.fileName() == 'Makefile':
            self.set_source(source, 'Makefile')
            return

        ## Ignored extension
        if fileInfo.suffix() in self.ignored():
            file_name_string.append("  <small> *** ignored ***</small>")
            self.lblFileName.setText(file_name_string)
            self.editor.setText("")
            return

        if not fileInfo.suffix() in self.supported():
            file_name_string.append("  <small> *** not supported ***</small>")
            self.lblFileName.setText(file_name_string)
            self.editor.setText("")
            return

        ## load file
        txt = self.main.ut.get_file_contents(fileInfo.filePath())
        self.emit(QtCore.SIGNAL("open_file"), fileInfo.filePath())
        #self.editor.set_source(txt)
        ## QsciLexerCPP, QsciLexerMakefile, QsciLexerJava, QsciLexerHTML, QsciLexerPerl, QsciLexerPython, QsciLexerYAML
        ## TODO MAkefile and show images
        print "YES>>", fileInfo.suffix(), fileInfo.fileName(
        ), fileInfo.filePath()

        self.set_source(txt, fileInfo.suffix())

    ######################################################################
    ## Write File
    ######################################################################
    def write_file(self):
        file2Write = QtCore.QFile(self.current_file_path)
        if not file2Write.open(QtCore.QIODevice.WriteOnly
                               | QtCore.QIODevice.Text):
            print "TODO: error writing file"
            return
        stream_out = QtCore.QTextStream(file2Write)
        stream_out << self.editor.text()
        file2Write.close()
Esempio n. 28
0
    editor.setCaretLineVisible(True)
    editor.setCaretLineBackgroundColor(QtGui.QColor("#CDA869"))

    ## Margins colors
    # line numbers margin
    editor.setMarginsBackgroundColor(QtGui.QColor("#333333"))
    editor.setMarginsForegroundColor(QtGui.QColor("#CCCCCC"))

    # folding margin colors (foreground,background)
    editor.setFoldMarginColors(QtGui.QColor("#99CC66"),
                               QtGui.QColor("#333300"))

    ## Choose a lexer
    lexer = QsciLexerPython1()

    lexer.setDefaultFont(font)
    editor.setLexer(lexer)
    myApis = QsciAPIs(lexer)
    myApis.add(QtCore.QString("SDR"))
    myApis.add(QtCore.QString("sdr"))
    myApis.prepare()
    editor.setAutoCompletionSource(QsciScintilla.AcsAll)
    editor.setAutoCompletionCaseSensitivity(False)
    editor.setAutoCompletionThreshold(1)

    ## Render on screen
    editor.show()

    ## Show this file in the editor
    editor.setText(open("chardet.txt").read())
    sys.exit(app.exec_())
Esempio n. 29
0
class EditorWidget(QtGui.QWidget):

	def __init__(self, parent, main, arduino_mode=False):
		QtGui.QWidget.__init__(self)

		self.main = main
		self.current_file_path = None
		self.board= "board_name"
		self.port = "Sanderman"

		mainLayout = QtGui.QVBoxLayout()
		mainLayout.setContentsMargins(0, 0, 0, 0)
		mainLayout.setSpacing(0)
		self.setLayout(mainLayout)

		##############################################################
		### File Info Bar at the top
		##############################################################
		fileInfoBox = QtGui.QHBoxLayout()
		mainLayout.addLayout(fileInfoBox, 0)

		self.lblFileName = QtGui.QLabel(self)
		self.lblFileName.setText("Filename")
		style_grad = "background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #efefef, stop: 1 %s);" % "#6A7885"
		style_grad += "font-weight: bold; border: 1px outset #41484E; padding: 3px;"
		self.lblFileName.setStyleSheet(style_grad)
		fileInfoBox.addWidget(self.lblFileName, 4)

		#########################################
		## Save Button
		self.buttonSave = QtGui.QPushButton(self)
		self.buttonSave.setText("Save") 
		self.buttonSave.setIcon(Icon(Ico.Save))
		fileInfoBox.addWidget(self.buttonSave)
		self.connect(self.buttonSave, QtCore.SIGNAL("clicked()"), self.on_save_button_clicked)

		###########################################
		## Actions button with dropdown menu
		buttActions = QtGui.QPushButton(self)
		buttActions.setText("Actions")
		buttActions.setIcon(Icon(Ico.Green))
		fileInfoBox.addWidget(buttActions)
		
		fileActionsMenu = QtGui.QMenu(buttActions)
		buttActions.setMenu(fileActionsMenu)
		self.fileActionsGroup = QtGui.QActionGroup(self)
		self.connect(self.fileActionsGroup, QtCore.SIGNAL("triggered(QAction*)"), self.on_file_action)
		for act in [['rename', 'Rename'], ['copy','Copy'],['commit','Commit']]:
			nuAction = fileActionsMenu.addAction(act[1])
			nuAction.setProperty('action_name', act[0])
			# TODO - maybe this should be in button group	
		

			
		####################################################
		## Scintilla Editor
		####################################################
		self.editor = QsciScintilla(self)
		self.editor.setUtf8(True)
		self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
		self.editor.setMarginLineNumbers(1, True)
		self.editor.setMarginWidth(1, 30)
		self.editor.setAutoIndent(True)
		mainLayout.addWidget(self.editor, 200)

		bottomStatusBar = QtGui.QStatusBar(self)
		mainLayout.addWidget(bottomStatusBar, 0)

		#########################################
		## File Size and Modified info
		self.lblFileSize = GenericWidgets.StatusLabel(self, "Size")
		bottomStatusBar.addPermanentWidget(self.lblFileSize)

		self.lblFileModified = GenericWidgets.StatusLabel(self, "Modified")
		bottomStatusBar.addPermanentWidget(self.lblFileModified)


		##############################################################
		### Arduino Compiler With compile and board selector
		##############################################################
		"""if arduino_mode:
			self.arduinoBar = ArduinoCompilerBar(self, self.main)
			self.connect(self.arduinoBar, QtCore.SIGNAL("compile_action"), self.on_compile_action)
			self.editorCompilerSplitter.addWidget(self.arduinoBar)
			pass

		
		self.terminalWidget = None
		if arduino_mode:
			self.terminalWidget = TerminalWidget(self, self.main)
			self.editorTerminalSplitter.addWidget(self.terminalWidget)

			self.editorCompilerSplitter.setStretchFactor(0, 2)
			self.editorCompilerSplitter.setStretchFactor(1, 0)
	
			self.editorTerminalSplitter.setStretchFactor(0, 5)
			self.editorTerminalSplitter.setStretchFactor(1, 2)
		"""

	def on_save_button_clicked(self):
		self.write_file()
		self.emit(QtCore.SIGNAL("file_saved"), "file_name") # TODO

	def on_file_action(self, butt):
		print "on_file_action", butt # TODO

		

	##########################################
	## Extensions
	##########################################
	## TODO - make this a list of allowed extension, we also need png and image viewer, xml etc in browser ?
	## nick what u think ?
	def supported(self):
		"""returns a list of supportes extensions"""
		extensions = [	'pde', 'c','h','cpp','cxx', 
						'java', 'py', 'pyw',  'pl', 'sh', 
						'html', 'yaml', 
						'txt'
					]
		return extensions

	def ignored(self):
		"""returns a list of ignored extensions""" ## TODO - image viewer
		extensions = [	'pyc', 'png','gif','jpeg' ]
		return extensions


	def DEADload_keywords(self):
		words_file = settings.keywords_path().absoluteFilePath("/keywords_ripped.txt")
		words_str = app.utils.get_file_contents(words_file)
		word_lines = words_str.split("\n")
		for line in word_lines:
			#print line
			line = line.trimmed()
			#print "..", line
			if line.length() > 0:
				if not line.startsWith("#"):
					line = str(line)
					parts = line.split(" ")
					#print parts
					for p in parts:
						print "==", p
					keyword = parts[0]
					print "#%s#" % keyword
					self.arduinoFunctionsAPI.add(keyword)


	def find_lexer(self, extension):
		extension = extension.toLower()
		#TODO: This is horrible and evil. Fix it.
		for extensions, lexer in extension_map:
			if extension in extensions:
				return lexer()
		# Fallback
		return QsciLexerCPP()

	def set_source(self, source, extension=None):
		self.editor.setText(source)
		self.lexer = self.find_lexer(extension)
		print "lex=", self.lexer
		self.editor.setLexer(self.lexer)

	########################################################
	## Load file, detects extension and ignores pyc etc
	########################################################
	def load_file(self, file_path, tabIndex=None):
		fileInfo = QtCore.QFileInfo(file_path)

		if fileInfo.isDir():
			#self.emit(QtCore.SIGNAL("open_file"), None)
			self.editor.setText("")
			self.lblFileName.setText("")
			self.lblFileSize.setText("")
			self.lblFileModified.setText("")
			self.current_file_path = None
			return

		self.current_file_path = fileInfo.filePath()
		file_name_string = QtCore.QString("<b>").append(fileInfo.fileName()).append("</b>")
		self.lblFileName.setText(file_name_string)
		self.lblFileSize.setText("%sB" % fileInfo.size())
		self.lblFileModified.setText("%s" % fileInfo.lastModified().toString(QtCore.Qt.SystemLocaleShortDate))
		source = app.utils.get_file_contents(fileInfo.filePath())

		## unique Files
		if fileInfo.fileName() == 'Makefile':
			self.set_source(source, 'Makefile' )
			return

		## Ignored extension
		if fileInfo.suffix() in self.ignored():
			file_name_string.append("  <small> *** ignored ***</small>")
			self.lblFileName.setText(file_name_string)
			self.editor.setText("")
			return
		
		if not fileInfo.suffix() in self.supported():
			file_name_string.append("  <small> *** not supported ***</small>")		
			self.lblFileName.setText(file_name_string)
			self.editor.setText("")
			return

		## load file
		txt = app.utils.get_file_contents(fileInfo.filePath())
		self.emit(QtCore.SIGNAL("open_file"), fileInfo.filePath())
		#self.editor.set_source(txt)
			## QsciLexerCPP, QsciLexerMakefile, QsciLexerJava, QsciLexerHTML, QsciLexerPerl, QsciLexerPython, QsciLexerYAML
		## TODO MAkefile and show images
		#print "YES>>", fileInfo.suffix(), fileInfo.fileName(), fileInfo.filePath()

		self.set_source( txt, fileInfo.suffix())

	######################################################################
	## Write File
	######################################################################
	def save_file(self):
		#print self.current_file_path
		file2Write = QtCore.QFile(self.current_file_path)
		if not file2Write.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text):
			print "TODO: error writing file"
			return False
		stream_out = QtCore.QTextStream(file2Write)
		stream_out << self.editor.text()
		file2Write.close()
		return True
Esempio n. 30
0
class editor(QtGui.QWidget):
   def __init__(self, parent, main):
       QtGui.QWidget.__init__(self)

       self.__Dir = os.path.dirname(sys.argv[0])
       self.icons =  os.path.join(self.__Dir, 'icons/')

       self.main = main

       mainLayout = QtGui.QVBoxLayout()
       mainLayout.setContentsMargins(0, 0, 0, 0)
       mainLayout.setSpacing(0)
       self.setLayout(mainLayout)

       self.editor = QsciScintilla(self)

       self.font = QtGui.QFont()
       self.font.setFamily("Consolas")
       self.font.setFixedPitch(True)
       self.font.setPointSize(10)
       self.fm = QtGui.QFontMetrics(self.font)
       self.editor.setFont(self.font)
       self.editor.setMarginsFont(self.font)
       self.editor.setMarginWidth(0, self.fm.width( "0000" ))

       self.editor.setMarginLineNumbers(0, True)
       self.editor.setUtf8(True)
       self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
       self.editor.setBraceMatching(QsciScintilla.SloppyBraceMatch)
       self.editor.setCaretLineVisible(True)
       self.editor.setCaretLineBackgroundColor(QtGui.QColor('#bfbfbf'))
       self.editor.setMarginsBackgroundColor(QtGui.QColor('#3e3e3e'))
       self.editor.setMarginsForegroundColor(QtGui.QColor('#aaff00'))
       self.editor.setFoldMarginColors(QtGui.QColor('#ff0000'),QtGui.QColor('#000000'))
       lexer = QsciLexerPython()
       self.editor.setLexer(lexer)

       fileBox = QtGui.QHBoxLayout()
       mainLayout.addLayout(fileBox, 0)

       self.saveAsButton = QtGui.QPushButton(self)
       self.saveAsButton.setText("Save As")
       self.saveAsButton.setIcon(QtGui.QIcon(self.icons+'save.png')) 
       fileBox.addWidget(self.saveAsButton)
       self.connect(self.saveAsButton, QtCore.SIGNAL("clicked()"), self.saveAs)

       self.saveButton = QtGui.QPushButton(self)
       self.saveButton.setText("Save")
       self.saveButton.setIcon(QtGui.QIcon(self.icons+'save.png')) 
       fileBox.addWidget(self.saveButton)
       self.connect(self.saveButton, QtCore.SIGNAL("clicked()"), self.save)

       self.openButton = QtGui.QPushButton(self)
       self.openButton.setText("Open") 
       self.openButton.setIcon(QtGui.QIcon(self.icons+'open.png')) 
       fileBox.addWidget(self.openButton)
       self.connect(self.openButton, QtCore.SIGNAL("clicked()"), self.openFile)

       mainLayout.addWidget(self.editor, 200)

       self.CurrentfileName = ''

   def openFile(self):
      self.fn = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home', '')
      if self.fn.isEmpty():
          return
      self.fileName = str(self.fn)
      try:
          self.f = open(self.fileName,'r').read()
          self.editor.setText(self.f)
      except:
          return
      self.CurrentfileName = self.fileName

   def openArg(self, fileName):
      self.f = open(self.fileName,'r').read()
      self.editor.setText(self.f)

   def saveAs(self):
      self.fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '')
      try:
          self.f = open(str(self.fn),'w+r')
      except:
          return
      self.f.write(str(self.editor.text()))
      self.f.close()

   def getTitle(self):
      return self.CurrentfileName

   def save(self):
      try:
          self.f = open(self.CurrentfileName,'w+r')
      except:
          return
      self.f.write(str(self.editor.text()))
      self.f.close()

   def closeEvent(self, event):
      if (self.editor.isModified() == True):
          if (self.filename == ""):
              ret = QtGui.QMessageBox.warning(self, "PyTe",
                          "The Code has been modified.\n"
                          "Do you want to save your changes?",
                          QtGui.QMessageBox.Save | QtGui.QMessageBox.Discard |
                          QtGui.QMessageBox.Cancel)
              if ret == QtGui.QMessageBox.Save:
                  self.fn = QtGui.QFileDialog.getSaveFileName(self, 'Save File', '')
                  try:
                     self.f = open(str(self.fn),'w+r')
                  except:
                     return
                  self.f.write(str(self.text()))
                  self.f.close()
                  event.accept()
              elif ret == QtGui.QMessageBox.Cancel:
                  event.ignore()
      else:
          try:
              self.f = open(self.CurrentfileName,'w+r')
          except:
              return
          self.f.write(str(self.text()))
          self.f.close()
          event.accept()
Esempio n. 31
0
class EditorWidget(QtGui.QWidget):

	def __init__(self, parent, main, arduino_mode=False):
		QtGui.QWidget.__init__(self)

		self.main = main
		self.current_file_path = None
		self.board= "board_name"
		self.port = "Sanderman"

		mainLayout = QtGui.QVBoxLayout()
		mainLayout.setContentsMargins(0, 0, 0, 0)
		mainLayout.setSpacing(0)
		self.setLayout(mainLayout)

		##############################################################
		### File Info Bar at the top
		##############################################################
		fileInfoBox = QtGui.QHBoxLayout()
		mainLayout.addLayout(fileInfoBox, 0)

		self.lblFileName = QtGui.QLabel(self)
		self.lblFileName.setText("Filename")
		style_grad = "background-color: qlineargradient(x1: 0, y1: 0, x2: 1, y2: 0, stop: 0 #efefef, stop: 1 %s);" % "#6A7885"
		style_grad += "font-weight: bold; border: 1px outset #41484E; padding: 3px;"
		self.lblFileName.setStyleSheet(style_grad)
		fileInfoBox.addWidget(self.lblFileName, 4)

		#########################################
		## Project File Actions
		butt = QtGui.QPushButton(self)
		butt.setText("Copy")
		fileInfoBox.addWidget(butt)

		butt = QtGui.QPushButton(self)
		butt.setText("Rename")
		fileInfoBox.addWidget(butt)

		## TODO detect gitor svn or hg etc
		butt = QtGui.QPushButton(self)
		butt.setText("Commit")
		fileInfoBox.addWidget(butt)

		#########################################
		## File Size and Modified info
		self.lblFileSize = GenericWidgets.StatusLabel(self, "Size")
		fileInfoBox.addWidget(self.lblFileSize, 1)

		self.lblFileModified = GenericWidgets.StatusLabel(self, "Modified")
		fileInfoBox.addWidget(self.lblFileModified, 2)

		#########################################
		## Middle splitter, editor on left, Compiler on right
		#########################################
		self.editorCompilerSplitter = QtGui.QSplitter(self)
		mainLayout.addWidget(self.editorCompilerSplitter, 20)
		self.editorCompilerSplitter.setOrientation(QtCore.Qt.Horizontal)
		

			
		####################################################
		## Source Editor
		####################################################

		self.editorTerminalSplitter = QtGui.QSplitter(self)
		self.editorTerminalSplitter.setOrientation(QtCore.Qt.Vertical)
		self.editorCompilerSplitter.addWidget(self.editorTerminalSplitter)

		self.editor = QsciScintilla(self)
		self.editor.setUtf8(True)
		self.editor.setFolding(QsciScintilla.BoxedTreeFoldStyle)
		self.editor.setMarginLineNumbers(1, True)
		self.editor.setAutoIndent(True)
		self.editorTerminalSplitter.addWidget(self.editor)



		##############################################################
		### Arduino Compiler With compile and board selector
		##############################################################
		if arduino_mode:
			self.arduinoBar = ArduinoCompilerBar(self, self.main)
			self.connect(self.arduinoBar, QtCore.SIGNAL("compile_action"), self.on_compile_action)
			self.editorCompilerSplitter.addWidget(self.arduinoBar)
			pass

		
		self.terminalWidget = None
		if arduino_mode:
			self.terminalWidget = TerminalWidget(self, self.main)
			self.editorTerminalSplitter.addWidget(self.terminalWidget)


		self.editorCompilerSplitter.setStretchFactor(0, 2)
 		self.editorCompilerSplitter.setStretchFactor(1, 0)

		self.editorTerminalSplitter.setStretchFactor(0, 5)
		self.editorTerminalSplitter.setStretchFactor(1, 1)

	def on_compile_action(self, compile_action):
		print "on_compile_action", compile_action
		compiler = app.Compiler.Compiler(self)
		#print compiler
		
		#self.connect(compiler, QtCore.SIGNAL("compile_error"), self.terminalWidget.on_compile_error)
		#self.connect(compiler, QtCore.SIGNAL("compile_result"), self.terminalWidget.on_compile_result)
		self.connect(compiler, QtCore.SIGNAL("compile_log"), self.terminalWidget.on_compile_log)
		compiler.ard_make(board = self.board, port=self.port, file_to_compile=self.current_file_path)

	def on_compiler_event(self):
		print "on_compiler_event"
		

	##########################################
	## Extensions
	##########################################
	## TODO - make this a list of allowed extension, we also need png and image viewer, xml etc in browser ?
	## nick what u think ?
	def supported(self):
		"""returns a list of supportes extensions"""
		extensions = [	'pde', 'c','h','cpp','cxx', 
						'java', 'py', 'pyw',  'pl', 'sh', 
						'html', 'yaml', 
						'txt'
					]
		return extensions

	def ignored(self):
		"""returns a list of ignored extensions""" ## TODO - image viewer
		extensions = [	'pyc', 'png','gif','jpeg' ]
		return extensions





	def on_upload(self):
		print "upload"


	def DEADload_keywords(self):
		words_file = settings.keywords_path().absoluteFilePath("/keywords_ripped.txt")
		words_str = app.utils.get_file_contents(words_file)
		word_lines = words_str.split("\n")
		for line in word_lines:
			#print line
			line = line.trimmed()
			#print "..", line
			if line.length() > 0:
				if not line.startsWith("#"):
					line = str(line)
					parts = line.split(" ")
					#print parts
					for p in parts:
						print "==", p
					keyword = parts[0]
					print "#%s#" % keyword
					self.arduinoFunctionsAPI.add(keyword)


	def find_lexer(self, extension):
		extension = extension.toLower()
		#TODO: This is horrible and evil. Fix it.
		for extensions, lexer in extension_map:
			if extension in extensions:
				return lexer()
		# Fallback
		return QsciLexerCPP()

	def set_source(self, source, extension=None):

		self.editor.setText(source)
		self.lexer = self.find_lexer(extension)
		self.editor.setLexer(self.lexer)

	def load_file(self, file_path, tabIndex=None):
		print "file_path", file_path
		fileInfo = QtCore.QFileInfo(file_path)

		if fileInfo.isDir():
			#self.emit(QtCore.SIGNAL("open_file"), None)
			self.editor.setText("")
			self.lblFileName.setText("")
			self.lblFileSize.setText("")
			self.lblFileModified.setText("")
			self.current_file_path = None
			return

		self.current_file_path = fileInfo.filePath()
		file_name_string = QtCore.QString("<b>").append(fileInfo.fileName()).append("</b>")
		self.lblFileName.setText(file_name_string)
		self.lblFileSize.setText("%sB" % fileInfo.size())
		self.lblFileModified.setText("%s" % fileInfo.lastModified().toString(QtCore.Qt.SystemLocaleShortDate))
		source = app.utils.get_file_contents(fileInfo.filePath())

		## unique Files
		if fileInfo.fileName() == 'Makefile':
			self.set_source(source, 'Makefile' )
			return

		## Ignored extension
		if fileInfo.suffix() in self.ignored():
			file_name_string.append("  <small> *** ignored ***</small>")
			self.lblFileName.setText(file_name_string)
			self.editor.setText("")
			return
		
		if not fileInfo.suffix() in self.supported():
			file_name_string.append("  <small> *** not supported ***</small>")		
			self.lblFileName.setText(file_name_string)
			self.editor.setText("")
			return

		## load file
		txt = app.utils.get_file_contents(fileInfo.filePath())
		self.emit(QtCore.SIGNAL("open_file"), fileInfo.filePath())
		#self.editor.set_source(txt)
			## QsciLexerCPP, QsciLexerMakefile, QsciLexerJava, QsciLexerHTML, QsciLexerPerl, QsciLexerPython, QsciLexerYAML
		## TODO MAkefile and show images
		print "YES>>", fileInfo.suffix(), fileInfo.fileName(), fileInfo.filePath()

		self.set_source( txt, fileInfo.suffix())

	######################################################################
	## Write File
	######################################################################
	def write_file(self):
		file2Write = QtCore.QFile(self.current_file_path)
		if not file2Write.open(QtCore.QIODevice.WriteOnly | QtCore.QIODevice.Text):
			print "TODO: error writing file"
			return
		stream_out = QtCore.QTextStream(file2Write)
		stream_out << self.editor.text()
		file2Write.close()