def create_new_tab(self, title, data=None):
        # TODO: this doesn't use the font size of the existing tab, even though it inherits the palette

        insertion_index = self.ui.tabs_WID.count() - 1

        # build new tab
        tab_wid = QtGui.QWidget()
        text_edit = QtGui.QPlainTextEdit()
        text_edit.setPalette(self.ui.script_TEXT.palette())

        # TODO: add data, add QPlainTextEdit
        # use this to create the first tab?

        self.ui.tabs_WID.insertTab(insertion_index, tab_wid, title)
        self.ui.tabs_WID.setCurrentIndex(insertion_index)
        new_tab = self.ui.tabs_WID.widget(insertion_index)

        vert_layout = QtGui.QVBoxLayout()
        new_tab.setLayout(vert_layout)
        vert_layout.addWidget(text_edit)
        vert_layout.setContentsMargins(3, 3, 3, 3)

        # set tab text edit
        new_tab.text_wid = text_edit
        # set tab width to feel like 4 spaces
        new_tab.text_wid.setTabStopWidth(20)
        new_tab.text_wid.setLineWrapMode(QtGui.QPlainTextEdit.NoWrap)

        # connect the syntax highlighter
        highlight = syntax.PythonHighlighter(new_tab.text_wid.document())

        # add data if available
        if data:
            text_edit.setPlainText(data)
Exemple #2
0
 def on_button_clicked(self, num):
     """
     Receives integers from button click to use for calling example script
     """
     if exconfig.button_num != num and exconfig.is_green != num:
         tab_num = int(floor(num / 10)) - 1
         row_num = num % 10
         self.tab_buttons[tab_num][row_num].setStyleSheet(
             'QPushButton {font-family: Verdana;border-width: 3px;border-color:#111111;border-style: solid;border-radius: 7;background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E0F1E0, stop: 0.1 #C1E3C1, stop: 0.49 #A3D6A3, stop: 0.5 #84C884, stop: 1 #66BB66)}'
         )
         self.tab_buttons[tab_num][row_num].setText('Run Example')
         exconfig.button_num = num
         old_tab_num = int(floor(exconfig.is_green / 10)) - 1
         old_row_num = exconfig.is_green % 10
         self.tab_buttons[old_tab_num][old_row_num].setStyleSheet(
             'QPushButton {font-family: Verdana;border-width: 2px;border-color:#666666;border-style: solid;border-radius: 7;background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #B8E2EF, stop: 0.1 #A5DBEB, stop: 0.49 #8CD1E6, stop: 0.5 #7BCAE1, stop: 1 #57BCD9)}'
         )
         self.tab_buttons[old_tab_num][old_row_num].setText(
             self.tab_buttons[old_tab_num][old_row_num].label)
         exconfig.is_green = num
         syntax.PythonHighlighter(self.editor.document())
         self.editor.show()
         _text_file = compile(
             "infile = open(self.dir+'ex_" + str(exconfig.is_green) +
             ".py', 'r')", '<string>', 'exec')
         exec(_text_file)
         self.editor.setPlainText(infile.read())
     else:
         self.moveout()
         exconfig.tab = int(floor(num / 10)) - 1
         exconfig.option = num
         self.close()
    def __init__(self, parent=None):
        """ This class houses the entire editor interface, including
            most functions related to text editing
        """

        # initialize the editor
        super(self.__class__, self).__init__()
        self.setupUi(self)

        self.root = os.path.realpath(
            __file__)  # where to find defaults.py and assets
        self.root = os.path.dirname(self.root)
        self.root += '\\'

        for font in os.listdir(self.root + 'fonts'):
            QtGui.QFontDatabase.addApplicationFont(self.root + 'fonts\\' +
                                                   font)
            print('font initted:', font)

        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap(self.root + "icon.png"),
                       QtGui.QIcon.Normal, QtGui.QIcon.Off)

        self.setWindowIcon(icon)

        self.color_mode = defaults.color_mode

        self.system = system()  # from platform module
        if self.system == 'Windows':
            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                'edit')

        # set up the editor style
        self.fontsize = defaults.font_size
        self.highlighter = syntax.PythonHighlighter(self.textEdit,
                                                    self.color_mode)

        self.actionSetup()
        self.buttonSetup()
        self.closeFind()
        self.flipTheme(override=True)
        self.messageText.setVisible(0)

        # set up properties of this specific python script
        if len(sys.argv) == 1:
            self.file = ''
        else:
            self.file = sys.argv[1]
            self.open(no_dialog=True)

        self.setWindowTitle(self.windowTitle() + '*')
        self.textEdit.textChanged.connect(self.textChange)
        self.textEdit.cursorPositionChanged.connect(self.textCursorChange)

        self.findText.textChanged.connect(self.findTextChange)
        self.replaceText.textChanged.connect(self.replaceTextChange)

        self.setupFont()
        self.captureHistory()  # prime the undo buffer
        self.textEdit.setFocus()
