Пример #1
0
	def __init__(self):
		QDialog.__init__(self)
		self.setupUi(self)
		self.setWindowIcon( QIcon('logo.svg') )
		self.setWindowFlags( Qt.WindowMinimizeButtonHint )

		s = QSettings( "norBIT", "norGIS-ALKIS-Import" )

		self.leSERVICE.setText( s.value( "service", "" ) )
		self.leHOST.setText( s.value( "host", "" ) )
		self.lePORT.setText( s.value( "port", "5432" ) )
		self.leDBNAME.setText( s.value( "dbname", "" ) )
		self.leUID.setText( s.value( "uid", "" ) )
		self.lePWD.setText( s.value( "pwd", "" ) )
		self.leGT.setText( s.value( "gt", "20000" ) )
		self.leGT.setValidator( QIntValidator( -1, 99999999 ) )
		self.lstFiles.addItems( s.value( "files", [] ) or [] )
		self.cbxSkipFailures.setChecked( s.value( "skipfailures", False, type=bool ) )
		self.cbFnbruch.setCurrentIndex( 0 if s.value( "fnbruch", True, type=bool ) else 1 )
		self.cbxUseCopy.setChecked( s.value( "usecopy", False, type=bool ) )
		self.cbxCreate.setChecked( False )

		self.cbEPSG.addItem( "UTM32N", "25832")
		self.cbEPSG.addItem( "UTM33N", "25833")
		self.cbEPSG.addItem( "3GK2 (BW)", "131466")
		self.cbEPSG.addItem( "3GK3 (BW)", "131467")
		self.cbEPSG.addItem( "3GK4 (BY)", "131468")
		self.cbEPSG.setCurrentIndex( self.cbEPSG.findData( s.value( "epsg", "25832" ) ) )

		self.pbAdd.clicked.connect(self.selFiles)
		self.pbAddDir.clicked.connect(self.selDir)
		self.pbRemove.clicked.connect(self.rmFiles)
		self.pbSelectAll.clicked.connect( self.lstFiles.selectAll )
		self.pbLoad.clicked.connect(self.loadList)
		self.pbSave.clicked.connect(self.saveList)
		self.lstFiles.itemSelectionChanged.connect(self.selChanged)

		self.pbStart.clicked.connect(self.run)
		self.pbLoadLog.clicked.connect(self.loadLog)
		self.pbSaveLog.clicked.connect(self.saveLog)
		self.pbClearLog.clicked.connect(self.clearLog)
		self.pbAbout.clicked.connect(self.about)
		self.pbClose.clicked.connect(self.accept)
		self.pbProgress.setVisible( False )

		f = QFont("Monospace")
		f.setStyleHint( QFont.TypeWriter )
		self.lwProtocol.setFont( f )
		self.lwProtocol.setUniformItemSizes(True)

		self.status("")

		self.restoreGeometry( s.value("geometry", QByteArray(), type=QByteArray) )

		self.canceled = False
		self.running = False
		self.skipScroll = False
		self.logqry = None

		self.reFilter = None
Пример #2
0
    def __init__(self):
        super(MonoSpaceLabel, self).__init__()

        font = QFont('monospace')
        font.setStyleHint(QFont.TypeWriter)

        self.setFont(font)
    def __init__(self, callback):
        super().__init__()

        self.callback = callback

        #Toolbar
        toolbar = QToolBar(self)
        self.button_test = toolbar.addAction("Test script")
        self.button_burn = toolbar.addAction("Write script to ROM")
        #self.button_reload = toolbar.addAction("Refresh")
        self.button_pokescriptdoc = toolbar.addAction("PokeScript doc")
        self.button_pokescriptdoc.setToolTip(
            "Opens your webbrowser, pointing at a page where some elemnets of PokeScript are explained."
        )
        self.button_scriptdoc = toolbar.addAction("List of commands.")
        self.button_scriptdoc.setToolTip(
            "Opens a list of available commands in your default browser.")
        toolbar.actionTriggered.connect(self.toolbarAction)

        #Code editor
        sourceeditor = LNTextEdit(self)
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        sourceeditor.setFont(font)
        sourceeditor.setLineWrapMode(0)
        sourceeditor.setHighlighterClass(PokeScriptHighlighter)

        #Wrap it up
        layout = QVBoxLayout(self)
        layout.addWidget(toolbar)
        layout.addWidget(sourceeditor)
        layout.setContentsMargins(0, 0, 0, 0)

        #Store elements that we need later
        self.sourceeditor = sourceeditor
Пример #4
0
            def cb_read(result):
                self.log_file.release()
                self.log_file = None

                self.label_download.setVisible(False)
                self.progress_download.setVisible(False)

                if result.error != None:
                    self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True)
                    return

                try:
                    self.content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    self.log(u'Error: Log file is not UTF-8 encoded', bold=True)
                    return

                self.button_save.setEnabled(True)

                if self.continuous:
                    content = self.content.lstrip()
                else:
                    content = self.content

                self.edit_content.setPlainText('')

                font = QFont('monospace')
                font.setStyleHint(QFont.TypeWriter)

                self.edit_content.setFont(font)
                self.edit_content.setPlainText(content)
Пример #5
0
    def __init__(self, parent=None, command="/bin/bash",
                 font_name="Monospace", font_size=14):
        super(TerminalWidget, self).__init__(parent)
        self._columns = 80
        self._rows = 24
        self._char_width = [0]*(self._columns+1)
        self._char_height = [0]*(self._rows+1)

#        self.parent().setTabOrder(self, self)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_OpaquePaintEvent, True)
        self.setCursor(Qt.IBeamCursor)
        font = QFont(font_name)
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(font_size)
        self.setFont(font)
        self._session = None
        self._last_update = 0
        self._screen = []
        self._text = []
        self._cursor_rect = None
        self._cursor_col = 0
        self._cursor_row = 0
        self._dirty = False
        self._blink = False
        self._press_pos = None
        self._selection = None
        self._clipboard = QApplication.clipboard()
        self._pixmap = None
Пример #6
0
 def _setup_editor(self):
     font = QFont('Some font that does not exist')
     font.setStyleHint(font.TypeWriter, font.PreferDefault)
     editor = codeeditor.CodeEditor(self)
     try:
         editor.setup_editor(linenumbers=True,
                             language='py',
                             scrollflagarea=False,
                             codecompletion_enter=self.enter_completion,
                             tab_mode=False,
                             edge_line=False,
                             font=font,
                             codecompletion_auto=True,
                             go_to_definition=True,
                             codecompletion_single=True,
                             calltips=True)
     except TypeError:  # codecompletion_single is gone in 2.3.0
         editor.setup_editor(linenumbers=True,
                             language='py',
                             scrollflagarea=False,
                             codecompletion_enter=self.enter_completion,
                             tab_mode=False,
                             edge_line=False,
                             font=font,
                             codecompletion_auto=True,
                             go_to_definition=True,
                             calltips=True)
     editor.setCursor(Qt.IBeamCursor)
     editor.horizontalScrollBar().setCursor(Qt.ArrowCursor)
     editor.verticalScrollBar().setCursor(Qt.ArrowCursor)
     return editor
Пример #7
0
    def __init__(self):
        super(MonoSpaceLabel, self).__init__()

        font = QFont('monospace')
        font.setStyleHint(QFont.TypeWriter)

        self.setFont(font)
Пример #8
0
 def __init__(self, parent):
     QPlainTextEdit.__init__(self, parent)
     # Set font to monospaced (TypeWriter)
     font = QFont('')
     font.setStyleHint(font.TypeWriter, font.PreferDefault)
     font.setPointSize(8)
     self.setFont(font)
Пример #9
0
            def cb_read(result):
                self.log_file.release()
                self.log_file = None

                self.label_download.setVisible(False)
                self.progress_download.setVisible(False)

                if result.error != None:
                    self.log(u'Error: ' + Qt.escape(unicode(result.error)), bold=True)
                    return

                try:
                    self.content = result.data.decode('utf-8')
                except UnicodeDecodeError:
                    # FIXME: maybe add a encoding guesser here or try some common encodings if UTF-8 fails
                    self.log(u'Error: Log file is not UTF-8 encoded', bold=True)
                    return

                self.button_save.setEnabled(True)

                if self.continuous:
                    content = self.content.lstrip()
                else:
                    content = self.content

                self.edit_content.setPlainText('')

                font = QFont('monospace')
                font.setStyleHint(QFont.TypeWriter)

                self.edit_content.setFont(font)
                self.edit_content.setPlainText(content)
Пример #10
0
    def add_file(self, file_name):
        font = QFont('Some font that does not exist')
        font.setStyleHint(font.TypeWriter, font.PreferDefault)
        editor = CodeEditor()
        editor.setup_editor(linenumbers=True, language='py',
            scrollflagarea=False, codecompletion_enter=True,
            tab_mode=False, edge_line=False, font=font,
            codecompletion_auto=True, go_to_definition=True,
            codecompletion_single=True)
        editor.setCursor(Qt.IBeamCursor)
        editor.horizontalScrollBar().setCursor(Qt.ArrowCursor)
        editor.verticalScrollBar().setCursor(Qt.ArrowCursor)
        editor.file_name = file_name

        if file_name.endswith('py'):
            editor.set_text_from_file(file_name)
            tab_name = os.path.split(file_name)[1]
        else:
            editor.set_text(self.template_code)
            tab_name = 'New Analysis'

        editor.file_was_changed = False
        editor.textChanged.connect(lambda: self.file_changed(editor))

        self.tabs.addTab(editor, tab_name)
        self.tabs.setCurrentWidget(editor)

        self.setVisible(True)
        self.raise_()
Пример #11
0
 def __init__(self, callback):
     super().__init__()
     
     self.callback = callback
     
     #Toolbar
     toolbar = QToolBar(self)
     self.button_test = toolbar.addAction("Test script")
     self.button_burn = toolbar.addAction("Write script to ROM")
     #self.button_reload = toolbar.addAction("Refresh")
     self.button_pokescriptdoc = toolbar.addAction("PokeScript doc")
     self.button_pokescriptdoc.setToolTip("Opens your webbrowser, pointing at a page where some elemnets of PokeScript are explained.")
     self.button_scriptdoc = toolbar.addAction("List of commands.")
     self.button_scriptdoc.setToolTip("Opens a list of available commands in your default browser.")
     toolbar.actionTriggered.connect(self.toolbarAction)
     
     #Code editor
     sourceeditor = LNTextEdit(self)
     font = QFont("Monospace")
     font.setStyleHint(QFont.TypeWriter)
     sourceeditor.setFont(font)
     sourceeditor.setLineWrapMode(0)
     sourceeditor.setHighlighterClass(PokeScriptHighlighter)
     
     #Wrap it up
     layout = QVBoxLayout(self)
     layout.addWidget(toolbar)
     layout.addWidget(sourceeditor)
     layout.setContentsMargins(0, 0, 0, 0)
     
     #Store elements that we need later
     self.sourceeditor = sourceeditor
Пример #12
0
    def __init__(self,
                 parent=None,
                 command="/bin/bash",
                 font_name="Monospace",
                 font_size=14):
        super(TerminalWidget, self).__init__(parent)
        self._columns = 80
        self._rows = 24
        self._char_width = [0] * (self._columns + 1)
        self._char_height = [0] * (self._rows + 1)

        #        self.parent().setTabOrder(self, self)
        self.setFocusPolicy(Qt.StrongFocus)
        self.setAutoFillBackground(False)
        self.setAttribute(Qt.WA_OpaquePaintEvent, True)
        self.setCursor(Qt.IBeamCursor)
        font = QFont(font_name)
        font.setStyleHint(QFont.TypeWriter)
        font.setPixelSize(font_size)
        self.setFont(font)
        self._session = None
        self._last_update = 0
        self._screen = []
        self._text = []
        self._cursor_rect = None
        self._cursor_col = 0
        self._cursor_row = 0
        self._dirty = False
        self._blink = False
        self._press_pos = None
        self._selection = None
        self._clipboard = QApplication.clipboard()
        self._pixmap = None
Пример #13
0
 def __init__(self, parent):
     QPlainTextEdit.__init__(self, parent)
     # Set font to monospaced (TypeWriter)
     font = QFont('')
     font.setStyleHint(font.TypeWriter, font.PreferDefault)
     font.setPointSize(8)
     self.setFont(font)
Пример #14
0
 def __init__(self, active=True, parent=None):
     self.active = active
     QListWidgetItem.__init__(self, parent)
     self.set_color()
     font = QFont(QFont.SansSerif)
     font.setStyleHint(QFont.Monospace)
     font.setPointSize(10)
     font.setFixedPitch(True)
     self.setFont(font)
     self.setTextAlignment(4)
Пример #15
0
    def __init__(self, *args):
        QPlainTextEdit.__init__(self, *args)

        self.setMaximumWidth(655)

        font = QFont('')
        font.setFamily('Courier')
        font.setStyleHint(QFont.Monospace)
        font.setPointSize(10)
        self.setFont(font)
Пример #16
0
def getMonoFont(fontsize=12, msg=False):
    monofont = QFont()
    monofont.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
    monofont.setStyleHint(QFont.Courier)
    monofont.setFamily(IMC.fontFamily)
    monofont.setFixedPitch(True) # probably unnecessary
    monofont.setPointSize(fontsize)
    if msg and (monofont.family() != IMC.fontFamily):
        infoMsg("Font {0} not available, using {1}".format(
            IMC.fontFamily, monoinf.family()) )
    return monofont
Пример #17
0
 def __init__(self, parent=None):
     super(htmlPreview, self).__init__(parent)
     hbox = QHBoxLayout()
     self.refreshButton = QPushButton(u"Refresh")
     hbox.addWidget(self.refreshButton, 0)
     hbox.addStretch(1)
     self.refreshAndClearButton = QPushButton(u"Refresh + Clear")
     hbox.addWidget(self.refreshAndClearButton)
     vbox = QVBoxLayout()
     vbox.addLayout(hbox, 0)
     self.preview = QWebView(self)
     # save a shortcut reference to web page and its history
     self.webPage = self.preview.page()
     self.history = self.preview.page().history()
     vbox.addWidget(self.preview, 1)
     self.setLayout(vbox)
     # make the web preview uneditable
     self.webPage.setContentEditable(False)
     self.settings = self.preview.settings()
     # Find out the nearest font to Palatino
     qf = QFont()
     qf.setStyleStrategy(QFont.PreferAntialias + QFont.PreferMatch)
     qf.setStyleHint(QFont.Serif)
     qf.setFamily(QString(u'Palatino'))
     qfi = QFontInfo(qf)
     # set the default font to that serif font
     self.settings.setFontFamily(QWebSettings.StandardFont, qfi.family())
     self.settings.setFontSize(QWebSettings.DefaultFontSize, 16)
     self.settings.setFontSize(QWebSettings.MinimumFontSize, 6)
     self.settings.setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
     self.zoomFactor = 1.0
     # Disable everything but bog-standard html, appropriate for PP
     self.settings.setAttribute(QWebSettings.JavascriptEnabled, False)
     self.settings.setAttribute(QWebSettings.JavaEnabled, False)
     self.settings.setAttribute(QWebSettings.PluginsEnabled, False)
     self.settings.setAttribute(QWebSettings.ZoomTextOnly, False)
     # the following causes a hard error in linux
     #self.settings.setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
     # hook up the refresh buttons
     self.connect(self.refreshButton, SIGNAL("clicked()"),
                  self.refresh1Click)
     self.connect(self.refreshAndClearButton, SIGNAL("clicked()"),
                  self.refresh2Click)
     # hook up the load status signals
     self.connect(self.preview, SIGNAL("loadStarted()"), self.loadStarts)
     self.connect(self.preview, SIGNAL("loadProgress(int)"),
                  self.loadProgresses)
     self.connect(self.preview, SIGNAL("loadFinished(bool)"), self.loadEnds)
     # here we store the scroll position to return to after reloading
     self.scrollPosition = QPoint(0, 0)
     # here save the user's find text for ctl-g use
     self.findText = QString()
     # here store the base URL for the current book.
     self.baseURL = QUrl()
Пример #18
0
  def __init__(self, parent=None):
    super(QDockWidget, self).__init__('Status', parent)
    self.setFeatures(QDockWidget.DockWidgetMovable)

    self.txt_log = QTextEdit(self)
    self.txt_log.setReadOnly(False)
    font = QFont('Monospace')
    font.setStyleHint(QFont.TypeWriter)
    self.txt_log.setFont(font)
    self.setWidget(self.txt_log)

    self.setMaximumHeight(120)
Пример #19
0
    def __init__(self, parent=None):
        super(QDockWidget, self).__init__('Status', parent)
        self.setFeatures(QDockWidget.DockWidgetMovable)

        self.txt_log = QTextEdit(self)
        self.txt_log.setReadOnly(False)
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        self.txt_log.setFont(font)
        self.setWidget(self.txt_log)

        self.setMaximumHeight(120)