Exemple #4
0
 def actualizeDAPCFix(self):
     """change la valeur du choix quand changer"""
     #print("changeFix")
     currentValue = str(self.ui.DAPCfixPlainTextEdit.toPlainText().toUtf8())
     highlight = syntax.PythonHighlighter(
         self.ui.DAPCfixPlainTextEdit.document())
     self.ui.DAPCfixPlainTextEdit.setPlainText(currentValue.decode("utf-8"))
Exemple #5
0
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_main()
        self.ui.setupUi(self)
        syntax.PythonHighlighter(self.ui.script.document())
        self.ui.script.setText("""class KaraokeEffect(MuccaFxEffect):
	def apply(self, ass):
		for line in ass.lines:
			self.dispatchEffect(line)
		pass

	def dispatchEffect(self, line):
		if line['effect'] == 'sample':
			self.sampleEffect(line)
		pass

	def sampleEffect(self, line):
		line['text'] = "{\\fad(250,250)}{0}".format(line['text'])
		pass
""")
        self.ui.actionAssColor.triggered.connect(self.actionAssColor)
        self.ui.actionExit.triggered.connect(self.actionExit)
        self.ui.actionSave.triggered.connect(self.actionSave)
        self.ui.actionSaveAs.triggered.connect(self.actionSaveAs)
        self.ui.actionOpen.triggered.connect(self.actionOpen)
        self.ui.actionSelectASS.triggered.connect(self.actionSelectASS)
        self.ui.actionPreview.triggered.connect(self.actionPreview)
        self.refreshTitle()
Exemple #6
0
	def paintEvent(self, event):
		# super(QLabel, self).repaint(rect)
		painter = QPainter(self)

		# print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2", event.rect()

		# painter.fillRect(event.rect(), Qt.darkGray)

		doc = QTextDocument()

		highlight = syntax.PythonHighlighter(doc, is_dark = True, default = ['white'])

		font = self.font()
		# font.setFamily("Courier");	
		font.setStyleHint(QFont.Monospace);
		font.setFixedPitch(True);
		# font.setPointSize(self.font().pointSize());
		doc.setDefaultFont(font)
		self.width = event.rect().width()
		# doc.setTextWidth(self.width())

		text = self.text()

		doc.setPlainText(text)

		painter.translate(0., event.rect().center().y() - doc.size().height()/2.)
		doc.drawContents(painter, QRectF(event.rect()))
		painter.resetTransform()

		self.size = doc.size()

		

		# print "repainting"
		pass
Exemple #7
0
 def actualizeDAPCChange(self):
     """change la valeur du choix quand changer"""
     #print("changeChange")
     currentValue = str(self.ui.DAPCchangePlainTextEdit.toPlainText())
     highlight = syntax.PythonHighlighter(
         self.ui.DAPCchangePlainTextEdit.document())
     self.ui.DAPCchangePlainTextEdit.setPlainText(currentValue)
Exemple #8
0
	def editorConfig(self):

		# (TBD : Load from project json)
		self.textOpenql.setLineWrapMode(0)
		self.highlight = syntax.PythonHighlighter(self.textOpenql.document())
		self.textOpenql.setTabStopWidth(40)
		self.textOpenql.setFontFamily("Monospace")
Exemple #9
0
    def actualizeExpertMode(self):
        """change la valeur du choix quand changer"""
        if self.ui.expertCheckBox.isChecked():
            self.expertMode = "True"
            self.ui.expertFrame.show()
            self.ui.DAPCfixPlainTextEdit.clear()
            self.ui.DAPCchangePlainTextEdit.clear()

            highlight = syntax.PythonHighlighter(
                self.ui.DAPCfixPlainTextEdit.document())
            highlight2 = syntax.PythonHighlighter(
                self.ui.DAPCchangePlainTextEdit.document())

            self.ui.DAPCfixPlainTextEdit.setPlainText(DAPCfix)
            self.ui.DAPCchangePlainTextEdit.setPlainText(DAPCchange)
        else:
            self.expertMode = "False"
            self.ui.expertFrame.hide()
Exemple #10
0
    def addScriptAndData(self):
        """ Method which adds the script and scraped data to respective tabs.

            Syntax highlighter instance is created and functionality added to script Tab.
        """
        self.dataBrowser.setText(
            self.scraper_.data.encode('utf-8').decode('utf-8'))
        self.highlight = syntax.PythonHighlighter(
            self.scriptBrowser.document())
        self.scriptBrowser.setText(self.script)
Exemple #11
0
    def setup_editor(self):
        font = QtGui.QFont()
        font.setFamily("Courier")
        font.setFixedPitch(True)
        font.setPointSize(10)

        self.file_widget.file_line.setFont(font)

        self.higth_light = syntax.PythonHighlighter(
            self.file_widget.file_line.document())
Exemple #12
0
    def __init__(self, parent, doSetup=True):
        super().__init__()

        if doSetup:
            self.last_key_backspace = False
            self.inserted_by_user = True
            self.parent = parent

            self.syntax = syntax.PythonHighlighter(self.document())
            needs_to_be_updated.append(self)
Exemple #13
0
 def doSyntaxChanged(self, i):
     self.txtEditor.blockSignals(True)
     if self.cbxSyntax.currentIndex() == self.SYNTAX_PYTHON:
         self.highlight = syntax.PythonHighlighter(self.txtEditor.document())
     elif self.cbxSyntax.currentIndex() == self.SYNTAX_XML:
         self.highlight = syntax.XMLHighlighter(self.txtEditor.document())
     elif self.cbxSyntax.currentIndex() == self.SYNTAX_SQL:
         self.highlight = syntax.SQLHighlighter(self.txtEditor.document())
     else:
         self.highlight = syntax.TextHighlighter(self.txtEditor.document())
     self.txtEditor.blockSignals(False)
Exemple #14
0
    def __init__(self, parent=None):
        super(CodeEditor, self).__init__(parent)
        self.highlight = syntax.PythonHighlighter(self.document())

        self.lineNumberArea = LineNumberArea(self)

        self.blockCountChanged.connect(self.updateLineNumberAreaWidth)
        self.updateRequest.connect(self.updateLineNumberArea)
        self.cursorPositionChanged.connect(self.highlightCurrentLine)

        self.updateLineNumberAreaWidth(0)
Exemple #15
0
 def actualizeExtraparams(self):
     """change la valeur du choix quand changer"""
     #print("changeChange")
     currentValue = str(
         self.ui.extraparamsPlainTextEdit.toPlainText().toUtf8())
     if currentValue == "":
         currentValue = extraparams
     highlight = syntax.PythonHighlighter(
         self.ui.extraparamsPlainTextEdit.document())
     self.ui.extraparamsPlainTextEdit.setPlainText(
         currentValue.decode("utf-8"))
Exemple #16
0
	def openqlEditor(self):

		self.openqlLayout = QtWidgets.QVBoxLayout()
		
		self.textOpenql = QtWidgets.QTextEdit(self)
		self.textOpenql.setFixedSize(self.win_cx*0.55,self.win_ry*0.45)
		self.textOpenql.setText("OpenQL Editor")
		self.textOpenql.setLineWrapMode(0)
		self.textOpenql.setFontFamily("Monospace")
		self.textOpenql.setTabStopWidth(40)
		self.highlightO = syntax.PythonHighlighter(self.textOpenql.document())
		self.openqlLayout.addWidget(self.textOpenql)
		self.textOpenql.setEnabled(False)



		self.btnLayoutOC = QtWidgets.QHBoxLayout()

		self.btnO2C = QtWidgets.QPushButton(u"\u2193",self)
		# self.btnO2C.clicked.connect(self.convO2C)
		self.btnO2C.setFixedSize(self.win_cx*0.015,self.win_ry*0.03)
		self.btnLayoutOC.addWidget(self.btnO2C)
		self.btnO2C.setEnabled(False)
		
		self.btnC2O = QtWidgets.QPushButton(u"\u2191",self)
		# self.btnC2O.clicked.connect(self.convC2O)
		self.btnC2O.setFixedSize(self.win_cx*0.015,self.win_ry*0.03)
		self.btnLayoutOC.addWidget(self.btnC2O)
		self.btnC2O.setEnabled(False)
		
		self.openqlLayout.addLayout(self.btnLayoutOC)

		self.topLayoutH1.addLayout(self.openqlLayout)

		self.btnLayoutOQ = QtWidgets.QVBoxLayout()
		
		self.btnO2Q = QtWidgets.QPushButton(u"\u2192",self)
		self.btnO2Q.clicked.connect(self.convO2Q)
		self.btnO2Q.setFixedSize(self.win_cx*0.015,self.win_ry*0.03)
		self.btnLayoutOQ.addWidget(self.btnO2Q)
		self.btnO2Q.setEnabled(False)

		self.btnQ2O = QtWidgets.QPushButton(u"\u2190",self)
		# self.btnQ2O.clicked.connect(self.TBD)
		self.btnQ2O.setFixedSize(self.win_cx*0.015,self.win_ry*0.03)
		self.btnLayoutOQ.addWidget(self.btnQ2O)
		self.btnQ2O.setEnabled(False)

		self.topLayoutH1.addLayout(self.btnLayoutOQ)