Пример #20
0
    def __init__(self, callback):
        super().__init__()
        self.callback = callback

        self.offset = 0  # Offset of currently oaded script
        self.pointerscount = 0  # Number of pointers to the offset
        self.oldsize = 0  # Old size of currently loaded bytestring.
        self.freespace = 0  # Free space available after currently loaded bytestring.

        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        formlayout = QFormLayout()
        label_charscount = QLabel()
        label_offset = QLabel()
        label_pointersToOffset = QLabel()
        formlayout.addRow("Used / Maximum number of chars:", label_charscount)
        formlayout.addRow("String offset:", label_offset)
        formlayout.addRow("Pointers to offset:", label_pointersToOffset)

        find_startpoint = QPushButton("Try to find start of string.", self)
        find_startpoint.hide()
        editor_save = QPushButton("Save", self)
        editor_save_repoint = QPushButton("Save and update pointers.", self)
        editor_save_repoint.hide()

        stringeditor = LNTextEdit(self)
        font = QFont("Monospace")
        font.setStyleHint(QFont.TypeWriter)
        stringeditor.setFont(font)

        layout.addWidget(stringeditor)
        layout.addLayout(formlayout)
        layout.addWidget(find_startpoint)
        layout.addWidget(editor_save)
        layout.addWidget(editor_save_repoint)

        #self.label_totalchars = label_totalchars
        self.stringeditor = stringeditor
        self.label_charscount = label_charscount
        self.label_offset = label_offset
        self.label_pointersToOffset = label_pointersToOffset
        self.editor_save = editor_save
        self.find_startpoint = find_startpoint
        self.editor_save_repoint = editor_save_repoint

        stringeditor.edit.textChanged.connect(self.updateUI)
        find_startpoint.clicked.connect(self.findStartpoint)
        editor_save.clicked.connect(self.save)
        editor_save_repoint.clicked.connect(self.saveandrepoint)

        self.updateUI()
Пример #21
0
    def setupUi(self):
        self.setWindowTitle('Edit filter')
        #self.resize(400, 300)

        self.signatureLabel = QLabel(self)
        self.signatureLabel.setText('def filter(block):')

        font = QFont('Some font that does not exist')
        font.setStyleHint(font.TypeWriter, font.PreferDefault)
        self.editor = CodeEditor()
        self.editor.setup_editor(linenumbers=False, language='py',
            scrollflagarea=False, codecompletion_enter=True, font=font,
            highlight_current_line=False, occurence_highlighting=False)
        self.editor.set_text('return True')
        self.editor.setCursor(Qt.IBeamCursor)

        self.onExceptionCheckBox = QCheckBox(self)
        self.onExceptionCheckBox.setText('True on exception')
        self.onExceptionCheckBox.setToolTip('Determines if the filter will be admit items if there is an exception during its execution')

        self.filterTypeComboBox = QComboBox(self)
        self.filterTypeComboBox.addItem('Block')
        self.filterTypeComboBox.addItem('Segment')
        self.filterTypeComboBox.addItem('Recording Channel Group')
        self.filterTypeComboBox.addItem('Recording Channel')
        self.filterTypeComboBox.addItem('Unit')

        self.filterGroupComboBox = QComboBox(self)

        self.nameLineEdit = QLineEdit()

        self.dialogButtonBox = QDialogButtonBox(self)
        self.dialogButtonBox.setAutoFillBackground(False)
        self.dialogButtonBox.setOrientation(Qt.Horizontal)
        self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.Ok)
        self.dialogButtonBox.setCenterButtons(True)

        gridLayout = QGridLayout(self)
        gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 2)
        gridLayout.addWidget(self.editor, 1, 0, 1, 2)
        gridLayout.addWidget(self.onExceptionCheckBox, 2,0, 1, 2)
        gridLayout.addWidget(QLabel('Type:', self), 3, 0)
        gridLayout.addWidget(self.filterTypeComboBox, 3, 1)
        gridLayout.addWidget(QLabel('Group:', self), 4, 0)
        gridLayout.addWidget(self.filterGroupComboBox, 4, 1)
        gridLayout.addWidget(QLabel('Name:', self), 5, 0)
        gridLayout.addWidget(self.nameLineEdit, 5, 1)
        gridLayout.addWidget(self.dialogButtonBox, 6, 0, 1, 2)

        self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept)
        self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject)
        self.connect(self.filterTypeComboBox, SIGNAL('currentIndexChanged(int)'), self.on_filterTypeComboBox_currentIndexChanged)
Пример #22
0
    def __init__(self, callback):
        super().__init__()
        self.callback = callback
        
        self.offset = 0         # Offset of currently oaded script
        self.pointerscount = 0  # Number of pointers to the offset
        self.oldsize = 0        # Old size of currently loaded bytestring.
        self.freespace = 0      # Free space available after currently loaded bytestring.
                
        layout = QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)

        formlayout = QFormLayout()
        label_charscount = QLabel()
        label_offset = QLabel()
        label_pointersToOffset = QLabel()
        formlayout.addRow("Used / Maximum number of chars:", label_charscount)
        formlayout.addRow("String offset:", label_offset)
        formlayout.addRow("Pointers to offset:", label_pointersToOffset)
        
        find_startpoint = QPushButton("Try to find start of string.", self)
        find_startpoint.hide()
        editor_save = QPushButton("Save", self)
        editor_save_repoint = QPushButton("Save and update pointers.", self)
        editor_save_repoint.hide()
        
        stringeditor = LNTextEdit(self)
        font = QFont("Monospace");
        font.setStyleHint(QFont.TypeWriter);
        stringeditor.setFont(font)
        
        layout.addWidget(stringeditor)
        layout.addLayout(formlayout)
        layout.addWidget(find_startpoint)
        layout.addWidget(editor_save)
        layout.addWidget(editor_save_repoint)

        #self.label_totalchars = label_totalchars
        self.stringeditor = stringeditor
        self.label_charscount = label_charscount
        self.label_offset = label_offset
        self.label_pointersToOffset = label_pointersToOffset
        self.editor_save = editor_save
        self.find_startpoint = find_startpoint
        self.editor_save_repoint = editor_save_repoint
        
        stringeditor.edit.textChanged.connect(self.updateUI)
        find_startpoint.clicked.connect(self.findStartpoint)
        editor_save.clicked.connect(self.save)
        editor_save_repoint.clicked.connect(self.saveandrepoint)
        
        self.updateUI()
Пример #23
0
    def setupUi(self):
        self.setFixedSize(BUTTON_SIZE, BUTTON_SIZE)

        styles = [
            'font-size: {font_size}px;',
            'line-height: {font_size}px;',
        ]
        style = ' '.join(styles).format(font_size=BUTTON_FONT_SIZE, )
        self.setStyleSheet(style)

        font = QFont()
        font.setStyleHint(QFont.Monospace)
        self.setFont(font)
Пример #24
0
 def __init__(self, parent=None ):
     super(htmlPreview, self).__init__(parent)
     hbox = QHBoxLayout()
     self.refreshButton = QPushButton(u"Refresh")
     hbox.addWidget(self.refreshButton,0)
     hbox.addStretch(1)
     self.refreshAndClearButton = QPushButton(u"Refresh + Clear")
     hbox.addWidget(self.refreshAndClearButton)
     vbox = QVBoxLayout()
     vbox.addLayout(hbox,0)
     self.preview = QWebView(self)
     # save a shortcut reference to web page and its history
     self.webPage = self.preview.page()
     self.history = self.preview.page().history()
     vbox.addWidget(self.preview,1)
     self.setLayout(vbox)
     # make the web preview uneditable
     self.webPage.setContentEditable(False)
     self.settings = self.preview.settings()
     # Find out the nearest font to Palatino
     qf = QFont()
     qf.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
     qf.setStyleHint(QFont.Serif)
     qf.setFamily(QString(u'Palatino'))
     qfi = QFontInfo(qf)
     # set the default font to that serif font
     self.settings.setFontFamily(QWebSettings.StandardFont, qfi.family())
     self.settings.setFontSize(QWebSettings.DefaultFontSize, 16)
     self.settings.setFontSize(QWebSettings.MinimumFontSize, 6)
     self.settings.setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
     self.zoomFactor = 1.0
     # Disable everything but bog-standard html, appropriate for PP
     self.settings.setAttribute(QWebSettings.JavascriptEnabled, False)
     self.settings.setAttribute(QWebSettings.JavaEnabled, False)
     self.settings.setAttribute(QWebSettings.PluginsEnabled, False)
     self.settings.setAttribute(QWebSettings.ZoomTextOnly, False)
     # the following causes a hard error in linux
     #self.settings.setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
     # hook up the refresh buttons
     self.connect(self.refreshButton, SIGNAL("clicked()"),self.refresh1Click)
     self.connect(self.refreshAndClearButton, SIGNAL("clicked()"),self.refresh2Click)
     # hook up the load status signals
     self.connect(self.preview,SIGNAL("loadStarted()"),self.loadStarts )
     self.connect(self.preview,SIGNAL("loadProgress(int)"),self.loadProgresses )
     self.connect(self.preview,SIGNAL("loadFinished(bool)"),self.loadEnds )
     # here we store the scroll position to return to after reloading
     self.scrollPosition = QPoint(0,0)
     # here save the user's find text for ctl-g use
     self.findText = QString()
     # here store the base URL for the current book.
     self.baseURL = QUrl()
Пример #25
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)

        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = self.settings.value("pythonConsole/preloadAPI", True, type=bool)
        chekBoxPreparedAPI = self.settings.value("pythonConsole/usePreparedAPIFile", False, type=bool)
        if chekBoxAPI:
            pap = os.path.join(QgsApplication.pkgDataPath(), "python", "qsci_apis", "pyqgis.pap")
            self.api.loadPrepared(pap)
        elif chekBoxPreparedAPI:
            self.api.loadPrepared(self.settings.value("pythonConsole/preparedAPIFile"))
        else:
            apiPath = self.settings.value("pythonConsole/userAPI", [])
            for i in range(0, len(apiPath)):
                self.api.load(unicode(apiPath[i]))
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)
 def _setup_editor(self):
     font = QFont('Some font that does not exist')
     font.setStyleHint(font.TypeWriter, font.PreferDefault)
     editor = codeeditor.CodeEditor(self)
     editor.setup_editor(
         linenumbers=True, language='py',
         scrollflagarea=False, codecompletion_enter=self.enter_completion,
         tab_mode=False, edge_line=False, font=font,
         codecompletion_auto=True, go_to_definition=True,
         codecompletion_single=True, calltips=True)
     editor.setCursor(Qt.IBeamCursor)
     editor.horizontalScrollBar().setCursor(Qt.ArrowCursor)
     editor.verticalScrollBar().setCursor(Qt.ArrowCursor)
     return editor
    def __init__(self, display_name, absolute_name, tab, deletable=True):
        self.display_name   = display_name # is unique
        self.absolute_name  = absolute_name # is also unique
        self.tab            = tab
        self.deletable      = deletable
        self.index          = -1
        self.modified       = False
        self.content        = None
        self.edit           = QPlainTextEdit()

        font = QFont('monospace')
        font.setStyleHint(QFont.TypeWriter)

        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setFont(font)
        self.edit.textChanged.connect(self.check_content)
Пример #28
0
    def __init__(self, display_name, absolute_name, tab, deletable=True):
        self.display_name = display_name  # is unique
        self.absolute_name = absolute_name  # is also unique
        self.tab = tab
        self.deletable = deletable
        self.index = -1
        self.modified = False
        self.content = None
        self.edit = QPlainTextEdit()

        font = QFont('monospace')
        font.setStyleHint(QFont.TypeWriter)

        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setFont(font)
        self.edit.textChanged.connect(self.check_content)
Пример #29
0
    def __init__(self, parent=None ):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias+QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath,u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath)
                                )
        elif not helpFile.open(QIODevice.ReadOnly) :
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(helpPath,
                                                                 helpFile.error())
                                                         )
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
Пример #30
0
    def __init__(self, parent=None):
        super(helpDisplay, self).__init__(parent)
        # make page unmodifiable
        self.page().setContentEditable(False)
        # initialize settings
        # Find out the nearest font to Palatino
        qf = QFont()
        qf.setStyleStrategy(QFont.PreferAntialias + QFont.PreferMatch)
        qf.setStyleHint(QFont.Serif)
        qf.setFamily(QString(u'Palatino'))
        qfi = QFontInfo(qf)
        # set the default font to that serif font
        self.settings().setFontFamily(QWebSettings.StandardFont, qfi.family())
        self.settings().setFontSize(QWebSettings.DefaultFontSize, 16)
        self.settings().setFontSize(QWebSettings.MinimumFontSize, 6)
        self.settings().setFontSize(QWebSettings.MinimumLogicalFontSize, 6)
        self.textZoomFactor = 1.0
        self.setTextSizeMultiplier(self.textZoomFactor)
        self.settings().setAttribute(QWebSettings.JavascriptEnabled, False)
        self.settings().setAttribute(QWebSettings.JavaEnabled, False)
        self.settings().setAttribute(QWebSettings.PluginsEnabled, False)
        self.settings().setAttribute(QWebSettings.ZoomTextOnly, True)
        #self.settings().setAttribute(QWebSettings.SiteSpecificQuirksEnabled, False)
        self.userFindText = QString()
        # Look for pqHelp.html in the app folder and copy its text into
        # a local buffer. If it isn't found, put a message there instead.
        # We need to keep it in order to implement the "back" function.
        helpPath = os.path.join(IMC.appBasePath, u'pqHelp.html')
        helpFile = QFile(helpPath)
        if not helpFile.exists():
            self.HTMLstring = QString('''<p>Unable to locate pqHelp.html.</p>
	    <p>Looking in {0}'''.format(helpPath))
        elif not helpFile.open(QIODevice.ReadOnly):
            self.HTMLstring = QString('''<p>Unable to open pqHelp.html.</p>
	    <p>Looking in {0}</p><p>Error code {1}</p>'''.format(
                helpPath, helpFile.error()))
        else:
            helpStream = QTextStream(helpFile)
            helpStream.setCodec('ISO8859-1')
            self.HTMLstring = helpStream.readAll()
        self.setHtml(self.HTMLstring)
Пример #31
0
    def get_monospace_font(self):
        preferred_fonts_windows = ['Courier New', 'Lucida Console']
        preferred_fonts_linux = ['Noto Mono', 'Monospace']

        if 'Windows' in platform.system():
            pfonts = preferred_fonts_windows
        else:
            pfonts = preferred_fonts_linux

        for fontname in pfonts:
            font = QFont(fontname)
            font.setPointSize(12)
            info = QFontInfo(font)
            if info.fixedPitch():
                return font

        print('Warning: no font in preferred list %s found!'%pfonts)
        font = QFont()
        font.setStyleHint(QFont.Monospace)
        info = QFontInfo(font)
        print('Selected font family: %s'%info.family())
Пример #32
0
    def __init__(self, code_set, parent=None):
        super(CustomCodeFrame, self).__init__(parent)
        self.cs = code_set

        self.tmr_reset_bg_clr = QTimer(self)
        self.tmr_reset_bg_clr.setInterval(500)  # ms
        self.tmr_reset_bg_clr.timeout.connect(self.resetBGColor)

        self.txt_label = QLineEdit(self)
        self.txt_label.setMaximumWidth(160)
        self.txt_label.setPlaceholderText('Label')

        self.txt_codes = QPlainTextEdit(self)
        self.txt_codes.setMaximumHeight(66)
        font = QFont('Monospace')
        font.setStyleHint(QFont.TypeWriter)
        self.txt_codes.setFont(font)
        self.txt_codes.cursorPositionChanged.connect(self.resetBGColor)

        icon_height = self.txt_label.height() * 8 / 15

        self.btn_poke = QPushButton(self)
        self.btn_poke.setIcon(QIcon('img/flaticon/draw39.png'))
        self.btn_poke.setIconSize(QSize(icon_height, icon_height))
        self.btn_poke.setFixedSize(QSize(icon_height * 1.5, icon_height * 1.5))
        self.btn_poke.setAutoFillBackground(True)
        self.btn_poke.setStyleSheet('background-color: white')
        self.btn_poke.setToolTip('Poke memory')
        self.btn_poke.clicked.connect(self.onPoke)

        self.layout = QHBoxLayout(self)
        self.layout.addWidget(self.txt_label)
        self.layout.setAlignment(self.txt_label, Qt.AlignTop)
        self.layout.addWidget(self.txt_codes)
        self.layout.setAlignment(self.txt_codes, Qt.AlignTop)
        self.layout.addWidget(self.btn_poke)
        self.layout.setAlignment(self.btn_poke, Qt.AlignTop)
        self.layout.setContentsMargins(0, 2, 0, 2)
Пример #33
0
  def __init__(self, code_set, parent=None):
    super(CustomCodeFrame, self).__init__(parent)
    self.cs = code_set

    self.tmr_reset_bg_clr = QTimer(self)
    self.tmr_reset_bg_clr.setInterval(500) # ms
    self.tmr_reset_bg_clr.timeout.connect(self.resetBGColor)

    self.txt_label = QLineEdit(self)
    self.txt_label.setMaximumWidth(160)
    self.txt_label.setPlaceholderText('Label')

    self.txt_codes = QPlainTextEdit(self)
    self.txt_codes.setMaximumHeight(66)
    font = QFont('Monospace')
    font.setStyleHint(QFont.TypeWriter)
    self.txt_codes.setFont(font)
    self.txt_codes.cursorPositionChanged.connect(self.resetBGColor)

    icon_height = self.txt_label.height()*8/15

    self.btn_poke = QPushButton(self)
    self.btn_poke.setIcon(QIcon('img/flaticon/draw39.png'))
    self.btn_poke.setIconSize(QSize(icon_height, icon_height))
    self.btn_poke.setFixedSize(QSize(icon_height*1.5, icon_height*1.5))
    self.btn_poke.setAutoFillBackground(True)
    self.btn_poke.setStyleSheet('background-color: white')
    self.btn_poke.setToolTip('Poke memory')
    self.btn_poke.clicked.connect(self.onPoke)

    self.layout = QHBoxLayout(self)
    self.layout.addWidget(self.txt_label)
    self.layout.setAlignment(self.txt_label, Qt.AlignTop)
    self.layout.addWidget(self.txt_codes)
    self.layout.setAlignment(self.txt_codes, Qt.AlignTop)
    self.layout.addWidget(self.btn_poke)
    self.layout.setAlignment(self.btn_poke, Qt.AlignTop)
    self.layout.setContentsMargins(0, 2, 0, 2)