Exemple #17
0
    def setupUi(self, main):
        self.main = main
        ui.Ui_Ejemplos.setupUi(self, main)

        self._conectar_signals()
        syntax.PythonHighlighter(self.codigo.document())

        self._definir_estado_habilitado(True)
        self._mostrar_image_inicial()
        self._mostrar_codigo_presentacion_inicial()

        self.this_dir = os.path.abspath(os.path.dirname(__file__))
        self.example_dir = os.path.join(self.this_dir, 'ejemplos')
        self._cargar_lista_de_ejemplos()
        pilas.utils.centrar_ventana(self.main)
    def __init__(self, parent=None):
        super(ScriptWrangler, self).__init__(parent)

        # figure out the UI file path
        uiFile = __file__.replace('.py', '.ui')
        print 'loading', uiFile
        self.ui = loadUiWidget(uiFile)

        # make sure it's not modal
        # self.setModal(False)
        # self.setWindowModality(QtCore.Qt.NonModal)

        # connect the UI to code
        self.ui.execute_BTN.pressed.connect(self.execute_fn)
        self.ui.load_BTN.pressed.connect(self.load_fn)
        self.ui.save_BTN.pressed.connect(self.save_fn)
        self.ui.tabs_WID.currentChanged.connect(self.tab_changed_fn)

        # set the text_wid for the tab generated by UIC
        self.ui.tabs_WID.widget(0).text_wid = self.ui.script_TEXT
        self.ui.script_TEXT.setTabStopWidth(20)

        # stdout
        self._err_color = QtCore.Qt.red
        stdout = OutputWrapper(self, True)
        stdout.outputWritten.connect(self.handleOutput)
        stderr = OutputWrapper(self, False)
        stderr.outputWritten.connect(self.handleOutput)

        # syntax highlighting
        highlight = syntax.PythonHighlighter(self.ui.script_TEXT.document())

        # key binding
        QtGui.QShortcut(QtGui.QKeySequence("Alt+Return"), self.ui.tabs_WID, self.execute_fn, context=QtCore.Qt.WidgetShortcut)

        # install event filter for MMB closing tabs
        self.ui.tabs_WID.tabBar().installEventFilter(self)
        self.ui.tabs_WID.tabBar().previousMiddleIndex = -1

        '''
        #have the terminal start closed
        self.sizes = self.ui.splitter.sizes()
        print self.sizes
        total_size = self.sizes[0] + self.sizes[1]
        self.ui.splitter.setSizes([300,300])
        '''

        self.ui.show()
Exemple #19
0
	def createEditor(self, parent, option, index):        
		editor = QTextEdit(parent)
		highlight = syntax.PythonHighlighter(editor.document())

		font = QFont("Courier")
		font.setFamily("Courier");
		font.setStyleHint(QFont.Monospace);
		font.setFixedPitch(True);
		font.setPointSize(10);
		editor.setFont(font)

		tab_stop = 4;  # 4 characters
		metrics = QFontMetrics(font)
		editor.setTabStopWidth(tab_stop * metrics.width(' '));

		return editor
Exemple #20
0
    def openFile(self, filename = None):
        if filename == "Choose a file":
            self.current_file = None
            self.text.clear()
            return
        if filename is None:
            filename = QtGui.QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME'))

        try:
            f = open(filename, 'r')
            filedata = f.read()
            highlight = syntax.PythonHighlighter(self.text.document())
            self.text.setPlainText(filedata)
            self.text.show()

            self.current_file = filename
            f.close()            
        except:
            return
Exemple #21
0
	def paint(self, painter, option, index):

		is_dark = True

		item = self.parent().item(index.row())

		if item.faulty:
			pen = QPen(QColor(255, 117, 117), 3)
			painter.setPen(pen)
			painter.drawRect(option.rect)
		elif item == self.parent().currentItem():
			pen = QPen(Qt.white, 3)
			painter.setPen(pen)
			painter.drawRect(option.rect)
		

		if not item.has_script:
			painter.fillRect(option.rect, QColor(153, 153, 153))		
		else:
			painter.fillRect(option.rect, Qt.white)
			is_dark = False

		doc = QTextDocument()
		highlight = syntax.PythonHighlighter(doc, is_dark = is_dark)

		font = QFont("Courier")
		font.setFamily("Courier");
		font.setStyleHint(QFont.Monospace);
		font.setFixedPitch(True);
		font.setPointSize(self.parent().font().pointSize())
		doc.setDefaultFont(font)


		text = index.data(Qt.EditRole)	
		text = text.replace("\t", ''.join([' '] * 4))

		doc.setPlainText(text)
		doc.setDefaultStyleSheet("background-color: red;")

		painter.translate(option.rect.topLeft())
		doc.drawContents(painter)
		painter.resetTransform()
    def initUI(self):
        editor = QPlainTextEdit()
        editor.setStyleSheet("""
            QPlainTextEdit{
                font-family:'Consolas';
                color: #ccc;
                background-color: #2b2b2b;
                font-size: 10pt;
            }
        """)
        highlight = syntax.PythonHighlighter(editor.document())
        editor.setPlainText(session.contents)

        main_vbox = QVBoxLayout()
        main_vbox.setContentsMargins(0, 0, 0, 0)
        main_vbox.addWidget(editor)
        self.setLayout(main_vbox)
        self.setWindowTitle("File")
        self.setGeometry(400, 100, 1000, 700)
        self.show()
Exemple #23
0
	def paintEvent(self, event):
		painter = QPainter(self)

		doc = QTextDocument()
		highlight = syntax.PythonHighlighter(doc, is_dark = True, default = ['white'])

		font = self.font()
		font.setStyleHint(QFont.Monospace);
		font.setFixedPitch(True);
		doc.setDefaultFont(font)
		self.width = event.rect().width()
		text = self.text()

		doc.setPlainText(text)

		painter.translate(0., event.rect().center().y() - doc.size().height()/2.)
		doc.drawContents(painter, QRectF(event.rect()))
		painter.resetTransform()

		self.size = doc.size()
Exemple #24
0
    def __init__(self, parent=None):
        QtWidgets.QPlainTextEdit.__init__(self, parent=parent)
        self.highlight = syntax.PythonHighlighter(self.document())

        # set monospace font
        font = self.document().defaultFont()
        font.setFamily(FONT['name'])
        font.setPointSize(FONT['size'])
        self.document().setDefaultFont(font)

        # indent :
        fm = QtGui.QFontMetrics(font)
        indent_size = fm.tightBoundingRect(" " *
                                           (FONT['indent'] + 1)).width() - 1
        self.setTabStopWidth(indent_size)

        # no wrap
        self.setLineWrapMode(QtWidgets.QPlainTextEdit.NoWrap)

        self.setup_connections()
Exemple #25
0
    def OpenFiles(self):
        self.receiveArea.setStyleSheet("""QPlainTextEdit{
                                           font-family:'Consolas';
                                           color: #ccc;
                                           background-color: #2b2b2b;}""")
        # self.highlight = xml_syntax.XMLHighlighter(self.receiveArea.document())
        # getting path and bool value
        path, _ = QFileDialog.getOpenFileName(
            self, "Open file", "",
            "All Files (*);;Python Files (*.py);;XML Files (*.xml);;Bash Scripts (*.sh);;Text Files (*.txt)"
        )

        # if path is true
        if path:
            # try opening path
            try:
                with open(path, 'rU') as f:
                    # read the file
                    text = f.read()
            # if some error occured
            except Exception as e:
                # show error using critical method
                self.dialog_critical(str(e))
            # else
            else:
                # update path value
                self.path = path

                if self.path.split(".")[-1] == "py":
                    self.highlight = syntax.PythonHighlighter(
                        self.receiveArea.document())
                elif self.path.split(".")[-1] == "xml":
                    self.receiveArea.setStyleSheet("")
                    self.highlight = syntax.XMLHighlighter(
                        self.receiveArea.document())

                # update the text
                self.receiveArea.setPlainText(text)
                # update the title
                self.update_title()