class SystemLog(object):
    def __init__(self, display_name, source_name):
        self.display_name = display_name
        self.source_name = source_name  # FIXME: need to handle rotated logs
        self.last_filename = os.path.join(get_home_path(), display_name)
        self.content = ''
        self.edit = QPlainTextEdit()
        self.normal_font = self.edit.font()
        self.monospace_font = QFont('monospace')

        self.edit.setUndoRedoEnabled(False)
        self.edit.setReadOnly(True)
        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setPlainText(
            'Click "Refresh" to download {0}.'.format(display_name))

        self.monospace_font.setStyleHint(QFont.TypeWriter)

    def log(self, message, bold=False, pre=False):
        if bold:
            self.edit.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
        elif pre:
            self.edit.appendHtml(u'<pre>{0}</pre>'.format(message))
        else:
            self.edit.appendPlainText(message)

    def reset(self):
        self.content = None

        self.edit.setPlainText('')
        self.edit.setFont(self.normal_font)

    def set_content(self, content):
        self.content = content

        self.edit.setPlainText('')
        self.edit.setFont(self.monospace_font)
        self.edit.setPlainText(content)
Пример #35
0
    def resizeEvent(self, event):
        """
        We only need to extend resizeEvent, not every event.
        """

        result = super(SmartSizedMessageBox, self).resizeEvent(event)

        f = QFont('Monospace')
        f.setPointSize(14)
        f.setStyleHint(QFont.TypeWriter)

        details_box = self.findChild(QTextEdit)
        details_box.setFont(f)
        fm = details_box.fontMetrics()
        text = details_box.property('plainText')
        lines = text.split('\n')
        rect = fm.boundingRect(lines[0])
        width  = int(rect.width()*1.5)
        height = int(rect.height()*len(lines)*1.5)
        if details_box is not None:
            details_box.setFixedSize(QSize(width, height))

        return result
Пример #36
0
    def resizeEvent(self, event):
        """
        We only need to extend resizeEvent, not every event.
        """

        result = super(SmartSizedMessageBox, self).resizeEvent(event)

        f = QFont('Monospace')
        f.setPointSize(14)
        f.setStyleHint(QFont.TypeWriter)

        details_box = self.findChild(QTextEdit)
        details_box.setFont(f)
        fm = details_box.fontMetrics()
        text = details_box.property('plainText')
        lines = text.split('\n')
        rect = fm.boundingRect(lines[0])
        width = int(rect.width() * 1.5)
        height = int(rect.height() * len(lines) * 1.5)
        if details_box is not None:
            details_box.setFixedSize(QSize(width, height))

        return result