Exemple #26
0
    def initUI(self):

        self.editor = QtWidgets.QPlainTextEdit(self)
        self.setCentralWidget(self.editor)
        self.highlight = syntax.PythonHighlighter(self.editor.document())

        self.lineNumberArea = LineNumberArea(self)
        self.editor.blockCountChanged.connect(self.updateLineNumberAreaWidth)
        self.editor.updateRequest.connect(self.updateLineNumberArea)
        self.editor.cursorPositionChanged.connect(self.highlightCurrentLine)

        self.initToolbar()

        self.updateLineNumberAreaWidth(0)
        infile = open('blinky.py', 'r')
        self.editor.setPlainText(infile.read())

        # self.statusbar = self.statusbar()

        self.setGeometry(100, 100, 800, 600)

        self.setWindowTitle("mpEdit")
    def flipTheme(self, override=False):
        """ switch from light to dark theme """

        if not override:
            self.color_mode = not self.color_mode

        utils.changeCSS(self, 'background',
                        styles.ui_colors[self.color_mode]['bg_window'])

        utils.changeCSS(self.textEdit, 'color',
                        styles.syntax_colors[self.color_mode]['default'])

        utils.changeCSS(self.textEdit, 'background',
                        styles.ui_colors[self.color_mode]['bg_textEdit'])

        utils.changeCSS(self.messageText, 'color',
                        styles.syntax_colors[self.color_mode]['default'])

        utils.changeCSS(self.messageText, 'background',
                        styles.ui_colors[self.color_mode]['bg_textEdit'])

        utils.changeCSS(self.pybutton, 'color',
                        styles.ui_colors[self.color_mode]['py_color'])

        for button in self.buttons:

            utils.changeCSS(button, 'background-color',
                            styles.ui_colors[self.color_mode]['bg_button'])

            utils.changeCSS(button, 'border',
                            styles.ui_colors[self.color_mode]['bd_button'])

        self.highlighter = syntax.PythonHighlighter(self.textEdit,
                                                    self.color_mode)

        self.changeDefault('color_mode', self.color_mode)
            else:
                self.setCurrentBlockState(in_state)
                length = len(text) - start + add
            # Apply formatting
            self.setFormat(start, length, style)
            # Look for the next match
            start = delimiter.indexIn(text, start + length)

        # Return True if still inside a multi-line string, False otherwise
        if self.currentBlockState() == in_state:
            return True
        else:
            return False


if __name__ == "__main__":

    import qt.QtCore as qc
    import qt.QtGui as qg
    import syntax

    app = qg.QApplication([])
    editor = qg.QPlainTextEdit()
    syntax.PythonHighlighter(editor.document())
    editor.show()

    # Load syntax.py into the editor for demo purposes
    infile = open('syntax.py', 'r')
    editor.setPlainText(infile.read())

    app.exec_()
Exemple #29
0
    def __init__(self):
        super().__init__()
        self.screen_width, self.screen_height = self.geometry().width(
        ), self.geometry().height()
        self.resize(self.screen_width * 2, self.screen_height * 2)
        self.filterTypes = 'Text Document (*.txt);; Python File (*.py);; Markdown File (*.md)'
        self.path = None
        fixedFont = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        fixedFont.setPointSize(12)
        mainLayout = QVBoxLayout()

        # Editor
        self.editor = QPlainTextEdit()
        self.editor.setFont(fixedFont)
        self.syntax = syntax.PythonHighlighter(self.editor.document())
        mainLayout.addWidget(self.editor)

        # Status Bar
        self.statusBar = self.statusBar()

        # App Container
        container = QWidget()
        container.setLayout(mainLayout)
        self.setCentralWidget(container)

        # File Menu
        file_menu = self.menuBar().addMenu('&File')

        # Open, Save, Save As
        open_file_action = QAction(QIcon(''), 'Open...', self)
        open_file_action.setStatusTip('Open file')
        open_file_action.setShortcut(QKeySequence.Open)
        open_file_action.triggered.connect(self.file_open)

        save_file_action = self.create_action(self, '', 'Save', 'Save',
                                              self.file_save)
        save_file_action.setShortcut(QKeySequence.Save)

        save_fileAs_action = self.create_action(self, '', 'Save As...',
                                                'Save as', self.file_saveAs)
        save_fileAs_action.setShortcut(QKeySequence('Ctrl+Shift+S'))

        file_menu.addActions(
            [open_file_action, save_file_action, save_fileAs_action])

        # Separator
        file_menu.addSeparator()

        # Print
        print_action = self.create_action(self, '', 'Print', 'Print',
                                          self.print_file)
        print_action.setShortcut(QKeySequence.Print)
        file_menu.addAction(print_action)

        # Separator
        file_menu.addSeparator()

        # Exit
        exit_action = self.create_action(self, '', 'Exit', 'Exit', self.exit)
        file_menu.addAction(exit_action)

        # Edit Menu
        edit_menu = self.menuBar().addMenu('&Edit')

        # Undo, Redo
        undo_action = self.create_action(self, '', 'Undo', 'Undo',
                                         self.editor.undo)
        undo_action.setShortcut(QKeySequence.Undo)
        redo_action = self.create_action(self, '', 'Redo', 'Redo',
                                         self.editor.redo)
        redo_action.setShortcut(QKeySequence.Redo)
        edit_menu.addActions([undo_action, redo_action])

        # Separator
        edit_menu.addSeparator()

        # Cut, Copy, Paste, Select All
        cut_action = self.create_action(self, '', 'Cut', 'Cut',
                                        self.editor.cut)
        copy_action = self.create_action(self, '', 'Copy', 'Copy',
                                         self.editor.copy)
        paste_action = self.create_action(self, '', 'Paste', 'Paste',
                                          self.editor.paste)
        select_all_action = self.create_action(self, '', 'Select All',
                                               'Select all',
                                               self.editor.selectAll)

        cut_action.setShortcut(QKeySequence.Cut)
        copy_action.setShortcut(QKeySequence.Copy)
        paste_action.setShortcut(QKeySequence.Paste)
        select_all_action.setShortcut(QKeySequence.SelectAll)
        edit_menu.addActions(
            [cut_action, copy_action, paste_action, select_all_action])

        # Separator
        edit_menu.addSeparator()

        # Wrap Text
        wrap_text_action = self.create_action(self, '', 'Wrap Text',
                                              'Wrap text',
                                              self.toggle_wrap_text)
        wrap_text_action.setShortcut('Ctrl+Shift+W')
        edit_menu.addAction(wrap_text_action)

        self.update_title()