class SystemLog(object):
    def __init__(self, display_name, source_name):
        self.display_name   = display_name
        self.source_name    = source_name # FIXME: need to handle rotated logs
        self.last_filename  = os.path.join(get_home_path(), display_name)
        self.content        = ''
        self.edit           = QPlainTextEdit()
        self.normal_font    = self.edit.font()
        self.monospace_font = QFont('monospace')

        self.edit.setUndoRedoEnabled(False)
        self.edit.setReadOnly(True)
        self.edit.setWordWrapMode(QTextOption.NoWrap)
        self.edit.setPlainText('Click "Refresh" to download {0}.'.format(display_name))

        self.monospace_font.setStyleHint(QFont.TypeWriter)

    def log(self, message, bold=False, pre=False):
        if bold:
            self.edit.appendHtml(u'<b>{0}</b>'.format(Qt.escape(message)))
        elif pre:
            self.edit.appendHtml(u'<pre>{0}</pre>'.format(message))
        else:
            self.edit.appendPlainText(message)

    def reset(self):
        self.content = None

        self.edit.setPlainText('')
        self.edit.setFont(self.normal_font)

    def set_content(self, content):
        self.content = content

        self.edit.setPlainText('')
        self.edit.setFont(self.monospace_font)
        self.edit.setPlainText(content)
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setColor(QColor(Qt.red), 14)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 2)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.setLexer(self.lexer)
Пример #39
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext", "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)
        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(self.settings.value("pythonConsole/defaultFontColor", QColor(Qt.black))))
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentFontColor", QColor(Qt.gray))), 1)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/keywordFontColor", QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/classFontColor", QColor(Qt.blue))), 8)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/methodFontColor", QColor(Qt.darkGray))), 9)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/decorFontColor", QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/commentBlockFontColor", QColor(Qt.gray))), 12)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/singleQuoteFontColor", QColor(Qt.blue))), 4)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/doubleQuoteFontColor", QColor(Qt.blue))), 3)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleSingleQuoteFontColor", QColor(Qt.blue))), 6)
        self.lexer.setColor(QColor(self.settings.value("pythonConsole/tripleDoubleQuoteFontColor", QColor(Qt.blue))), 7)
        self.lexer.setColor(QColor(Qt.red), 14)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 2)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(self.settings.value("pythonConsole/paperBackgroundColor", QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.setLexer(self.lexer)
Пример #40
0
class OpenedFileView(ScintillaWrapper):
    MARGIN_NUMBERS, MARGIN_MARKER_FOLD, MARGIN_MARKER_BP, MARGIN_MARKER_TP, MARGIN_MARKER_EXEC, \
    MARGIN_MARKER_EXEC_SIGNAL, MARKER_HIGHLIGHTED_LINE, MARGIN_MARKER_STACK, MARGIN_MARKER_BP_DIS = range(9)

    def __init__(self, distributedObjects, filename, parent):
        ScintillaWrapper.__init__(self, parent)
        self.breakpointOverlays = {}

        filename = str(filename)
        self.distributedObjects = distributedObjects
        self.debugController = self.distributedObjects.debugController
        self.__bpModel = self.distributedObjects.breakpointModel
        self.tracepointController = self.distributedObjects.tracepointController
        self.signalProxy = self.distributedObjects.signalProxy
        self.filename = filename
        self.lastContextMenuLine = 0
        self.markerBp = QPixmap(":/markers/bp.png")
        self.markerBpDisabled = QPixmap(":/markers/bp_dis.png")
        self.markerTp = QPixmap(":/markers/tp.png")
        self.markerExec = QPixmap(":/markers/exec_pos.png")
        self.markerStack = QPixmap(":/markers/stack_pos.png")
        self.markerExecSignal = QPixmap(":/markers/exec_pos_signal.png")
        self.shown = False

        self.font = QFont("DejaVu Sans Mono", 10)
        self.font.setStyleHint(QFont.TypeWriter)
        self.lexer = Qsci.QsciLexerCPP()
        self.lexer.setFont(self.font)

        self.setToolTip("")
        self.setWhatsThis("")
        self.setLexer(self.lexer)
        self.setMarginLineNumbers(self.MARGIN_NUMBERS, True)
        # set sensitivity
        self.setMarginSensitivity(self.MARGIN_NUMBERS, True)
        self.setMarginSensitivity(self.MARGIN_MARKER_BP, True)
        self.setMarginSensitivity(self.MARGIN_MARKER_TP, True)
        # define symbol
        self.markerDefine(self.markerBp, self.MARGIN_MARKER_BP)
        self.markerDefine(self.markerBpDisabled, self.MARGIN_MARKER_BP_DIS)
        self.markerDefine(self.markerTp, self.MARGIN_MARKER_TP)
        self.markerDefine(self.markerExec, self.MARGIN_MARKER_EXEC)
        self.markerDefine(self.markerStack, self.MARGIN_MARKER_STACK)
        self.markerDefine(self.markerExecSignal, self.MARGIN_MARKER_EXEC_SIGNAL)
        self.markerDefine(Qsci.QsciScintilla.Background, self.MARKER_HIGHLIGHTED_LINE)

        # define width and mask to show margin
        self.setMarginWidth(self.MARGIN_MARKER_BP, 10)
        self.setMarginMarkerMask(self.MARGIN_MARKER_BP, 1 << self.MARGIN_MARKER_BP | 1 << self.MARGIN_MARKER_BP_DIS)
        self.setMarginWidth(self.MARGIN_MARKER_TP, 10)
        self.setMarginMarkerMask(self.MARGIN_MARKER_TP, 1 << self.MARGIN_MARKER_TP)
        self.setMarginWidth(self.MARGIN_MARKER_EXEC, 10)
        self.setMarginMarkerMask(self.MARGIN_MARKER_EXEC,
                1 << self.MARGIN_MARKER_EXEC |
                1 << self.MARGIN_MARKER_EXEC_SIGNAL |
                1 << self.MARGIN_MARKER_STACK)
        self.setMarginWidth(self.MARKER_HIGHLIGHTED_LINE, 0)
        self.setMarginMarkerMask(self.MARKER_HIGHLIGHTED_LINE, 1 << self.MARKER_HIGHLIGHTED_LINE)

        self.INDICATOR_TOOLTIP = self.indicatorDefine(self.BoxIndicator)
        self.setIndicatorDrawUnder(True, self.INDICATOR_TOOLTIP)

        self.setReadOnly(False)

        if not (QtCore.QFile.exists(filename)):
            logging.error("Could not open file %s", filename)

        self.file_ = QtCore.QFile(filename)
        self.file_.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        self.read(self.file_)
        self.file_.close()

        self.changed = False
        self.modificationChanged.connect(self.__setFileModified)

        self.setMarginWidthByLineNumbers()
        self.SendScintilla(Qsci.QsciScintilla.SCI_SETMOUSEDWELLTIME, 500)

        # override scintillas context menu with our own
        self.SendScintilla(Qsci.QsciScintilla.SCI_USEPOPUP, 0)
        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self.showContextMenu)

        self.marginClicked.connect(self.onMarginClicked)
        self.SCN_DOUBLECLICK.connect(self.editDoubleClicked)
        self.dwellStart.connect(self.onDwellStart)
        self.dwellEnd.connect(self.onDwellEnd)

        self.__bpModel.rowsInserted.connect(self.breakpointsInserted)
        # don't connect to rowsRemoved here since the breakpoint is already gone
        # from the model when it's emitted
        self.__bpModel.rowsAboutToBeRemoved.connect(self.breakpointsRemoved)
        self.__bpModel.dataChanged.connect(self.breakpointsModified)
        _model = self.tracepointController.model()
        _model.rowsInserted.connect(self.getTracepointsFromModel)
        _model.rowsRemoved.connect(self.getTracepointsFromModel)

        act = self.distributedObjects.actions
        act.ToggleTrace.triggered.connect(self.toggleTracepoint)

        self.distributedObjects.editorController.config.itemsHaveChanged.connect(self.updateConfig)
        self.updateConfig()

        # initially, read all breakpoints and tracepoints from the model
        self.getTracepointsFromModel()

        self.__allowToolTip = True
        self.__enableToolTip(True)

        self.__popupMenu = None

        self.__fileWatcher = QFileSystemWatcher([self.filename])
        self.__fileWatcher.fileChanged.connect(self.__fileChanged)

        # this timer is used for a workaround: QFileSystemWatcher will sometimes
        # report a change multiple times; therefore, in self.__fileChanged, we
        # simply start the timer on a notification and discard all notifications
        # while the timer is running
        self.__fileChangedTimer = QTimer()
        self.__fileChangedTimer.setSingleShot(True)
        self.__fileChangedTimer.setInterval(100)

        self.__wordHighlightTimer = QTimer()
        self.cursorPositionChanged.connect(lambda: self.__wordHighlightTimer.start())
        self.__wordHighlightTimer.setSingleShot(True)
        self.__wordHighlightTimer.setInterval(250)
        self.__wordHighlightTimer.timeout.connect(self.highlightWordFromCursorPosition)

    def updateConfig(self):
        qs = Qsci.QsciScintilla
        c = self.distributedObjects.editorController.config
        self.setWhitespaceVisibility(qs.WsVisible if c.showWhiteSpaces.value else qs.WsInvisible)
        self.setIndentationGuides(c.showIndentationGuides.value)
        self.setTabWidth(int(c.tabWidth.value))
        self.setWrapMode(qs.WrapWord if c.wrapLines.value else qs.WrapNone)
        self.setFolding(qs.BoxedTreeFoldStyle if c.folding.value else qs.NoFoldStyle, self.MARGIN_MARKER_FOLD)
        self.lexer.setPaper(QColor(c.backgroundColor.value))
        self.lexer.setColor(QColor(c.identifierColor.value), self.lexer.Identifier)
        self.lexer.setColor(QColor(c.identifierColor.value), self.lexer.Operator)
        self.setCaretForegroundColor(QColor(c.identifierColor.value))
        self.lexer.setColor(QColor(c.keywordColor.value), self.lexer.Keyword)
        self.lexer.setColor(QColor(c.stringColor.value), self.lexer.SingleQuotedString)
        self.lexer.setColor(QColor(c.stringColor.value), self.lexer.DoubleQuotedString)
        self.lexer.setColor(QColor(c.numberColor.value), self.lexer.Number)
        self.lexer.setColor(QColor(c.preprocessorColor.value), self.lexer.PreProcessor)
        self.lexer.setColor(QColor(c.commentColor.value), self.lexer.Comment)
        self.lexer.setColor(QColor(c.commentColor.value), self.lexer.CommentLine)
        self.lexer.setColor(QColor(c.commentColor.value), self.lexer.CommentDoc)
        self.setIndicatorForegroundColor(QColor(c.tooltipIndicatorColor.value))
        self.setMarkerBackgroundColor(QColor(c.highlightColor.value), self.MARKER_HIGHLIGHTED_LINE)

        # check whether we're supposed to use overlays and reload everything
        # that uses them
        self.__useBreakpointOverlays = c.useBreakpointOverlays.value
        self.getBreakpointsFromModel()

    def __fileChanged(self):
        if not self.__fileChangedTimer.isActive():
            logging.warning("Source file %s modified. Recompile executable for correct debugging.", self.filename)
            self.__fileChangedTimer.start()

    def saveFile(self):
        ''' Save source file '''
        if (QtCore.QFile.exists(self.filename)):
            f = open(self.filename, 'w')
            f.write(self.text())
            f.close()
            self.file_.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
            self.read(self.file_)
            self.file_.close()
            self.__setFileModified(False)

    def __setFileModified(self, modified):
        ''' Method called whenever current file is marked as modified '''
        self.distributedObjects.signalProxy.fileModified.emit(self.filename, modified)

    def onDwellStart(self, pos, x, y):
        if self.__allowToolTip:
            exp, (line, start, end) = self.getWordOrSelectionAndRangeFromPosition(pos)

            # try evaluating the expression before doing anything else: this will return None if the
            # expression is not valid (ie. something that is not a variable)
            if self.debugController.evaluateExpression(exp.strip()) is not None:
                startPos = self.positionFromLineIndex(line, start)
                x = self.SendScintilla(Qsci.QsciScintilla.SCI_POINTXFROMPOSITION, 0, startPos)
                y = self.SendScintilla(Qsci.QsciScintilla.SCI_POINTYFROMPOSITION, 0, startPos)
                self.distributedObjects.toolTipController.showToolTip(exp, QtCore.QPoint(x + 3, y + 3 + self.textHeight(line)), self)

    def onDwellEnd(self, _1, _2, _3):
        self.distributedObjects.toolTipController.hideToolTip()

    def showContextMenu(self, point):
        scipos = self.SendScintilla(
                Qsci.QsciScintilla.SCI_POSITIONFROMPOINT, point.x(), point.y())
        point = self.mapToGlobal(point)
        exp, (line, start, end) = self.getWordOrSelectionAndRangeFromPosition(scipos)

        # self.lineIndexFromPosition(..) returns tuple. first element is line
        self.lastContextMenuLine = int(self.lineIndexFromPosition(scipos)[0])

        self.__popupMenu = QtGui.QMenu(self)
        self.__popupMenu.addAction(self.distributedObjects.actions.ToggleTrace)

        if exp:
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddToWatchAction(exp, self.signalProxy.addWatch))
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddToDatagraphAction(exp, self.distributedObjects.datagraphController.addWatch))
            self.__popupMenu.addAction(self.distributedObjects.actions.getAddWatchpointAction(exp, self.distributedObjects.breakpointModel.insertWatchpoint))

            listOfTracepoints = self.tracepointController.getTracepointsFromModel()
            if listOfTracepoints:
                subPopupMenu = QtGui.QMenu(self)
                subPopupMenu.setTitle("Add variable " + exp + " to tracepoint...")

                for tp in listOfTracepoints:
                    subPopupMenu.addAction(self.distributedObjects.actions.getAddToTracepointAction(exp, tp.name, tp.addVar))

                self.__popupMenu.addSeparator()
                self.__popupMenu.addMenu(subPopupMenu)

        self.__popupMenu.popup(point)

        # disable the tooltips while the menu is shown
        self.__enableToolTip(False)
        self.__popupMenu.aboutToHide.connect(lambda: self.__enableToolTip(True))

    def __enableToolTip(self, enable):
        self.__allowToolTip = enable

    def isPositionInsideSelection(self, position):
        lf, cf, lt, ct = self.getSelection()
        pl, pc = self.lineIndexFromPosition(position)

        if lf < pl and pl < lt:
            return True
        elif lf == pl and pl < lt:
            return True if cf <= pc else False
        elif lf < pl and pl == lt:
            return True if pc <= ct else False
        elif lf == pl and pl == lt:
            return True if (cf <= pc and pc <= ct) else False
        else:
            return False

    def getWordOrSelectionAndRangeFromPosition(self, position):
        if self.isPositionInsideSelection(position):
            line, start, lineTo, end = self.getSelection()
            if line != lineTo:
                return "", (None, None, None)
        else:
            line, start, end = self.getWordRangeFromPosition(position)
        return self.getWordFromRange(line, start, end), (line, start, end)

    def getWordRangeFromPosition(self, position):
        line, col = self.lineIndexFromPosition(position)
        start, end = self.getWordRangeFromLineCol(line, col)
        return line, start, end

    def getWordRangeFromLineCol(self, line, col):
        s = str(self.text(line))
        start = col - 1
        end = col

        a = 0

        while start >= 0:
            if s[start].isalnum() or s[start] in [".", "_"]:
                pass
            elif s[start] == ">" and start >= 1 and s[start - 1] == "-":
                start -= 1
            elif s[start] == "]":
                a -= 1
            elif s[start] == "[":
                a += 1
            else:
                break
            start -= 1
        start += 1

        while end < len(s):
            if a >= 0:
                pass
            if s[end].isalnum() or s[end] == "_":
                pass
            elif s[end] == "]":
                a -= 1
            else:
                break
            end += 1

        if a == 0:
            return start, end
        else:
            return 0, 0

    def getWordFromLineCol(self, line, col):
        self.clearIndicatorRange(0, 0, self.lines(), 1, self.INDICATOR_TOOLTIP)

        start, end = self.getWordRangeFromLineCol(line, col)
        word = self.getWordFromRange(line, start, end)
        if word:
            for i, line in enumerate(self.text().split('\n')):
                for match in re.finditer(r"\b%s\b" % word, line):
                    self.fillIndicatorRange(i, match.start(), i, match.end(), self.INDICATOR_TOOLTIP)
                

    def getWordFromRange(self, line, start, end):
        return str(self.text(line))[start:end]

    def editDoubleClicked(self, position, line, modifiers):
        line, start, end = self.getWordRangeFromPosition(position)
        w = str(self.text(line))[start:end]
        if w:
            self.signalProxy.addWatch(w)

    def showExecutionPosition(self, line):
        self.markerAdd(line, self.MARGIN_MARKER_EXEC)
        self.showLine(line)

    def showSignalPosition(self, line):
        self.markerAdd(line, self.MARGIN_MARKER_EXEC_SIGNAL)
        self.showLine(line)

    def showLine(self, line):
        self.setCursorPosition(line, 1)
        self.ensureLineVisible(line)

    def clearExecutionPositionMarkers(self):
        self.markerDeleteAll(self.MARGIN_MARKER_EXEC)

    def setMarginWidthByLineNumbers(self):
        self.setMarginWidth(0, ceil(log(self.lines(), 10)) * 10 + 5)

    def onMarginClicked(self, margin, line, _):
        # if breakpoint should be toggled
        if margin == self.MARGIN_NUMBERS or margin == self.MARGIN_MARKER_BP:
            self.toggleBreakpointWithLine(line)
        elif margin == self.MARGIN_MARKER_TP:
            self.toggleTracepointWithLine(line)

    def highlightWordFromCursorPosition(self):
        line, col = self.getCursorPosition()
        print self.getWordFromLineCol(line, col)

    def toggleBreakpointWithLine(self, line):
        self.__bpModel.toggleBreakpoint(self.filename, line + 1)

    def toggleTracepointWithLine(self, line):
        self.tracepointController.toggleTracepoint(self.filename, line + 1)

    def toggleTracepoint(self):
        self.toggleTracepointWithLine(self.lastContextMenuLine)

    def getBreakpointsFromModel(self):
        self.markerDeleteAll(self.MARGIN_MARKER_BP)
        self.markerDeleteAll(self.MARGIN_MARKER_BP_DIS)

        self.removeAllOverlayWidgets()
        self.breakpointOverlays = {}

        for bp in self.__bpModel.breakpoints:
            if bp.fullname == self.filename:
                self.markerAdd(bp.line - 1, self.MARGIN_MARKER_BP if bp.enabled else self.MARGIN_MARKER_BP_DIS)
                self.__addBreakpointOverlay(bp)

    def __addBreakpointOverlay(self, bp):
        if not self.__useBreakpointOverlays:
            return

        l = BreakpointOverlayWidget(self.viewport(), bp, self.__bpModel)
        self.breakpointOverlays[bp.number] = l
        self.__updateBreakpointOverlay(bp)
        l.show()
        self.addOverlayWidget(l, int(bp.line), None, 50, 400)

    def __updateBreakpointOverlay(self, bp):
        if not self.__useBreakpointOverlays:
            return

        w = self.breakpointOverlays[bp.number]
        w.update()

    def __removeBreakpointOverlay(self, bp):
        if not self.__useBreakpointOverlays:
            return

        self.removeOverlayWidget(self.breakpointOverlays[bp.number], bp.line)

    def __validBreakpoints(self, startRow, endRow):
        for i in xrange(startRow, endRow + 1):
            # the column has no meaning here, all columns will return the
            # breakpoint object for role InternalDataRole
            bp = self.__bpModel.data(self.__bpModel.index(i, 0), self.__bpModel.InternalDataRole)
            if not bp.fullname == self.filename:
                continue
            yield bp

    def breakpointsInserted(self, _, start, end):
        for bp in self.__validBreakpoints(start, end):
            self.markerAdd(bp.line - 1, self.MARGIN_MARKER_BP if bp.enabled else self.MARGIN_MARKER_BP_DIS)
            self.__addBreakpointOverlay(bp)

    def breakpointsRemoved(self, _, start, end):
        for bp in self.__validBreakpoints(start, end):
            self.markerDelete(bp.line - 1, self.MARGIN_MARKER_BP)
            self.markerDelete(bp.line - 1, self.MARGIN_MARKER_BP_DIS)
            self.__removeBreakpointOverlay(bp)

    def breakpointsModified(self, topLeft, bottomRight):
        for bp in self.__validBreakpoints(topLeft.row(), bottomRight.row()):
            self.markerDelete(bp.line - 1, self.MARGIN_MARKER_BP)
            self.markerDelete(bp.line - 1, self.MARGIN_MARKER_BP_DIS)
            self.markerAdd(bp.line - 1, self.MARGIN_MARKER_BP if bp.enabled else self.MARGIN_MARKER_BP_DIS)
            self.__updateBreakpointOverlay(bp)

    def getTracepointsFromModel(self):
        """Get tracepoints from model."""
        self.markerDeleteAll(self.MARGIN_MARKER_TP)
        for tp in self.tracepointController.getTracepointsFromModel():
            if tp.fullname == self.filename:
                self.markerAdd(int(tp.line) - 1, self.MARGIN_MARKER_TP)

    def highlightLine(self, line):
        self.removeHighlightedLines()
        self.markerAdd(line, self.MARKER_HIGHLIGHTED_LINE)
        QTimer.singleShot(int(self.distributedObjects.editorController.config.highlightingDuration.value), self.removeHighlightedLines)

    def removeHighlightedLines(self):
        self.markerDeleteAll(self.MARKER_HIGHLIGHTED_LINE)
    def __init__(self):
        """Widget creator."""

        super().__init__()

        # Other attributes...
        self.inputSeg = None
        self.morphology = dict()
        self.selectedMainWord = None
        self.mainWords = list()
        self.selectedParse = None
        self.parses = list()
        self.selectedStemForParse = None
        self.stemsForParse = list()
        self.selectedSuffixForParse = None
        self.suffixesForParse = list()
        self.selectedMainSignature = None
        self.mainSignatures = list()
        self.wordsForSig = list()
        self.stemsForSig = list()
        self.suffixesForSig = list()

        # Next two instructions are helpers from TextableUtils. Corresponding
        # interface elements are declared here and actually drawn below (at
        # their position in the UI)...
        self.infoBox = InfoBox(widget=self.controlArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute="infoBox",
            sendIfPreCallback=None,
        )

        # User interface...

        # A) Control area...

        # Options box...
        optionsBox = gui.widgetBox(
            widget=self.controlArea,
            box="Options",
            orientation="vertical",
        )
        gui.spin(
            widget=optionsBox,
            master=self,
            value='minStemLen',
            label='Minimum length of stems: ',
            callback=self.sendButton.sendIf,
            labelWidth=180,
            tooltip=(
                'Select the minimum number of required characters in stems'),
            minv=LOWER_MIN_STEM_LEN,
            maxv=MAX_MORPH_LEN,
            step=1,
        )
        gui.separator(widget=optionsBox, height=2)

        gui.rubber(self.controlArea)

        # B) Main area...

        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)

        # Tabs...
        self.tabs = QTabWidget()
        self.wordTab = QWidget()
        self.signatureTab = QWidget()
        self.tabs.addTab(self.wordTab, "Words")
        self.tabs.addTab(self.signatureTab, "Signatures")

        # Words tab...
        wordTabBox = QHBoxLayout()
        wordBox = gui.widgetBox(
            widget=self.wordTab,
            orientation="horizontal",
            margin=5,
        )

        wordBoxRight = gui.widgetBox(widget=wordBox)

        self.mainWordListbox = gui.listBox(
            widget=wordBoxRight,
            master=self,
            value="selectedMainWord",
            labels="mainWords",
            callback=self.mainWordSelected,
            tooltip="Select a word to display its possible parses.",
        )
        self.mainWordListbox.setFont(font)

        gui.separator(widget=wordBox, width=3)

        wordBoxLeft = gui.widgetBox(widget=wordBox)

        gui.label(
            widget=wordBoxLeft,
            master=self,
            label="Parse(s):",
        )

        self.parsesListbox = gui.listBox(
            widget=wordBoxLeft,
            master=self,
            value="selectedParse",
            labels="parses",
            callback=self.parseSelected,
            tooltip="Select a parse to display the corresponding signature.",
        )
        self.parsesListbox.setFont(font)

        self.sigForParseBox = gui.widgetBox(
            widget=wordBoxLeft,
            box="Signature",
        )

        gui.label(
            widget=self.sigForParseBox,
            master=self,
            label="Stem(s):",
        )

        self.stemsForParseListbox = gui.listBox(
            widget=self.sigForParseBox,
            master=self,
            labels="stemsForParse",
            tooltip="Stems associated with the parse selected above.",
        )

        gui.separator(widget=self.sigForParseBox, height=2)

        gui.label(
            widget=self.sigForParseBox,
            master=self,
            label="Suffixes(s):",
        )

        self.suffixesForParseListbox = gui.listBox(
            widget=self.sigForParseBox,
            master=self,
            labels="suffixesForParse",
            tooltip="Suffixes associated with the parse selected above.",
        )

        wordTabBox.addWidget(wordBox)
        self.wordTab.setLayout(wordTabBox)

        # Signature tab...
        signatureTabBox = QHBoxLayout()

        signatureBox = gui.widgetBox(
            widget=self.signatureTab,
            orientation="horizontal",
            margin=5,
        )

        signatureBoxRight = gui.widgetBox(widget=signatureBox)

        self.mainSignatureListbox = gui.listBox(
            widget=signatureBoxRight,
            master=self,
            value="selectedMainSignature",
            labels="mainSignatures",
            callback=self.mainSignatureSelected,
            tooltip="Select a signature to display its contents.",
        )
        self.mainSignatureListbox.setFont(font)

        gui.separator(widget=signatureBox, width=3)

        signatureBoxLeft = gui.widgetBox(widget=signatureBox)

        gui.label(
            widget=signatureBoxLeft,
            master=self,
            label="Words:",
        )

        self.wordsForSigListbox = gui.listBox(
            widget=signatureBoxLeft,
            master=self,
            labels="wordsForSig",
            tooltip="Words associated with the selected signature.",
        )
        self.wordsForSigListbox.setFont(font)

        gui.label(
            widget=signatureBoxLeft,
            master=self,
            label="Stem(s):",
        )

        self.stemsForSigListbox = gui.listBox(
            widget=signatureBoxLeft,
            master=self,
            labels="stemsForSig",
            tooltip="Stems associated with the selected signature.",
        )
        self.stemsForSigListbox.setFont(font)

        gui.label(
            widget=signatureBoxLeft,
            master=self,
            label="Suffixes(s):",
        )

        self.suffixesForSigListbox = gui.listBox(
            widget=signatureBoxLeft,
            master=self,
            labels="suffixesForSig",
            tooltip="Suffixes associated with the selected signature.",
        )
        self.suffixesForSigListbox.setFont(font)

        signatureTabBox.addWidget(signatureBox)
        self.signatureTab.setLayout(signatureTabBox)

        self.mainArea.layout().addWidget(self.tabs)

        # Now Info box and Send button must be drawn...
        self.sendButton.draw()
        self.infoBox.draw()
        self.infoBox.setText("Widget needs input", "warning")

        self.setMinimumWidth(602)
        self.setMinimumHeight(317)
        self.adjustSizeWithTimer()

        # Send data if autoSend.
        self.sendButton.sendIf()
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.label = u'extracted_xml'
        self.importElement = False

        # Other attributes...
        self.inputSegmentation = None
        self.conditionsLabels = list()
        self.selectedConditionsLabels = list()
        self.newConditionAttribute = u''
        self.newConditionRegex = r''
        self.ignoreCase = False
        self.unicodeDependent = True
        self.multiline = False
        self.dotAll = False
        self.infoBox = InfoBox(widget=self.controlArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute='infoBox',
            sendIfPreCallback=self.updateGUI,
        )
        self.advancedSettings = AdvancedSettings(
            widget=self.controlArea,
            master=self,
            callback=self.sendButton.settingsChanged,
        )

        # GUI...

        self.advancedSettings.draw()

        # XML extraction box
        xmlExtractionBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'XML Extraction',
            orientation='vertical',
        )
        gui.lineEdit(
            widget=xmlExtractionBox,
            master=self,
            value='element',
            orientation='horizontal',
            label=u'XML element:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"The XML element that will be extracted from the\n"
                     u"input segmentation."),
        )
        gui.separator(widget=xmlExtractionBox, height=3)
        xmlExtractionBoxLine2 = gui.widgetBox(
            widget=xmlExtractionBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        gui.checkBox(
            widget=xmlExtractionBoxLine2,
            master=self,
            value='importElement',
            label=u'Import element with key:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Associate each output segment with an annotation\n"
                     u"whose value is the above specified XML element."),
        )
        self.importElementAsLineEdit = gui.lineEdit(
            widget=xmlExtractionBoxLine2,
            master=self,
            value='importElementAs',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for the XML element."),
        )
        gui.checkBox(
            widget=xmlExtractionBox,
            master=self,
            value='deleteMarkup',
            label=u'Remove markup',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Check this box to remove all XML markup occurring\n"
                     u"within the above specified XML element."),
        )
        gui.separator(widget=xmlExtractionBox, height=3)
        gui.checkBox(
            widget=xmlExtractionBox,
            master=self,
            value='preserveLeaves',
            label=u'Prioritize shallow attributes',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"This box lets you indicate how you want to solve\n"
                     u"conflicts that may occur in the case where two\n"
                     u"or more occurrences of the above specified XML\n"
                     u"element are nested and have different values for\n"
                     u"the same attribute\n\n"
                     u"By default, the attribute value associated with\n"
                     u"the deepest element will be used. Check this box\n"
                     u"if you would rather use the value of the most\n"
                     u"shallow element."),
        )
        gui.separator(widget=xmlExtractionBox, height=3)
        conditionsBox = gui.widgetBox(
            widget=xmlExtractionBox,
            box=u'Conditions',
            orientation='vertical',
        )
        xmlExtractionBoxLine4 = gui.widgetBox(
            widget=conditionsBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        self.conditionsListbox = gui.listBox(
            widget=xmlExtractionBoxLine4,
            master=self,
            value='selectedConditionsLabels',
            labels='conditionsLabels',
            callback=self.updateConditionsBoxButtons,
            tooltip=(u"The list of conditions on attribute values that\n"
                     u"will be applied to in-/exclude each occurrence\n"
                     u"of the above specified XML element in the output\n"
                     u"segmentation.\n\n"
                     u"Note that all conditions must be satisfied for an\n"
                     u"element occurrence to be included.\n\n"
                     u"Column 1 shows the name of the attribute.\n"
                     u"Column 2 shows the corresponding regex pattern.\n"
                     u"Column 3 shows the associated flags."),
        )
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)
        self.conditionsListbox.setFont(font)
        xmlExtractionBoxCol2 = gui.widgetBox(
            widget=xmlExtractionBoxLine4,
            orientation='vertical',
        )
        self.removeButton = gui.button(
            widget=xmlExtractionBoxCol2,
            master=self,
            label=u'Remove',
            callback=self.remove,
            tooltip=(u"Remove the selected condition from the list."),
        )
        self.clearAllButton = gui.button(
            widget=xmlExtractionBoxCol2,
            master=self,
            label=u'Clear All',
            callback=self.clearAll,
            tooltip=(u"Remove all conditions from the list."),
        )
        xmlExtractionBoxLine5 = gui.widgetBox(
            widget=conditionsBox,
            box=False,
            orientation='vertical',
        )
        # Add condition box
        addConditionBox = gui.widgetBox(
            widget=xmlExtractionBoxLine5,
            box=False,
            orientation='vertical',
        )
        gui.lineEdit(
            widget=addConditionBox,
            master=self,
            value='newConditionAttribute',
            orientation='horizontal',
            label=u'Attribute:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"The name of attribute in the condition that will\n"
                     u"be added to the list when button 'Add' is clicked."),
        )
        gui.separator(widget=addConditionBox, height=3)
        gui.lineEdit(
            widget=addConditionBox,
            master=self,
            value='newConditionRegex',
            orientation='horizontal',
            label=u'Regex:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"The regex pattern associated with the condition\n"
                     u"that will be added to the list when button 'Add'\n"
                     u"is clicked."),
        )
        gui.separator(widget=addConditionBox, height=3)
        addConditionBoxLine3 = gui.widgetBox(
            widget=addConditionBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addConditionBoxLine3,
            master=self,
            value='ignoreCase',
            label=u'Ignore case (i)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Regex pattern is case-insensitive."),
        )
        gui.checkBox(
            widget=addConditionBoxLine3,
            master=self,
            value='unicodeDependent',
            label=u'Unicode dependent (u)',
            callback=self.updateGUI,
            tooltip=(u"Built-in character classes are Unicode-aware."),
        )
        addConditionBoxLine4 = gui.widgetBox(
            widget=addConditionBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addConditionBoxLine4,
            master=self,
            value='multiline',
            label=u'Multiline (m)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Anchors '^' and '$' match the beginning and\n"
                     u"end of each line (rather than just the beginning\n"
                     u"and end of each input segment)."),
        )
        gui.checkBox(
            widget=addConditionBoxLine4,
            master=self,
            value='dotAll',
            label=u'Dot matches all (s)',
            callback=self.updateGUI,
            tooltip=(u"Meta-character '.' matches any character (rather\n"
                     u"than any character but newline)."),
        )
        gui.separator(widget=addConditionBox, height=3)
        self.addButton = gui.button(
            widget=addConditionBox,
            master=self,
            label=u'Add',
            callback=self.add,
            tooltip=(u"Add the current condition to the list."),
        )
        self.advancedSettings.advancedWidgets.append(xmlExtractionBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # Options box...
        optionsBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Options',
            orientation='vertical',
            addSpace=False,
        )
        optionsBoxLine2 = gui.widgetBox(
            widget=optionsBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        gui.checkBox(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumber',
            label=u'Auto-number with key:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotate output segments with increasing numeric\n"
                     u"indices."),
        )
        self.autoNumberKeyLineEdit = gui.lineEdit(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumberKey',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for output segment auto-numbering."),
        )
        gui.checkBox(
            widget=optionsBox,
            master=self,
            value='importAnnotations',
            label=u'Import annotations',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Add to each output segment the annotation keys\n"
                     u"and values associated with the corresponding\n"
                     u"input segment."),
        )
        gui.separator(widget=optionsBox, height=3)
        gui.checkBox(
            widget=optionsBox,
            master=self,
            value='mergeDuplicates',
            label=u'Fuse duplicates',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Fuse segments that have the same address.\n\n"
                     u"The annotation of fused segments will be fused\n"
                     u"as well. In the case where fused segments have\n"
                     u"distinct values for the same annotation key, only\n"
                     u"the value of the last one will be kept."),
        )
        gui.separator(widget=optionsBox, height=2)
        self.advancedSettings.advancedWidgets.append(optionsBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # (Basic) XML extraction box
        basicXmlExtractionBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'XML Extraction',
            orientation='vertical',
            addSpace=False,
        )
        gui.lineEdit(
            widget=basicXmlExtractionBox,
            master=self,
            value='element',
            orientation='horizontal',
            label=u'XML element:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"The XML element that will be extracted from the\n"
                     u"input segmentation."),
        )
        gui.separator(widget=basicXmlExtractionBox, height=3)
        gui.checkBox(
            widget=basicXmlExtractionBox,
            master=self,
            value='deleteMarkup',
            label=u'Remove markup',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Check this box to remove all XML markup occurring\n"
                     u"within the above specified XML element."),
        )
        gui.separator(widget=basicXmlExtractionBox, height=2)
        self.advancedSettings.basicWidgets.append(basicXmlExtractionBox)
        self.advancedSettings.basicWidgetsAppendSeparator()

        gui.rubber(self.controlArea)

        # Send button...
        self.sendButton.draw()

        # Info box...
        self.infoBox.draw()

        self.sendButton.sendIf()
        self.adjustSizeWithTimer()
Пример #43
0
    def __init__(self):
        QDialog.__init__(self)
        self.setupUi(self)
        self.setWindowIcon(QIcon('logo.svg'))
        self.setWindowFlags(Qt.WindowMinimizeButtonHint)

        s = QSettings("norBIT", "norGIS-ALKIS-Import")

        self.leSERVICE.setText(s.value("service", ""))
        self.leHOST.setText(s.value("host", ""))
        self.lePORT.setText(s.value("port", "5432"))
        self.leDBNAME.setText(s.value("dbname", ""))
        self.leUID.setText(s.value("uid", ""))
        self.lePWD.setText(s.value("pwd", ""))
        self.lstFiles.addItems(s.value("files", []) or [])
        self.cbxSkipFailures.setChecked(
            s.value("skipfailures", False, type=bool))
        self.cbFnbruch.setCurrentIndex(
            0 if s.value("fnbruch", True, type=bool) else 1)
        self.cbxDebug.setChecked(s.value("debug", False, type=bool))

        self.cbEPSG.addItem("UTM32N", "25832")
        self.cbEPSG.addItem("UTM33N", "25833")
        self.cbEPSG.addItem("3GK2 (BW)", "131466")
        self.cbEPSG.addItem("3GK3 (BW)", "131467")
        self.cbEPSG.addItem("3GK4 (BY)", "131468")
        self.cbEPSG.setCurrentIndex(
            self.cbEPSG.findData(s.value("epsg", "25832")))

        self.pbAdd.clicked.connect(self.selFiles)
        self.pbAddDir.clicked.connect(self.selDir)
        self.pbRemove.clicked.connect(self.rmFiles)
        self.pbSelectAll.clicked.connect(self.lstFiles.selectAll)
        self.pbLoad.clicked.connect(self.loadList)
        self.pbSave.clicked.connect(self.saveList)
        self.lstFiles.itemSelectionChanged.connect(self.selChanged)

        self.pbStart.clicked.connect(self.run)
        self.pbLoadLog.clicked.connect(self.loadLog)
        self.pbSaveLog.clicked.connect(self.saveLog)
        self.pbClearLog.clicked.connect(self.clearLog)
        self.pbAbout.clicked.connect(self.about)
        self.pbClose.clicked.connect(self.accept)
        self.pbProgress.setValue(0)

        f = QFont("Monospace")
        f.setStyleHint(QFont.TypeWriter)
        self.lwProtocol.setFont(f)
        self.lwProtocol.setUniformItemSizes(True)

        self.status("")

        self.restoreGeometry(s.value("geometry", QByteArray(),
                                     type=QByteArray))

        self.canceled = False
        self.running = False
        self.skipScroll = False
        self.logqry = None

        self.reFilter = None
Пример #44
0
class ScaleBarItem(QGraphicsItem):
    def __init__(self, canvas, parent=None):
        super(ScaleBarItem, self).__init__(parent)
        self.canvas = canvas
        self.realsize = 100
        black = QColor(Qt.black)
        black.setAlpha(150)
        white = QColor(Qt.white)
        white.setAlpha(150)
        blackpen = QPen(black, 4)
        whitepen = QPen(white, 8)
        self.pens = [whitepen, blackpen]
        self.whitepen = QPen(white, 1)
        self.blackbrush = QBrush(black)
        self.ticksize = 10
        self.fontsize = 15
        self.font = QFont()
        self.font.setPointSize(self.fontsize)
        self.font.setStyleHint(QFont.Times, QFont.PreferAntialias)
        self.font.setBold(True)
        self.metrics = QFontMetrics(self.font)

    def boundingRect(self):
        try:
            width, realsize, label, fontsize = self._calc_size()
            halfheight = (self.ticksize + fontsize[1]) / 2
            halfwidth = (width + fontsize[0]) / 2
            return QRectF(-halfwidth, -halfheight, halfwidth, halfheight)
        except ZeroDivisionError:
            return QRectF()

    def paint(self, painter, styleoptions, widget=None):
        try:
            width, realsize, label, fontsize = self._calc_size()
        except ZeroDivisionError:
            return

        mapunits = self.canvas.mapUnits()

        # painter.drawRect(self.boundingRect())
        array = QPolygon()
        canvasheight = self.canvas.height()
        canvaswidth = self.canvas.width()
        margin = 20
        originy = 0
        originx = 0

        self.setPos(margin, canvasheight - margin)

        x1, y1 = originx, originy
        x2, y2 = originx, originy + self.ticksize
        x3, y3 = originx + width, originy + self.ticksize
        midx, midy = originx + width /2, originy + self.ticksize / 2
        x4, y4 = originx + width, originy

        for pen in self.pens:
            painter.setPen(pen)
            # Drwa the scale bar
            painter.drawLine(x1, y1, x2, y2)
            painter.drawLine(x2, y2, x3, y3)
            painter.drawLine(x3, y3, x4, y4)
            painter.drawLine(midx, midy, midx, y1)

        # Draw the text
        fontwidth = self.metrics.width("0")
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        path = QPainterPath()
        point = QPointF(x1 - fontwidth, y1 - fontheight)
        path.addText(point, self.font, "0")
        painter.setPen(self.whitepen)
        painter.setBrush(self.blackbrush)
        painter.setRenderHints(QPainter.Antialiasing)
        painter.setFont(self.font)
        painter.drawPath(path)

        fontwidth = self.metrics.width(label)
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        point = QPointF(x4 - fontwidth, y4 - fontheight)
        path.addText(point, self.font, label)
        painter.drawPath(path)

    def _calc_size(self):
        realSize = self.realsize
        canvaswidth = self.canvas.width()
        mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel())
        mapunits = self.canvas.mapUnits()
        prefered_units = roam.config.settings.get("prefer_units", "meters")
        newunits = QGis.fromLiteral(prefered_units, QGis.Meters)
        mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits)
        mapunits = newunits

        # Convert the real distance into pixels
        barwidth = realSize / mapunitsperpixel

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

        # Round
        powerof10 = math.floor(math.log10(realSize))
        scaler = math.pow(10.0, powerof10)
        realSize = round(realSize / scaler) * scaler
        barwidth = realSize / mapunitsperpixel
        label, realSize = self._label_size(mapunits, realSize)
        metrics = QFontMetrics(self.font)
        fontwidth = metrics.width(label)
        fontheight = metrics.height()

        sizelabel = QLocale.system().toString(realSize)
        sizelabel = "{} {}".format(sizelabel, label)

        barwidth = self._adjust_bar_size(barwidth, mapunits)
        barwidth = barwidth + fontwidth

        return barwidth, realSize, sizelabel, (fontwidth, fontheight)

    def _label_size(self, unit, currentsize):
        if unit == QGis.Meters:
            if currentsize > 1000:
                return "km", currentsize / 1000
            elif currentsize < 0.01:
                return "mm", currentsize * 1000
            elif currentsize < 0.1:
                return "cm", currentsize * 100
            else:
                return "m", currentsize
        elif unit == QGis.Feet:
            print currentsize
            if currentsize > 5280.0:
                return "miles", currentsize / 5000
            elif currentsize == 5280.0:
                return "mile", currentsize / 5000
            elif currentsize < 1:
                return "inches", currentsize * 10
            elif currentsize == 1.0:
                return "foot", currentsize
            else:
                return "feet", currentsize
        elif unit == QGis.Degrees:
            if currentsize == 1.0:
                return "degree", currentsize
            else:
                return "degrees", currentsize
        else:
            return str(unit), currentsize

    def _adjust_bar_size(self, barsize, unit):
        if unit == QGis.Feet:
            if barsize > 5280.0 or barsize == 5280.0:
                return (barsize * 5290) / 5000
            elif barsize < 1:
                return (barsize * 10) / 12

        return barsize
Пример #45
0
    def __init__(self, data):
        icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning)
        F = self.DataField

        def _finished(*, key=(data.get(F.MODULE),
                              data.get(F.WIDGET_MODULE)),
                      filename=data.get(F.WIDGET_SCHEME)):
            self._cache.add(key)
            try: os.remove(filename)
            except Exception: pass

        super().__init__(None, Qt.Window, modal=True,
                         sizeGripEnabled=True, windowIcon=icon,
                         windowTitle='Unexpected Error',
                         finished=_finished)
        self._data = data

        layout = QVBoxLayout(self)
        self.setLayout(layout)
        labels = QWidget(self)
        labels_layout = QHBoxLayout(self)
        labels.setLayout(labels_layout)
        labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50)))
        labels_layout.addWidget(QLabel(
            'The program encountered an unexpected error. Please<br>'
            'report it anonymously to the developers.<br><br>'
            'The following data will be reported:'))
        labels_layout.addStretch(1)
        layout.addWidget(labels)
        font = QFont('Monospace', 10)
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        textbrowser = QTextBrowser(self,
                                   font=font,
                                   openLinks=False,
                                   lineWrapMode=QTextBrowser.NoWrap,
                                   anchorClicked=QDesktopServices.openUrl)
        layout.addWidget(textbrowser)

        def _reload_text():
            add_scheme = cb.isChecked()
            settings.setValue('error-reporting/add-scheme', add_scheme)
            lines = ['<table>']
            for k, v in data.items():
                if k.startswith('_'):
                    continue
                _v, v = v, escape(v)
                if k == F.WIDGET_SCHEME:
                    if not add_scheme:
                        continue
                    v = '<a href="{}">{}</a>'.format(urljoin('file:', pathname2url(_v)), v)
                if k == F.STACK_TRACE:
                    v = v.replace('\n', '<br>').replace(' ', '&nbsp;')
                lines.append('<tr><th align="left">{}:</th><td>{}</td></tr>'.format(k, v))
            lines.append('</table>')
            textbrowser.setHtml(''.join(lines))

        settings = QSettings()
        cb = QCheckBox(
            'Include workflow (data will NOT be transmitted)', self,
            checked=settings.value('error-reporting/add-scheme', True, type=bool))
        cb.stateChanged.connect(_reload_text)
        _reload_text()

        layout.addWidget(cb)
        buttons = QWidget(self)
        buttons_layout = QHBoxLayout(self)
        buttons.setLayout(buttons_layout)
        buttons_layout.addWidget(QPushButton('Send Report (Thanks!)', default=True, clicked=self.accept))
        buttons_layout.addWidget(QPushButton("Don't Send", default=False, clicked=self.reject))
        layout.addWidget(buttons)
Пример #46
0
from PyQt4.QtGui import QFont, QHBoxLayout, QFrame
from PyQt4 import QtCore

monospace_font = QFont('Monospace')
monospace_font.setStyleHint(QFont.TypeWriter)

script_file_filter = 'Coinscripts (*.coinscript);;Text files (*.txt);;All files (*.*)'

def floated_buttons(btns, left=False):
    """Returns a HBoxLayout with buttons floated to the right or left."""
    hbox = QHBoxLayout()
    for b in btns:
        hbox.addWidget(b)
    if left:
        hbox.addStretch(1)
    else:
        hbox.insertStretch(0, 1)
    return hbox

class Separator(QFrame):
    def __init__(self, parent=None):
        super(Separator, self).__init__(parent)
        self.setFrameShape(QFrame.HLine)
        self.setFrameShadow(QFrame.Raised)
        self.setLineWidth(6)
        self.setMidLineWidth(2)

    def sizeHint(self):
        return QtCore.QSize(6, 8)