Exemple #30
0
    def __init__(self, version, direc, parent=None):
        QtGui.QWidget.__init__(self, parent)
        from qutip.examples.examples_text import tab_labels, button_labels, button_desc, button_nums
        #set tab button style
        tab_button_style = 'QPushButton {font-family: Verdana;border-width: 2px;border-color:#666666;border-style: solid;border-radius: 7;background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #B8E2EF, stop: 0.1 #A5DBEB, stop: 0.49 #8CD1E6, stop: 0.5 #7BCAE1, stop: 1 #57BCD9)}'
        #set quit button style
        quit_style = 'QPushButton {font-family: Verdana;border-width: 2px;border-color:#666666;border-style: solid;border-radius: 7;font-size: 16px;background-color: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #FFAAAA, stop: 0.1 #FF9999, stop: 0.49 #FF8888, stop: 0.5 #FF7777, stop: 1 #FF6666)}'

        #WINDOW PROPERTIES
        self.setWindowTitle('QuTiP Examples')
        self.setWindowIcon(QtGui.QIcon(CD_BASE + "/icon.png"))
        self.resize(1300, 720)
        self.setMinimumSize(1300, 720)
        self.setMaximumSize(1300, 720)
        self.center()
        self.setFocus()
        self.dir = direc + '/examples/'
        mapper = QtCore.QSignalMapper(self)

        title_font = QtGui.QFont()
        title_font.setFamily("Verdana")
        title_font.setBold(True)
        if sys.platform == 'darwin':
            title_font.setPointSize(14)
        else:
            title_font.setPointSize(12)
        title_fm = QtGui.QFontMetrics(title_font)
        #text across top of demos window
        title = QtGui.QLabel(self)
        title.setFont(title_font)
        title_text = "Click button once for code preview.  Click again to run example."
        pixelswide = title_fm.width(title_text)
        title.setText(title_text)
        title.setGeometry((self.width() - pixelswide) / 2.0, 0, 800, 30)

        font = QtGui.QFont()
        font.setFamily("Verdana")
        font.setBold(True)
        if sys.platform == 'darwin':
            font.setPointSize(12)
        else:
            font.setPointSize(10)
        fm = QtGui.QFontMetrics(font)

        #QUIT BUTTON-----------------
        #quit = HoverExit('Close',self)
        #quit.setGeometry(1120, 710, 70, 40)
        #quit.setStyleSheet(quit_style)
        #quit.setFocusPolicy(QtCore.Qt.NoFocus)
        #quit.clicked.connect(self.close)

        #copyright text
        copyright = QtGui.QLabel(self)
        copy_text = "Copyright (c) 2011-2012, P. D. Nation & J. R. Johansson"
        copyright.setText(copy_text)
        font.setBold(False)
        copyright.setFont(font)
        copyright.setGeometry(10, 695, 400, 30)
        #tab widget
        tab_widget = QtGui.QTabWidget()
        tab_widget.move(10, 10)
        tab_widget.resize(600, 665)
        tab_widget.setFixedSize(600, 665)
        #tabs for tab widget
        num_tabs = len(tab_labels)
        tabs = [QtGui.QWidget() for k in range(num_tabs)]
        for k in range(num_tabs):
            tab_widget.addTab(tabs[k], tab_labels[k])
        tab_widget.setTabShape(QtGui.QTabWidget.Triangular)
        tab_widget.setCurrentIndex(exconfig.tab)

        #tab buttons
        self.tab_verts = [QtGui.QVBoxLayout(tabs[k]) for k in range(num_tabs)]
        self.num_elems = [len(button_labels[k]) for k in range(num_tabs)]
        self.tab_buttons = [[] for j in range(num_tabs)]
        for j in range(num_tabs):
            for k in range(self.num_elems[j]):
                button = HoverButton(button_nums[j][k], button_labels[j][k])
                button.setFont(font)
                if button_nums[j][k] == exconfig.is_green:
                    button.setText('Run Example')
                    button.setStyleSheet(
                        'QPushButton {font-family: Verdana;border-width: 2px;border-color:#666666;border-style: solid;border-radius: 7;background: QLinearGradient( x1: 0, y1: 0, x2: 0, y2: 1, stop: 0 #E0F1E0, stop: 0.1 #C1E3C1, stop: 0.49 #A3D6A3, stop: 0.5 #84C884, stop: 1 #66BB66)}'
                    )
                else:
                    button.setText(button_labels[j][k])
                    button.setStyleSheet(tab_button_style)
                button.setFixedSize(170, 40)
                self.connect(button, QtCore.SIGNAL("clicked()"), mapper,
                             QtCore.SLOT("map()"))
                mapper.setMapping(button, button_nums[j][k])
                self.tab_buttons[j].append(button)

        #font for example descriptions
        font2 = QtGui.QFont()
        font2.setFamily("Verdana")
        font2.setBold(False)
        if sys.platform == 'darwin':
            font2.setPointSize(12)
        else:
            font2.setPointSize(10)

        self.tab_button_desc = [[] for j in range(num_tabs)]
        for j in range(num_tabs):
            for k in range(self.num_elems[j]):
                _label = QtGui.QLabel(button_desc[j][k])
                _label.setWordWrap(True)  #auto wrap
                _label.setFont(font2)
                self.tab_button_desc[j].append(_label)

        self.tab_widgets = [[
            QtGui.QWidget() for k in range(self.num_elems[j])
        ] for j in range(num_tabs)]
        self.tab_horiz_layouts = [[
            QtGui.QHBoxLayout(self.tab_widgets[j][k])
            for k in range(self.num_elems[j])
        ] for j in range(num_tabs)]
        for j in range(num_tabs):
            for k in range(self.num_elems[j]):
                self.tab_horiz_layouts[j][k].addWidget(self.tab_buttons[j][k])
                self.tab_horiz_layouts[j][k].addSpacing(15)
                self.tab_horiz_layouts[j][k].addWidget(
                    self.tab_button_desc[j][k])
        for j in range(num_tabs):
            for k in range(self.num_elems[j]):
                self.tab_verts[j].addWidget(self.tab_widgets[j][k])
            self.tab_verts[j].addStretch()

        #set mapper to on_button_clicked funtions
        self.connect(mapper, QtCore.SIGNAL("mapped(int)"),
                     self.on_button_clicked)
        self.layout = QtGui.QGridLayout(self)
        #create text editor widget
        self.editor = QtGui.QTextEdit()
        self.editor.setCurrentFont(QtGui.QFont("Courier"))
        if sys.platform == 'darwin':
            self.editor.setFontPointSize(12)
        else:
            self.editor.setFontPointSize(10)
        self.editor.setReadOnly(True)
        self.editor.resize(600, 665)
        self.editor.setFixedSize(600, 666)
        #add tabwidget and textwidget to main window
        self.layout.addWidget(tab_widget, 0, 0, 5, 1)
        self.layout.addWidget(self.editor, 0, 3, 5, 1)
        #set text of editor if demos previsouly ran.
        if exconfig.is_green != 0:
            syntax.PythonHighlighter(self.editor.document())
            self.editor.show()
            _text_file = compile(
                "infile = open(self.dir+'ex_" + str(exconfig.is_green) +
                ".py', 'r')", '<string>', 'exec')
            exec(_text_file)
            self.editor.setPlainText(infile.read())