hashmal_style = '''
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.inputSegmentation = None
        self.regexLabels = list()
        self.selectedRegexLabels = list()
        self.newRegex = r''
        self.newAnnotationKey = r''
        self.newAnnotationValue = r''
        self.ignoreCase = False
        self.unicodeDependent = True
        self.multiline = False
        self.dotAll = False
        self.infoBox = InfoBox(widget=self.controlArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute='infoBox',
            sendIfPreCallback=self.updateGUI,
        )
        self.advancedSettings = AdvancedSettings(
            widget=self.controlArea,
            master=self,
            callback=self.sendButton.settingsChanged,
        )

        # GUI...

        self.advancedSettings.draw()

        # Regexes box
        regexBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Regexes',
            orientation='vertical',
            addSpace=False,
        )
        regexBoxLine1 = gui.widgetBox(
            widget=regexBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        self.regexListbox = gui.listBox(
            widget=regexBoxLine1,
            master=self,
            value='selectedRegexLabels',
            labels='regexLabels',
            callback=self.updateRegexBoxButtons,
            tooltip=(u"The list of regexes that will be applied to each\n"
                     u"segment of the input segmentation.\n\n"
                     u"Regexes will be applied in the same order as they\n"
                     u"appear in the list.\n\n"
                     u"Column 1 shows the segmentation mode.\n"
                     u"Column 2 shows the regex pattern.\n"
                     u"Column 3 shows the associated annotation (if any).\n"
                     u"Column 4 shows the associated flags."),
        )
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)
        self.regexListbox.setFont(font)
        regexBoxCol2 = gui.widgetBox(
            widget=regexBoxLine1,
            orientation='vertical',
        )
        self.moveUpButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Move Up',
            callback=self.moveUp,
            tooltip=(u"Move the selected regex upward in the list."),
        )
        self.moveDownButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Move Down',
            callback=self.moveDown,
            tooltip=(u"Move the selected regex downward in the list."),
        )
        self.removeButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Remove',
            callback=self.remove,
            tooltip=(u"Remove the selected regex from the list."),
        )
        self.clearAllButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Clear All',
            callback=self.clearAll,
            tooltip=(u"Remove all regexes from the list."),
        )
        self.exportButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Export List',
            callback=self.exportList,
            tooltip=(u"Open a dialog for selecting a file where the\n"
                     u"regex list can be exported in JSON format."),
        )
        self.importButton = gui.button(
            widget=regexBoxCol2,
            master=self,
            label=u'Import List',
            callback=self.importList,
            tooltip=(u"Open a dialog for selecting a regex list to\n"
                     u"import (in JSON format). Regexes from this list\n"
                     u"will be added to the existing ones."),
        )
        regexBoxLine2 = gui.widgetBox(
            widget=regexBox,
            box=False,
            orientation='vertical',
        )
        # Add regex box
        addRegexBox = gui.widgetBox(
            widget=regexBoxLine2,
            box=True,
            orientation='vertical',
            addSpace=False,
        )
        self.modeCombo = gui.comboBox(
            widget=addRegexBox,
            master=self,
            value='mode',
            sendSelectedValue=True,
            items=[u'Tokenize', u'Split'],
            orientation='horizontal',
            label=u'Mode:',
            labelWidth=131,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Segmentation mode.\n\n"
                     u"'Tokenize': the regex specifies the form of\n"
                     u"segments themselves.\n\n"
                     u"'Split': the regex specifies the form of\n"
                     u"character sequences occuring between the segments."),
        )
        self.modeCombo.setMinimumWidth(120)
        gui.separator(
            widget=addRegexBox,
            height=3,
        )
        gui.lineEdit(
            widget=addRegexBox,
            master=self,
            value='newRegex',
            orientation='horizontal',
            label=u'Regex:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"The regex pattern that will be added to the list\n"
                     u"when button 'Add' is clicked. Commonly used\n"
                     u"segmentation units include:\n"
                     u"1) .\tcharacters (except newline)\n"
                     u'2) \w\t"letters" (alphanumeric chars and underscores)\n'
                     u'3) \w+\t"words" (sequences of "letters")\n'
                     u"4) .+\tlines\n"
                     u"and so on."),
        )
        gui.separator(
            widget=addRegexBox,
            height=3,
        )
        gui.lineEdit(
            widget=addRegexBox,
            master=self,
            value='newAnnotationKey',
            orientation='horizontal',
            label=u'Annotation key:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"This field lets you specify a custom annotation\n"
                     u"key for segments identified by the regex pattern\n"
                     u"about to be added to the list.\n\n"
                     u"Groups of characters captured by parentheses in\n"
                     u"the regex pattern may be inserted in the\n"
                     u"annotation value by using the form '&' (ampersand)\n"
                     u"immediately followed by a digit indicating the\n"
                     u"captured group number (e.g. '&1', '&2', etc.)."),
        )
        gui.separator(
            widget=addRegexBox,
            height=3,
        )
        gui.lineEdit(
            widget=addRegexBox,
            master=self,
            value='newAnnotationValue',
            orientation='horizontal',
            label=u'Annotation value:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"This field lets you specify a custom annotation\n"
                     u"value for segments identified by the regex pattern\n"
                     u"about to be added to the list.\n\n"
                     u"Groups of characters captured by parentheses in\n"
                     u"the regex pattern may be inserted in the\n"
                     u"annotation value by using the form '&' (ampersand)\n"
                     u"immediately followed by a digit indicating the\n"
                     u"captured group number (e.g. '&1', '&2', etc.)."),
        )
        gui.separator(
            widget=addRegexBox,
            height=3,
        )
        addRegexBoxLine1 = gui.widgetBox(
            widget=addRegexBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addRegexBoxLine1,
            master=self,
            value='ignoreCase',
            label=u'Ignore case (i)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Regex pattern is case-insensitive."),
        )
        gui.checkBox(
            widget=addRegexBoxLine1,
            master=self,
            value='unicodeDependent',
            label=u'Unicode dependent (u)',
            callback=self.updateGUI,
            tooltip=(u"Built-in character classes are Unicode-aware."),
        )
        addRegexBoxLine2 = gui.widgetBox(
            widget=addRegexBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addRegexBoxLine2,
            master=self,
            value='multiline',
            label=u'Multiline (m)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Anchors '^' and '$' match the beginning and\n"
                     u"end of each line (rather than just the beginning\n"
                     u"and end of each input segment)."),
        )
        gui.checkBox(
            widget=addRegexBoxLine2,
            master=self,
            value='dotAll',
            label=u'Dot matches all (s)',
            callback=self.updateGUI,
            tooltip=(u"Meta-character '.' matches any character (rather\n"
                     u"than any character but newline)."),
        )
        gui.separator(
            widget=addRegexBox,
            height=3,
        )
        self.addButton = gui.button(
            widget=addRegexBox,
            master=self,
            label=u'Add',
            callback=self.add,
            tooltip=(u"Add the regex pattern currently displayed in the\n"
                     u"'Regex' text field to the list."),
        )
        self.advancedSettings.advancedWidgets.append(regexBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # (Advanced) options box...
        optionsBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Options',
            orientation='vertical',
            addSpace=False,
        )
        optionsBoxLine2 = gui.widgetBox(
            widget=optionsBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumber',
            label=u'Auto-number with key:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotate output segments with increasing numeric\n"
                     u"indices."),
        )
        self.autoNumberKeyLineEdit = gui.lineEdit(
            widget=optionsBoxLine2,
            master=self,
            value='autoNumberKey',
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Annotation key for output segment auto-numbering."),
        )
        gui.separator(
            widget=optionsBox,
            height=3,
        )
        gui.checkBox(
            widget=optionsBox,
            master=self,
            value='importAnnotations',
            label=u'Import annotations',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Add to each output segment the annotation keys\n"
                     u"and values associated with the corresponding\n"
                     u"input segment."),
        )
        gui.separator(
            widget=optionsBox,
            height=3,
        )
        gui.checkBox(
            widget=optionsBox,
            master=self,
            value='mergeDuplicates',
            label=u'Fuse duplicates',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Fuse segments that have the same address.\n\n"
                     u"The annotation of merged segments will be fused\n"
                     u"as well. In the case where fused segments have\n"
                     u"distinct values for the same annotation key, only\n"
                     u"the value of the last one (in order of regex\n"
                     u"application) will be kept."),
        )
        gui.separator(
            widget=optionsBox,
            height=2,
        )
        self.advancedSettings.advancedWidgets.append(optionsBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # (Basic) Regex box...
        basicRegexBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Segment type',
            orientation='vertical',
            addSpace=False,
        )
        self.segmentTypeCombo = gui.comboBox(
            widget=basicRegexBox,
            master=self,
            value='segmentType',
            sendSelectedValue=True,
            items=[
                u'Segment into letters',
                u'Segment into words',
                u'Segment into lines',
                u'Use a regular expression',
            ],
            orientation='horizontal',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Specify the kind of units into which the data will\n"
                     u"be segmented (letters, words, lines, or custom\n"
                     u"units defined using a regular expression)."),
        )
        self.basicRegexFieldBox = gui.widgetBox(
            widget=basicRegexBox,
            box=False,
            orientation='vertical',
        )
        gui.separator(
            widget=self.basicRegexFieldBox,
            height=2,
        )
        gui.lineEdit(
            widget=self.basicRegexFieldBox,
            master=self,
            value='regex',
            orientation='horizontal',
            label=u'Regex:',
            labelWidth=60,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"A pattern that specifies the form of units into\n"
                     u"which the data will be segmented."),
        )
        gui.separator(
            widget=basicRegexBox,
            height=3,
        )
        self.advancedSettings.basicWidgets.append(basicRegexBox)
        self.advancedSettings.basicWidgetsAppendSeparator()

        gui.rubber(self.controlArea)

        # Send button...
        self.sendButton.draw()

        # Info box...
        self.infoBox.draw()

        self.sendButton.sendIf()
        self.adjustSizeWithTimer()
Пример #48
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

        loadFont = self.settings.value("pythonConsole/fontfamilytext",
                                       "Monospace")
        fontSize = self.settings.value("pythonConsole/fontsize", 10, type=int)

        font = QFont(loadFont)
        font.setFixedPitch(True)
        font.setPointSize(fontSize)
        font.setStyleHint(QFont.TypeWriter)
        font.setStretch(QFont.SemiCondensed)
        font.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        font.setBold(False)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(
            QColor(
                self.settings.value("pythonConsole/defaultFontColor",
                                    QColor(Qt.black))))
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentFontColor",
                                    QColor(Qt.gray))), 1)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/keywordFontColor",
                                    QColor(Qt.darkGreen))), 5)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/classFontColor",
                                    QColor(Qt.blue))), 8)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/methodFontColor",
                                    QColor(Qt.darkGray))), 9)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/decorFontColor",
                                    QColor(Qt.darkBlue))), 15)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/commentBlockFontColor",
                                    QColor(Qt.gray))), 12)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/singleQuoteFontColor",
                                    QColor(Qt.blue))), 4)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/doubleQuoteFontColor",
                                    QColor(Qt.blue))), 3)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleSingleQuoteFontColor",
                                    QColor(Qt.blue))), 6)
        self.lexer.setColor(
            QColor(
                self.settings.value("pythonConsole/tripleDoubleQuoteFontColor",
                                    QColor(Qt.blue))), 7)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)

        for style in range(0, 33):
            paperColor = QColor(
                self.settings.value("pythonConsole/paperBackgroundColor",
                                    QColor(Qt.white)))
            self.lexer.setPaper(paperColor, style)

        self.api = QsciAPIs(self.lexer)
        chekBoxAPI = self.settings.value("pythonConsole/preloadAPI",
                                         True,
                                         type=bool)
        chekBoxPreparedAPI = self.settings.value(
            "pythonConsole/usePreparedAPIFile", False, type=bool)
        if chekBoxAPI:
            pap = os.path.join(QgsApplication.pkgDataPath(), "python",
                               "qsci_apis", "pyqgis.pap")
            self.api.loadPrepared(pap)
        elif chekBoxPreparedAPI:
            self.api.loadPrepared(
                self.settings.value("pythonConsole/preparedAPIFile"))
        else:
            apiPath = self.settings.value("pythonConsole/userAPI", [])
            for i in range(0, len(apiPath)):
                self.api.load(unicode(apiPath[i]))
            self.api.prepare()
            self.lexer.setAPIs(self.api)

        self.setLexer(self.lexer)
Пример #49
0
from decimal import Decimal

from PyQt4.QtGui import QFont, QHBoxLayout, QFrame, QLineEdit
from PyQt4 import QtCore

import config

RawRole = QtCore.Qt.UserRole + 1
"""DataRole that is considered "raw" / "non-human-readable."

For example, the hex data of a human-readable script.
"""

monospace_font = QFont('Monospace')
monospace_font.setPointSize(9)
monospace_font.setStyleHint(QFont.TypeWriter)

script_file_filter = 'Coinscripts (*.coinscript);;Text files (*.txt);;All files (*.*)'


def HBox(*widgets):
    """Create an HBoxLayout with the widgets passed."""
    hbox = QHBoxLayout()
    for w in widgets:
        hbox.addWidget(w)
    return hbox


def floated_buttons(btns, left=False):
    """Returns a HBoxLayout with buttons floated to the right or left."""
    hbox = QHBoxLayout()
Пример #50
0
    def __init__(self, *args, **kwargs):
        """Initialize a Recode widget"""
        super().__init__(*args, **kwargs)

        # Other attributes...
        self.createdInputIndices = list()
        self.segmentation = None
        self.substLabels = list()
        self.selectedSubstLabels = list()
        self.newRegex = r''
        self.newReplString = r''
        self.ignoreCase = False
        self.unicodeDependent = True
        self.multiline = False
        self.dotAll = False
        self.infoBox = InfoBox(widget=self.controlArea)
        self.sendButton = SendButton(
            widget=self.controlArea,
            master=self,
            callback=self.sendData,
            infoBoxAttribute='infoBox',
            sendIfPreCallback=self.updateGUI,
        )
        self.advancedSettings = AdvancedSettings(
            widget=self.controlArea,
            master=self,
            callback=self.sendButton.settingsChanged,
        )

        # GUI...

        self.advancedSettings.draw()

        # Substitutions box
        substBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Substitutions',
            orientation='vertical',
            addSpace=False,
        )
        substBoxLine1 = gui.widgetBox(
            widget=substBox,
            box=False,
            orientation='horizontal',
            addSpace=True,
        )
        self.substListbox = gui.listBox(
            widget=substBoxLine1,
            master=self,
            value='selectedSubstLabels',
            labels='substLabels',
            callback=self.updateSubstBoxButtons,
            tooltip=(u"The list of substitutions that will be applied to\n"
                     u"each segment of the input segmentation.\n\n"
                     u"Substitutions will be applied in the same order\n"
                     u"as they appear in the list.\n\n"
                     u"Column 1 shows the regex pattern.\n"
                     u"Column 2 shows the associated replacement string\n"
                     u"(if not empty).\n"
                     u"Column 3 shows the associated flags."),
        )
        font = QFont()
        font.setFamily('Courier')
        font.setStyleHint(QFont.Courier)
        font.setPixelSize(12)
        self.substListbox.setFont(font)
        substBoxCol2 = gui.widgetBox(
            widget=substBoxLine1,
            orientation='vertical',
        )
        self.moveUpButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Move Up',
            callback=self.moveUp,
            tooltip=(u"Move the selected substitution upward in the list."),
        )
        self.moveDownButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Move Down',
            callback=self.moveDown,
            tooltip=(u"Move the selected substitution downward in the list."),
        )
        self.removeButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Remove',
            callback=self.remove,
            tooltip=(u"Remove the selected substitution from the list."),
        )
        self.clearAllButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Clear All',
            callback=self.clearAll,
            tooltip=(u"Remove all substitutions from the list."),
        )
        self.exportButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Export List',
            callback=self.exportList,
            tooltip=(u"Open a dialog for selecting a file where the\n"
                     u"substitution list can be exported in JSON format."),
        )
        self.importButton = gui.button(
            widget=substBoxCol2,
            master=self,
            label=u'Import List',
            callback=self.importList,
            tooltip=(u"Open a dialog for selecting a substitution list\n"
                     u"to import (in JSON format). Substitutions from\n"
                     u"this list will be added to the existing ones."),
        )
        substBoxLine2 = gui.widgetBox(
            widget=substBox,
            box=False,
            orientation='vertical',
        )
        # Add regex box
        addSubstBox = gui.widgetBox(
            widget=substBoxLine2,
            box=True,
            orientation='vertical',
        )
        gui.lineEdit(
            widget=addSubstBox,
            master=self,
            value='newRegex',
            orientation='horizontal',
            label=u'Regex:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"The regex pattern that will be added to the list\n"
                     u"when button 'Add' is clicked."),
        )
        gui.separator(widget=addSubstBox, height=3)
        gui.lineEdit(
            widget=addSubstBox,
            master=self,
            value='newReplString',
            orientation='horizontal',
            label=u'Replacement string:',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"The (possibly empty) replacement string that will\n"
                     u"be added to the list when button 'Add' is clicked.\n\n"
                     u"Groups of characters captured by parentheses in\n"
                     u"the regex pattern may be inserted in the\n"
                     u"replacement string by using the form '&'\n"
                     u"(ampersand) immediately followed by a digit\n"
                     u" indicating the captured group number (e.g. '&1',\n"
                     u"'&2', etc.)."),
        )
        gui.separator(widget=addSubstBox, height=3)
        addSubstBoxLine3 = gui.widgetBox(
            widget=addSubstBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addSubstBoxLine3,
            master=self,
            value='ignoreCase',
            label=u'Ignore case (i)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Regex pattern is case-insensitive."),
        )
        gui.checkBox(
            widget=addSubstBoxLine3,
            master=self,
            value='unicodeDependent',
            label=u'Unicode dependent (u)',
            callback=self.updateGUI,
            tooltip=(u"Built-in character classes are Unicode-aware."),
        )
        addSubstBoxLine4 = gui.widgetBox(
            widget=addSubstBox,
            box=False,
            orientation='horizontal',
        )
        gui.checkBox(
            widget=addSubstBoxLine4,
            master=self,
            value='multiline',
            label=u'Multiline (m)',
            labelWidth=131,
            callback=self.updateGUI,
            tooltip=(u"Anchors '^' and '$' match the beginning and\n"
                     u"end of each line (rather than just the beginning\n"
                     u"and end of each input segment)."),
        )
        gui.checkBox(
            widget=addSubstBoxLine4,
            master=self,
            value='dotAll',
            label=u'Dot matches all (s)',
            callback=self.updateGUI,
            tooltip=(u"Meta-character '.' matches any character (rather\n"
                     u"than any character but newline)."),
        )
        gui.separator(widget=addSubstBox, height=3)
        self.addButton = gui.button(
            widget=addSubstBox,
            master=self,
            label=u'Add',
            callback=self.add,
            tooltip=(u"Add the current substitution to the list."),
        )
        self.advancedSettings.advancedWidgets.append(substBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # (Advanced) Options box...
        optionsBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Options',
            orientation='vertical',
            addSpace=False,
        )
        gui.checkBox(
            widget=optionsBox,
            master=self,
            value='copyAnnotations',
            label=u'Copy annotations',
            callback=self.sendButton.settingsChanged,
            tooltip=(u"Copy all annotations from input to output segments."),
        )
        gui.separator(widget=optionsBox, height=2)
        self.advancedSettings.advancedWidgets.append(optionsBox)
        self.advancedSettings.advancedWidgetsAppendSeparator()

        # (Basic) Substitution box...
        basicSubstBox = gui.widgetBox(
            widget=self.controlArea,
            box=u'Substitution',
            orientation='vertical',
            addSpace=False,
        )
        gui.lineEdit(
            widget=basicSubstBox,
            master=self,
            value='regex',
            orientation='horizontal',
            label=u'Regex:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"The regex that will be applied to each segment in\n"
                     u"the input segmentation."),
        )
        gui.separator(widget=basicSubstBox, height=3)
        gui.lineEdit(
            widget=basicSubstBox,
            master=self,
            value='replString',
            orientation='horizontal',
            label=u'Replacement string:',
            labelWidth=180,
            callback=self.sendButton.settingsChanged,
            tooltip=(u"The string that will be used for replacing each\n"
                     u"match of the above regex in the input segmentation."),
        )
        gui.separator(widget=basicSubstBox, height=3)
        self.advancedSettings.basicWidgets.append(basicSubstBox)
        self.advancedSettings.basicWidgetsAppendSeparator()

        gui.rubber(self.controlArea)

        # Send button...
        self.sendButton.draw()

        # Info box...
        self.infoBox.draw()

        self.sendButton.sendIf()
        self.adjustSizeWithTimer()
Пример #51
0
class ScriptEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)

        self.lexer = None
        self.api = None
        self.lexerType = -1

        self.setCommonOptions()
        self.initShortcuts()

    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(20)
        self.setFont(font)
        self.setMarginsFont(font)

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)

        self.setFonts(10)

    def setFonts(self, size):

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', size))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl
                           + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(QKeySequence(Qt.CTRL
                                                           + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def setLexerType(self, lexerType):
        self.lexerType = lexerType
        self.initLexer()

    def initLexer(self):
        if self.lexerType == self.LEXER_PYTHON:
            self.lexer = QsciLexerPython()

            colorDefault = QColor('#2e3436')
            colorComment = QColor('#c00')
            colorCommentBlock = QColor('#3465a4')
            colorNumber = QColor('#4e9a06')
            colorType = QColor('#4e9a06')
            colorKeyword = QColor('#204a87')
            colorString = QColor('#ce5c00')

            self.lexer.setDefaultFont(self.defaultFont)
            self.lexer.setDefaultColor(colorDefault)

            self.lexer.setColor(colorComment, 1)
            self.lexer.setColor(colorNumber, 2)
            self.lexer.setColor(colorString, 3)
            self.lexer.setColor(colorString, 4)
            self.lexer.setColor(colorKeyword, 5)
            self.lexer.setColor(colorString, 6)
            self.lexer.setColor(colorString, 7)
            self.lexer.setColor(colorType, 8)
            self.lexer.setColor(colorCommentBlock, 12)
            self.lexer.setColor(colorString, 15)

            self.lexer.setFont(self.italicFont, 1)
            self.lexer.setFont(self.boldFont, 5)
            self.lexer.setFont(self.boldFont, 8)
            self.lexer.setFont(self.italicFont, 12)

            self.api = QsciAPIs(self.lexer)

            settings = QSettings()
            useDefaultAPI = bool(settings.value('pythonConsole/preloadAPI',
                                                True))
            if useDefaultAPI:
                # Load QGIS API shipped with Python console
                self.api.loadPrepared(
                    os.path.join(QgsApplication.pkgDataPath(),
                                 'python', 'qsci_apis', 'pyqgis.pap'))
            else:
                # Load user-defined API files
                apiPaths = settings.value('pythonConsole/userAPI', [])
                for path in apiPaths:
                    self.api.load(path)
                self.api.prepare()
                self.lexer.setAPIs(self.api)
        elif self.lexerType == self.LEXER_R:
            # R lexer
            self.lexer = LexerR()

        self.setLexer(self.lexer)
Пример #52
0
    def drawContents(self, painter):
        """ @type painter: QPainter """
        w = self.width()
        h = self.height()

        margin = 10

        background = QColor(210, 211, 215)
        text_color = QColor(0, 0, 0)
        foreground = QColor(255, 255, 255)

        painter.setBrush(background)
        painter.fillRect(0, 0, w, h, background)


        pen = QPen()
        pen.setWidth(2)
        pen.setColor(foreground)


        painter.setPen(pen)
        painter.drawRect(0, 0, w - 1, h - 1)

        image_width = self.splash_image.width()
        image_height = self.splash_image.height()
        aspect = float(image_width) / float(image_height)

        scaled_height = h - 2 * margin
        scaled_width = scaled_height * aspect

        painter.drawRect(margin, margin, scaled_width, scaled_height)
        painter.drawPixmap(margin, margin, scaled_width, scaled_height, self.splash_image)

        text_x = scaled_width + 2 * margin
        top_offset = margin
        text_area_width = w - scaled_width - 2 * margin

        painter.setPen(text_color)


        text_size = 150
        font = QFont("Serif")
        font.setStyleHint(QFont.Serif)
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, margin + top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert)

        top_offset += text_size + 2 * margin
        text_size = 25
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert_title)

        top_offset += text_size + 4 * margin
        text_size = 20
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.version)

        top_offset += text_size + margin
        text_size = 15
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.timestamp)


        text_size = 12
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, h - text_size - margin - 5, text_area_width, text_size + 5, Qt.AlignHCenter | Qt.AlignCenter, self.copyright)
Пример #53
0
    def setupUi(self):
        self.setWindowTitle('Edit filter')
        #self.resize(400, 300)

        self.signatureLabel = QLabel(self)
        self.signatureLabel.setText('def filter(block):')

        font = QFont('Some font that does not exist')
        font.setStyleHint(font.TypeWriter, font.PreferDefault)
        self.editor = CodeEditor(self)
        self.editor.setup_editor(linenumbers=False,
                                 language='py',
                                 scrollflagarea=False,
                                 codecompletion_enter=True,
                                 font=font,
                                 highlight_current_line=False,
                                 occurence_highlighting=False)
        self.editor.setCursor(Qt.IBeamCursor)
        self.editor.horizontalScrollBar().setCursor(Qt.ArrowCursor)
        self.editor.verticalScrollBar().setCursor(Qt.ArrowCursor)
        self.editor.set_text('return True')

        self.onExceptionCheckBox = QCheckBox(self)
        self.onExceptionCheckBox.setText('True on exception')
        self.onExceptionCheckBox.setToolTip('Determines if the filter will '
                                            'admit items if there is an '
                                            'exception during its execution')

        self.combinedCheckBox = QCheckBox(self)
        self.combinedCheckBox.setText('Combined filter')
        self.combinedCheckBox.setToolTip('Determines if the filter operates '
                                         'on single items (return True or '
                                         'False) or lists of items (return a '
                                         'list of items to be admitted)')

        self.filterTypeComboBox = QComboBox(self)
        self.filterTypeComboBox.addItem('Block')
        self.filterTypeComboBox.addItem('Segment')
        self.filterTypeComboBox.addItem('Recording Channel Group')
        self.filterTypeComboBox.addItem('Recording Channel')
        self.filterTypeComboBox.addItem('Unit')

        self.filterGroupComboBox = QComboBox(self)

        self.nameLineEdit = QLineEdit()

        self.dialogButtonBox = QDialogButtonBox(self)
        self.dialogButtonBox.setAutoFillBackground(False)
        self.dialogButtonBox.setOrientation(Qt.Horizontal)
        self.dialogButtonBox.setStandardButtons(QDialogButtonBox.Cancel
                                                | QDialogButtonBox.Ok)
        self.dialogButtonBox.setCenterButtons(True)

        gridLayout = QGridLayout(self)
        gridLayout.addWidget(self.signatureLabel, 0, 0, 1, 4)
        gridLayout.addWidget(self.editor, 1, 0, 1, 4)
        gridLayout.addWidget(self.onExceptionCheckBox, 2, 2, 1, 1)
        gridLayout.addWidget(self.combinedCheckBox, 2, 3, 1, 1)
        gridLayout.addWidget(QLabel('Type:', self), 2, 0)
        gridLayout.addWidget(self.filterTypeComboBox, 2, 1)
        gridLayout.addWidget(QLabel('Group:', self), 3, 0)
        gridLayout.addWidget(self.filterGroupComboBox, 3, 1, 1, 3)
        gridLayout.addWidget(QLabel('Name:', self), 4, 0)
        gridLayout.addWidget(self.nameLineEdit, 4, 1, 1, 3)
        gridLayout.addWidget(self.dialogButtonBox, 5, 0, 1, 4)

        self.connect(self.dialogButtonBox, SIGNAL('accepted()'), self.accept)
        self.connect(self.dialogButtonBox, SIGNAL('rejected()'), self.reject)
        self.combinedCheckBox.stateChanged.connect(self.combined_state_changed)
        self.connect(self.filterTypeComboBox,
                     SIGNAL('currentIndexChanged(int)'),
                     self.on_filterTypeComboBox_currentIndexChanged)
Пример #54
0
 def readSettings(self):
     font = textformats.formatData('editor').font
     self.diff.setFont(font)
     diffFont = QFont("Monospace")
     diffFont.setStyleHint(QFont.TypeWriter)
     self.uni_diff.setFont(diffFont)
Пример #55
0
class SqlEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

    def __init__(self, parent=None):
        QsciScintilla.__init__(self, parent)

        self.mylexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

    def setCommonOptions(self):
        # Enable non-ASCII characters
        self.setUtf8(True)

        # Default font
        font = QFont()
        font.setFamily('Courier')
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

        self.setWrapMode(QsciScintilla.WrapWord)
        self.setWrapVisualFlags(QsciScintilla.WrapFlagByText,
                                QsciScintilla.WrapFlagNone, 4)

        self.setSelectionForegroundColor(QColor('#2e3436'))
        self.setSelectionBackgroundColor(QColor('#babdb6'))

        # Show line numbers
        self.setMarginWidth(1, '000')
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor('#2e3436'))
        self.setMarginsBackgroundColor(QColor('#babdb6'))

        # Highlight current line
        self.setCaretLineVisible(True)
        self.setCaretLineBackgroundColor(QColor('#d3d7cf'))

        # Folding
        self.setFolding(QsciScintilla.BoxedTreeFoldStyle)
        self.setFoldMarginColors(QColor('#d3d7cf'), QColor('#d3d7cf'))

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor('#eeeeec'))

        # Indentation
        self.setAutoIndent(True)
        self.setIndentationsUseTabs(False)
        self.setIndentationWidth(4)
        self.setTabIndents(True)
        self.setBackspaceUnindents(True)
        self.setTabWidth(4)

        # Autocomletion
        self.setAutoCompletionThreshold(2)
        self.setAutoCompletionSource(QsciScintilla.AcsAPIs)
        self.setAutoCompletionCaseSensitivity(False)

        # Load font from Python console settings
        settings = QSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', 10))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setStretch(QFont.SemiCondensed)
        self.defaultFont.setLetterSpacing(QFont.PercentageSpacing, 87.0)
        self.defaultFont.setBold(False)

        self.boldFont = QFont(self.defaultFont)
        self.boldFont.setBold(True)

        self.italicFont = QFont(self.defaultFont)
        self.italicFont.setItalic(True)

        self.setFont(self.defaultFont)
        self.setMarginsFont(self.defaultFont)

        self.initLexer()

    def initShortcuts(self):
        (ctrl, shift) = (self.SCMOD_CTRL << 16, self.SCMOD_SHIFT << 16)

        # Disable some shortcuts
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('D') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('L') + ctrl)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY,
                           ord('L') + ctrl + shift)
        self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord('T') + ctrl)

        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Z") + ctrl)
        #self.SendScintilla(QsciScintilla.SCI_CLEARCMDKEY, ord("Y") + ctrl)

        # Use Ctrl+Space for autocompletion
        self.shortcutAutocomplete = QShortcut(
            QKeySequence(Qt.CTRL + Qt.Key_Space), self)
        self.shortcutAutocomplete.setContext(Qt.WidgetShortcut)
        self.shortcutAutocomplete.activated.connect(self.autoComplete)

    def autoComplete(self):
        self.autoCompleteFromAll()

    def initLexer(self):
        self.mylexer = QsciLexerSQL()

        colorDefault = QColor('#2e3436')
        colorComment = QColor('#c00')
        colorCommentBlock = QColor('#3465a4')
        colorNumber = QColor('#4e9a06')
        colorType = QColor('#4e9a06')
        colorKeyword = QColor('#204a87')
        colorString = QColor('#ce5c00')

        self.mylexer.setDefaultFont(self.defaultFont)
        self.mylexer.setDefaultColor(colorDefault)

        self.mylexer.setColor(colorComment, 1)
        self.mylexer.setColor(colorNumber, 2)
        self.mylexer.setColor(colorString, 3)
        self.mylexer.setColor(colorString, 4)
        self.mylexer.setColor(colorKeyword, 5)
        self.mylexer.setColor(colorString, 6)
        self.mylexer.setColor(colorString, 7)
        self.mylexer.setColor(colorType, 8)
        self.mylexer.setColor(colorCommentBlock, 12)
        self.mylexer.setColor(colorString, 15)

        self.mylexer.setFont(self.italicFont, 1)
        self.mylexer.setFont(self.boldFont, 5)
        self.mylexer.setFont(self.boldFont, 8)
        self.mylexer.setFont(self.italicFont, 12)

        self.setLexer(self.mylexer)

    def lexer(self):
        return self.mylexer
Пример #56
0
class ScaleBarItem(QGraphicsItem):
    def __init__(self, canvas, parent=None):
        super(ScaleBarItem, self).__init__(parent)
        self.canvas = canvas
        self.realsize = 100
        black = QColor(Qt.black)
        black.setAlpha(150)
        white = QColor(Qt.white)
        white.setAlpha(150)
        blackpen = QPen(black, 4)
        whitepen = QPen(white, 8)
        self.pens = [whitepen, blackpen]
        self.whitepen = QPen(white, 1)
        self.blackbrush = QBrush(black)
        self.ticksize = 10
        self.fontsize = 15
        self.font = QFont()
        self.font.setPointSize(self.fontsize)
        self.font.setStyleHint(QFont.Times, QFont.PreferAntialias)
        self.font.setBold(True)
        self.metrics = QFontMetrics(self.font)

    def boundingRect(self):
        try:
            width, realsize, label, fontsize = self._calc_size()
            halfheight = (self.ticksize + fontsize[1]) / 2
            halfwidth = (width + fontsize[0]) / 2
            return QRectF(-halfwidth, -halfheight, halfwidth, halfheight)
        except ZeroDivisionError:
            return QRectF()

    def paint(self, painter, styleoptions, widget=None):
        try:
            width, realsize, label, fontsize = self._calc_size()
        except ZeroDivisionError:
            return

        mapunits = self.canvas.mapUnits()

        # painter.drawRect(self.boundingRect())
        array = QPolygon()
        canvasheight = self.canvas.height()
        canvaswidth = self.canvas.width()
        margin = 20
        originy = 0
        originx = 0

        self.setPos(margin, canvasheight - margin)

        x1, y1 = originx, originy
        x2, y2 = originx, originy + self.ticksize
        x3, y3 = originx + width, originy + self.ticksize
        midx, midy = originx + width / 2, originy + self.ticksize / 2
        x4, y4 = originx + width, originy

        for pen in self.pens:
            painter.setPen(pen)
            # Drwa the scale bar
            painter.drawLine(x1, y1, x2, y2)
            painter.drawLine(x2, y2, x3, y3)
            painter.drawLine(x3, y3, x4, y4)
            painter.drawLine(midx, midy, midx, y1)

        # Draw the text
        fontwidth = self.metrics.width("0")
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        path = QPainterPath()
        point = QPointF(x1 - fontwidth, y1 - fontheight)
        path.addText(point, self.font, "0")
        painter.setPen(self.whitepen)
        painter.setBrush(self.blackbrush)
        painter.setRenderHints(QPainter.Antialiasing)
        painter.setFont(self.font)
        painter.drawPath(path)

        fontwidth = self.metrics.width(label)
        fontheight = self.metrics.height()
        fontheight /= 2
        fontwidth /= 2
        point = QPointF(x4 - fontwidth, y4 - fontheight)
        path.addText(point, self.font, label)
        painter.drawPath(path)

    def _calc_size(self):
        realSize = self.realsize
        canvaswidth = self.canvas.width()
        mapunitsperpixel = abs(self.canvas.mapUnitsPerPixel())
        mapunits = self.canvas.mapUnits()
        prefered_units = roam.config.settings.get("prefer_units", "meters")
        newunits = QGis.fromLiteral(prefered_units, QGis.Meters)
        mapunitsperpixel *= QGis.fromUnitToUnitFactor(mapunits, newunits)
        mapunits = newunits

        # Convert the real distance into pixels
        barwidth = realSize / mapunitsperpixel

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

        # Round
        powerof10 = math.floor(math.log10(realSize))
        scaler = math.pow(10.0, powerof10)
        realSize = round(realSize / scaler) * scaler
        barwidth = realSize / mapunitsperpixel
        label, realSize = self._label_size(mapunits, realSize)
        metrics = QFontMetrics(self.font)
        fontwidth = metrics.width(label)
        fontheight = metrics.height()

        sizelabel = QLocale.system().toString(realSize)
        sizelabel = "{} {}".format(sizelabel, label)

        barwidth = self._adjust_bar_size(barwidth, mapunits)
        barwidth = barwidth + fontwidth

        return barwidth, realSize, sizelabel, (fontwidth, fontheight)

    def _label_size(self, unit, currentsize):
        if unit == QGis.Meters:
            if currentsize > 1000:
                return "km", currentsize / 1000
            elif currentsize < 0.01:
                return "mm", currentsize * 1000
            elif currentsize < 0.1:
                return "cm", currentsize * 100
            else:
                return "m", currentsize
        elif unit == QGis.Feet:
            print currentsize
            if currentsize > 5280.0:
                return "miles", currentsize / 5000
            elif currentsize == 5280.0:
                return "mile", currentsize / 5000
            elif currentsize < 1:
                return "inches", currentsize * 10
            elif currentsize == 1.0:
                return "foot", currentsize
            else:
                return "feet", currentsize
        elif unit == QGis.Degrees:
            if currentsize == 1.0:
                return "degree", currentsize
            else:
                return "degrees", currentsize
        else:
            return str(unit), currentsize

    def _adjust_bar_size(self, barsize, unit):
        if unit == QGis.Feet:
            if barsize > 5280.0 or barsize == 5280.0:
                return (barsize * 5290) / 5000
            elif barsize < 1:
                return (barsize * 10) / 12

        return barsize
Пример #57
0
class OpenedFileView(QObject):
    MARGIN_NUMBERS, MARGIN_MARKER_BP, MARGIN_MARKER_TP, MARGIN_MARKER_EXEC, \
    MARGIN_MARKER_EXEC_SIGNAL, MARGIN_MARKER_STACK = range(6)

    def __init__(self, distributedObjects, filename):
        QObject.__init__(self)
        filename = str(filename)
        self.distributedObjects = distributedObjects
        self.debugController = self.distributedObjects.debugController
        self.breakpointController = self.distributedObjects.breakpointController
        self.tracepointController = self.distributedObjects.tracepointController
        self.signalProxy = self.distributedObjects.signalProxy
        self.filename = filename
        self.lastContexMenuLine = 0
        self.markerBp = QPixmap(":/markers/bp.png")
        self.markerTp = QPixmap(":/markers/tp.png")
        self.markerExec = QPixmap(":/markers/exec_pos.png")
        self.markerExecSignal = QPixmap(":/markers/exec_pos_signal.png")
        self.shown = False

        self.FileWatcher = QFileSystemWatcher()
        self.FileWatcher.addPath(self.filename)
        self.FileWatcher.fileChanged.connect(self.fileChanged)

        self.tab = QtGui.QWidget()
        self.gridLayout = QtGui.QGridLayout(self.tab)
        self.gridLayout.setMargin(0)
        self.edit = Qsci.QsciScintilla(self.tab)
        self.font = QFont("DejaVu Sans Mono", 10)
        self.font.setStyleHint(QFont.TypeWriter)
        self.lexer = Qsci.QsciLexerCPP()
        self.lexer.setFont(self.font)

        self.edit.setToolTip("")
        self.edit.setWhatsThis("")
        self.edit.setTabWidth(4)
        self.edit.setLexer(self.lexer)
        self.edit.setWhitespaceVisibility(Qsci.QsciScintilla.WsVisible)
        self.edit.setIndentationGuides(True)
        self.edit.setMarginLineNumbers(self.MARGIN_NUMBERS, True)
        # set sensitivity
        self.edit.setMarginSensitivity(self.MARGIN_NUMBERS, True)
        self.edit.setMarginSensitivity(self.MARGIN_MARKER_BP, True)
        self.edit.setMarginSensitivity(self.MARGIN_MARKER_TP, True)
        # define symbol
        self.edit.markerDefine(self.markerBp, self.MARGIN_MARKER_BP)
        self.edit.markerDefine(self.markerTp, self.MARGIN_MARKER_TP)
        self.edit.markerDefine(self.markerExec, self.MARGIN_MARKER_EXEC)
        self.edit.markerDefine(self.markerExecSignal, self.MARGIN_MARKER_EXEC_SIGNAL)
        self.edit.markerDefine(Qsci.QsciScintilla.Background, self.MARGIN_MARKER_STACK)
        # define width and mask to show margin
        self.edit.setMarginWidth(self.MARGIN_MARKER_BP, 10)
        self.edit.setMarginMarkerMask(self.MARGIN_MARKER_BP, 1 << self.MARGIN_MARKER_BP)
        self.edit.setMarginWidth(self.MARGIN_MARKER_TP, 10)
        self.edit.setMarginMarkerMask(self.MARGIN_MARKER_TP, 1 << self.MARGIN_MARKER_TP)
        self.edit.setMarginWidth(self.MARGIN_MARKER_EXEC, 10)
        self.edit.setMarginMarkerMask(self.MARGIN_MARKER_EXEC,
                1 << self.MARGIN_MARKER_EXEC |
                1 << self.MARGIN_MARKER_EXEC_SIGNAL)
        self.edit.setMarginWidth(self.MARGIN_MARKER_STACK, 0)
        self.edit.setMarkerBackgroundColor(QColor(Qt.yellow), self.MARGIN_MARKER_STACK)
        self.edit.setMarginMarkerMask(self.MARGIN_MARKER_STACK, 1 << self.MARGIN_MARKER_STACK)
        # ...
        self.edit.setReadOnly(False)
        self.gridLayout.addWidget(self.edit, 0, 0, 1, 1)

        self.breakpoints = []

        if not (QtCore.QFile.exists(filename)):
            logging.error("could not open file", filename)
        self.file_ = QtCore.QFile(filename)
        self.file_.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
        self.edit.read(self.file_)
        self.file_.close()

        self.changed = False
        self.edit.modificationChanged.connect(self.__setFileModified)

        self.setMarginWidthByLineNumbers()
        self.edit.SendScintilla(Qsci.QsciScintilla.SCI_SETMOUSEDWELLTIME, 500)

        # override scintillas context menu with our own
        self.edit.SendScintilla(Qsci.QsciScintilla.SCI_USEPOPUP, 0)
        self.edit.setContextMenuPolicy(Qt.CustomContextMenu)
        self.edit.customContextMenuRequested.connect(self.showContextMenu)

        self.edit.marginClicked.connect(self.marginClicked)
        self.edit.SCN_DOUBLECLICK.connect(self.editDoubleClicked)
        self.edit.SCN_DWELLSTART.connect(self.dwellStart)
        self.edit.SCN_DWELLEND.connect(self.dwellEnd)

        # initially, read all breakpoints and tracepoints from the model
        self.getBreakpointsFromModel()
        self.getTracepointsFromModel()

        _model = self.breakpointController.model()
        _model.rowsInserted.connect(self.getBreakpointsFromModel)
        _model.rowsRemoved.connect(self.getBreakpointsFromModel)
        _model = self.tracepointController.model()
        _model.rowsInserted.connect(self.getTracepointsFromModel)
        _model.rowsRemoved.connect(self.getTracepointsFromModel)

        act = self.distributedObjects.actions
        act.ToggleTrace.triggered.connect(self.toggleTracepoint)

    def fileChanged(self):
        logging.warning("Source file %s modified. Recompile executable for \
                correct debugging.", self.filename)

    def saveFile(self):
        ''' Save source file '''
        if (QtCore.QFile.exists(self.filename)):
            f = open(self.filename, 'w')
            f.write(self.edit.text())
            f.close()
            self.file_.open(QtCore.QIODevice.ReadOnly | QtCore.QIODevice.Text)
            self.edit.read(self.file_)
            self.file_.close()
            self.__setFileModified(False)

    def __setFileModified(self, modified):
        ''' Method called whenever current file is marked as modified '''
        self.distributedObjects.signalProxy.emitFileModified(self.filename, modified)

    def dwellStart(self, pos, x, y):
        if self.edit.frameGeometry().contains(x, y):
            name = self.getWordOrSelectionFromPosition(pos)
            val = self.debugController.evaluateExpression(name.strip())
            if val != None:
                name = cgi.escape(name)
                val = cgi.escape(val)
                QToolTip.showText(self.edit.mapToGlobal(QtCore.QPoint(x, y)),
                        "<b>" + name + "</b> = " + val, self.edit,
                        QtCore.QRect())

    def dwellEnd(self, position, x, y):
        QToolTip.showText(self.edit.mapToGlobal(QtCore.QPoint(x, y)), "",
                self.edit, QtCore.QRect())

    def showContextMenu(self, point):
        scipos = self.edit.SendScintilla(
                Qsci.QsciScintilla.SCI_POSITIONFROMPOINT, point.x(), point.y())
        point = self.edit.mapToGlobal(point)
        exp = self.getWordOrSelectionFromPosition(scipos)
        # self.edit.lineIndexFromPosition(..) returns tupel. first of tupel is line
        self.lastContexMenuLine = int(self.edit.lineIndexFromPosition(scipos)[0])

        listOfTracepoints = self.tracepointController.getTracepointsFromModel()

        self.subPopupMenu = QtGui.QMenu(self.edit)
        self.subPopupMenu.setTitle("Add variable " + exp + " to...")

        for tp in listOfTracepoints:
            # dynamic actions, not in actiony.py Action class
            self.subPopupMenu.addAction(self.distributedObjects.actions.getAddToTracepointAction(exp, tp.name, tp.addVar))

        self.popupMenu = QtGui.QMenu(self.edit)
        # add watch and toggle breakpoint to menu
        self.popupMenu.addAction(self.distributedObjects.actions.getAddToWatchAction(exp, self.signalProxy.addWatch))
        self.popupMenu.addAction(self.distributedObjects.actions.ToggleTrace)
        self.popupMenu.addAction(self.distributedObjects.actions.getAddToDatagraphAction(exp, self.distributedObjects.datagraphController.addWatch))
        # add separator and self.subPopupMenu
        self.popupMenu.addSeparator()
        self.popupMenu.addMenu(self.subPopupMenu)
        self.popupMenu.popup(point)

    def isPositionInsideSelection(self, position):
        lf, cf, lt, ct = self.edit.getSelection()
        pl, pc = self.edit.lineIndexFromPosition(position)

        if lf < pl and pl < lt:
            return True
        elif lf == pl and pl < lt:
            return True if cf <= pc else False
        elif lf < pl and pl == lt:
            return True if pc <= ct else False
        elif lf == pl and pl == lt:
            return True if (cf <= pc and pc <= ct) else False
        else:
            return False

    def getWordOrSelectionFromPosition(self, position):
        if self.isPositionInsideSelection(position):
            return str(self.edit.selectedText())
        else:
            return self.getWordFromPosition(position)

    def getWordFromPosition(self, position):
        line, col = self.edit.lineIndexFromPosition(position)
        s = str(self.edit.text(line))
        start = col
        end = col

        r = re.compile(r'[\w\d_]')
        while start >= 0:
            if not r.match(s[start]):
                break
            start -= 1
        start += 1
        while end < len(s):
            if not r.match(s[end]):
                break
            end += 1
        return s[start:end]

    def editDoubleClicked(self, position, line, modifiers):
        w = self.getWordFromPosition(position)
        self.signalProxy.addWatch(str(w))

    def showExecutionPosition(self, line):
        self.edit.markerAdd(line, self.MARGIN_MARKER_EXEC)
        self.showLine(line)

    def showSignalPosition(self, line):
        self.edit.markerAdd(line, self.MARGIN_MARKER_EXEC_SIGNAL)
        self.showLine(line)

    def showLine(self, line):
        self.edit.setCursorPosition(line, 1)
        self.edit.ensureLineVisible(line)

    def clearExecutionPositionMarkers(self):
        self.edit.markerDeleteAll(self.MARGIN_MARKER_EXEC)

    def setMarginWidthByLineNumbers(self):
        self.edit.setMarginWidth(0, ceil(log(self.edit.lines(), 10)) * 10 + 5)

    def marginClicked(self, margin, line, state):
        # if breakpoint should be toggled
        if margin == self.MARGIN_NUMBERS or margin == self.MARGIN_MARKER_BP:
            self.toggleBreakpointWithLine(line)
        elif margin == self.MARGIN_MARKER_TP:
            self.toggleTracepointWithLine(line)

    def toggleBreakpointWithLine(self, line):
        self.breakpointController.toggleBreakpoint(self.filename, line + 1)

    def toggleTracepointWithLine(self, line):
        self.tracepointController.toggleTracepoint(self.filename, line + 1)

    def toggleTracepoint(self):
        self.toggleTracepointWithLine(self.lastContexMenuLine)

    def getBreakpointsFromModel(self, parent=None, start=None, end=None):
        """Get breakpoints from model."""
        # TODO: don't reload all breakpoints, just the one referenced by parent/start/end
        self.edit.markerDeleteAll(self.MARGIN_MARKER_BP)
        for bp in self.breakpointController.getBreakpointsFromModel():
            if bp.fullname == self.filename:
                self.edit.markerAdd(int(bp.line) - 1, self.MARGIN_MARKER_BP)

    def getTracepointsFromModel(self):
        """Get tracepoints from model."""
        self.edit.markerDeleteAll(self.MARGIN_MARKER_TP)
        for tp in self.tracepointController.getTracepointsFromModel():
            if tp.fullname == self.filename:
                self.edit.markerAdd(int(tp.line) - 1, self.MARGIN_MARKER_TP)
Пример #58
0
    def drawContents(self, painter):
        """ @type painter: QPainter """
        w = self.width()
        h = self.height()

        margin = 10

        background = QColor(210, 211, 215)
        text_color = QColor(0, 0, 0)
        foreground = QColor(255, 255, 255)

        painter.setBrush(background)
        painter.fillRect(0, 0, w, h, background)


        pen = QPen()
        pen.setWidth(2)
        pen.setColor(foreground)


        painter.setPen(pen)
        painter.drawRect(0, 0, w - 1, h - 1)

        image_width = self.splash_image.width()
        image_height = self.splash_image.height()
        aspect = float(image_width) / float(image_height)

        scaled_height = h - 2 * margin
        scaled_width = scaled_height * aspect

        painter.drawRect(margin, margin, scaled_width, scaled_height)
        painter.drawPixmap(margin, margin, scaled_width, scaled_height, self.splash_image)

        text_x = scaled_width + 2 * margin
        top_offset = margin
        text_area_width = w - scaled_width - 2 * margin

        painter.setPen(text_color)


        text_size = 150
        font = QFont("Serif")
        font.setStyleHint(QFont.Serif)
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, margin + top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert)

        top_offset += text_size + 2 * margin
        text_size = 25
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.ert_title)

        top_offset += text_size + 4 * margin
        text_size = 20
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.version)

        top_offset += text_size + margin
        text_size = 15
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, top_offset, text_area_width, text_size, Qt.AlignHCenter | Qt.AlignCenter, self.timestamp)


        text_size = 12
        font.setPixelSize(text_size)
        painter.setFont(font)
        painter.drawText(text_x, h - text_size - margin - 5, text_area_width, text_size + 5, Qt.AlignHCenter | Qt.AlignCenter, self.copyright)
Пример #59
0
    def initGUI(self):
        self.inputs = []
        layout = QHBoxLayout()
        
        textLayout = QVBoxLayout()
        self.log = QPlainTextEdit()
        f = QFont("Monospace")
        f.setStyleHint(QFont.TypeWriter)
        self.log.setFont(f)
        self.log.setReadOnly(True)
        textLayout.addWidget( self.log)
        self.input = QLineEdit()
        self.input.returnPressed.connect(self.sendSerial)
        self.setFocusProxy( self.input)
        textLayout.addWidget(self.input)
        self.inputs += [self.input]
        layout.addLayout( textLayout)
 
        buttonLayout = QVBoxLayout()
        p = QPushButton("Reconnect")
        p.clicked.connect(self.reconnect)
        buttonLayout.addWidget(p)
        p = QPushButton("Rainbow")
        p.clicked.connect(
            lambda: self.strip.write( bytearray( [MAGIC,Command.RAINBOW] )))
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Test")
        p.clicked.connect(
            lambda: self.strip.write( bytearray( [MAGIC,Command.TEST] )))
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Blank")
        p.clicked.connect(
            lambda: self.strip.write( bytearray( [MAGIC,Command.BLANK] )))
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("UniColor")
        p.clicked.connect( self.openUnicolor )
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("LED State")
        p.clicked.connect( self.getLEDState)
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Conf")
        p.clicked.connect( lambda: self.updateConfig(True))
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Debug")
        p.clicked.connect( self.strip.toggleDebug)
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Reset")
        p.clicked.connect(
            lambda: self.strip.write( bytearray( [MAGIC,Command.RESET] )))
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Set Size")
        p.clicked.connect( self.setSize)
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Speed Test")
        p.clicked.connect( self.speedTest)
        buttonLayout.addWidget(p)
        self.inputs += [p]
        p = QPushButton("Free Mem")
        p.clicked.connect( self.freeMemory)
        buttonLayout.addWidget(p)
        self.inputs += [p]
        buttonLayout.addStretch(1)
        p = QPushButton("Quit")
        p.clicked.connect( self.close)
        buttonLayout.addWidget(p)
        layout.addLayout(buttonLayout)
       
        self.setLayout(layout)