Exemple #1
0
class UpdateDialog(QDialog):
    """The dialog for update."""
    def __init__(self):
        super(UpdateDialog, self).__init__()
        vbox = QVBoxLayout(self)
        self.closed = False
        self.setModal(True)
        self.resize(500, 250)

        vbox.addWidget(QLabel(u"Actualización de la lista de episodios:"))
        self.text = QPlainTextEdit()
        self.text.setReadOnly(True)
        vbox.addWidget(self.text)

        bbox = QDialogButtonBox(QDialogButtonBox.Cancel)
        bbox.rejected.connect(self.reject)
        vbox.addWidget(bbox)

    def append(self, text):
        """Append some text in the dialog."""
        self.text.appendPlainText(text.strip())

    def closeEvent(self, event):
        """It was closed."""
        self.closed = True
Exemple #2
0
    def __init__(self, parent, project=None):
        QPlainTextEdit.__init__(self)
        EditorGeneric.__init__(self)
        BaseCentralWidget.__init__(self)
        self.parent = parent
        self.completer = Completer(self, project)
        self.setWordWrapMode(QTextOption.NoWrap)
        doc = self.document()
        option = QTextOption()
        option.setFlags(QTextOption.ShowTabsAndSpaces)
        doc.setDefaultTextOption(option)
        self.setDocument(doc)
        self.set_default_font()

        #file modification time POSIX
        self._mtime = None
        #Flag to dont bug the user when answer 'dont show the modification dialog'
        self.ask_if_externally_modified = True

        self.lineNumberArea = self.LineNumberArea(self)
        self.viewport().installEventFilter(self)

        self.highlighter = None
        styles.set_style(self, 'editor')

        self.connect(self, SIGNAL("cursorPositionChanged()"), self.highlight_current_line)
        self.connect(self, SIGNAL("modificationChanged(bool)"), self.modif_changed)
        self.highlight_current_line()
Exemple #3
0
    def __init__(self, parent=None):
        QPlainTextEdit.__init__(self, parent)
        
        self.extra_selections_dict = {}
        
        # Undo/Redo
        self.undo_available = False
        self.redo_available = False
        self.connect(self, SIGNAL("undoAvailable(bool)"), self.set_undo)
        self.connect(self, SIGNAL("redoAvailable(bool)"), self.set_redo)
        self.connect(self, SIGNAL('textChanged()'), self.changed)
        self.connect(self, SIGNAL('cursorPositionChanged()'),
                     self.cursor_position_changed)

        # Code completion / calltips
        self.completion_widget = CompletionWidget(self, parent)
        self.codecompletion_auto = False
        self.codecompletion_enter = False
        self.calltips = True
        self.completion_text = ""
        self.calltip_position = None

        # Brace matching
        self.bracepos = None

        self.setup()
Exemple #4
0
class RecipeEditionDialog(QDialog):
    def __init__(self, recipe = None, parent = None):
        super(RecipeEditionDialog, self).__init__(parent)

        self.setWindowTitle('Recipe edition')

        self.name = QLineEdit()
        self.description = QPlainTextEdit()
        self.tags = QLineEdit()
        buttons = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel)
        buttons.accepted.connect(self.accept)
        buttons.rejected.connect(self.reject)

        l = QFormLayout(self)
        l.addRow('Name', self.name)
        l.addRow('Description', self.description)
        l.addRow('Tags', self.tags)
        l.addWidget(buttons)


        if recipe:
            self.recipe = recipe
            self.name.setText(recipe.name)
            self.description.setPlainText(recipe.description)
            self.tags.setText(';'.join(t.name for t in recipe.tags))
        else:
            self.recipe = Recipe('')

        self.accepted.connect(self.save_recipe)

    def save_recipe(self):
        self.recipe.name = self.name.text()
        self.recipe.description = self.description.toPlainText()
        self.recipe.tags = [Tag.get(t) for t in self.tags.text().split(';')] if self.tags.text() else []
        Session.add(self.recipe)
Exemple #5
0
class IdListFilter(QWidget, Control):

    """ Multiple ids filter
    """

    def __init__(self, tree, dataset, master, parent=None):
        QWidget.__init__(self, parent)
        Control.__init__(self, tree, dataset, master)
        self.tree = tree
        self.dataset = dataset
        self.master = master
        self.setObjectName(tree.internalName)

        self.setLayout(QGridLayout())
        self.textWidget = QPlainTextEdit()  # TODO: Subclass to receive drop events from item model views
        self.layout().addWidget(self.textWidget, 0, 0, 1, 1)

    def value(self):
        """ Return filter value for use in a query
        """
        return str(self.textWidget.toPlainText()).split()

    def get_filter(self):
        return self.tree.internalName, self.value()

    def query(self):
        return [("Filter", self.tree, self.value())]

    def setControlValue(self, name, value):
        if type(value) == list:
            value = "\n".join(value)
        self.textWidget.setPlainText(value)
Exemple #6
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)
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(self.tr("Name:")), 0, 0)
        self.name = QLineEdit()
        if self._parent._item.name == '':
            self.name.setText(file_manager.get_basename(
                self._parent._item.path))
        else:
            self.name.setText(self._parent._item.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(self.tr("Project Type:")), 1, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent._item.projectType)
        grid.addWidget(self.txtType, 1, 1)
        grid.addWidget(QLabel(self.tr("Description:")), 2, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent._item.description)
        grid.addWidget(self.description, 2, 1)
        grid.addWidget(QLabel(self.tr("URL:")), 3, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent._item.url)
        grid.addWidget(self.url, 3, 1)
        grid.addWidget(QLabel(self.tr("Licence:")), 4, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        index = self.cboLicense.findText(self._parent._item.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 4, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent._item.extensions))
        grid.addWidget(QLabel(self.tr("Supported Extensions:")), 5, 0)
        grid.addWidget(self.txtExtensions, 5, 1)

        grid.addWidget(QLabel(self.tr("Indentation: ")), 6, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 6, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 6, 2)
Exemple #8
0
    def __init__(self,parent=None):
		
        self.lang= None
        self.prevBlockNum=0
        #~ self.
        self.foldableLines={}
        self.foldedLines={}
        QPlainTextEdit.__init__(self,parent)
        self.palette= QPalette()
        self.palette.setColor(QPalette.Base, Qt.white)
        self.palette.setColor(QPalette.Text, Qt.black)
        self.setPalette(self.palette)
        self.lineNumberArea = LineNumberArea (self)
        #~ self.connect(self, SIGNAL("textChanged()"), 
                     #~ self.findFoldableLines)
        self.connect(self, SIGNAL("blockCountChanged(int)"), 
                     self.updateLineNumberAreaWidth)
            
        self.connect(self, SIGNAL("updateRequest(const QRect &, int)"), 
                     self.updateLineNumberArea)
        
                #~ 
        self.connect(self, SIGNAL("cursorPositionChanged()"), 
                     self.highlightCurrentLine)

        self.updateLineNumberAreaWidth(0)
        self.errorPos=None
        self.highlightCurrentLine()
        
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        self.setWordWrapMode(QTextOption.NoWrap)
        self.findFoldableLines()
Exemple #9
0
 def resizeEvent(self, e):
     QPlainTextEdit.resizeEvent(self,e)
     self.cr = self.contentsRect()
     self.lineNumberArea.setGeometry(self.cr.left(), 
                                     self.cr.top(), 
                                     self.lineNumberAreaWidth(), 
                                     self.cr.height())
Exemple #10
0
    def __init__(self):
        QPlainTextEdit.__init__(self, u'>>> ')
        self.setUndoRedoEnabled(False)
        self.apply_editor_style()
        self.setToolTip(self.tr("Show/Hide (F4)"))
        self.moveCursor(QTextCursor.EndOfLine)

        self._patIsWord = re.compile('\w+')
        self.prompt = u'>>> '
        self._console = console.Console()
        self._history = []
        self._braces = None
        self.imports = ['import __builtin__']
        self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import')
        self.patImport = re.compile('^(\\s)*import (\\w)+')
        self.patObject = re.compile('[^a-zA-Z0-9_\\.]')
        self.completer = completer_widget.CompleterWidget(self)
        self.okPrefix = QRegExp('[.)}:,\]]')

        #Create Context Menu
        self._create_context_menu()

        self._highlighter = highlighter.Highlighter(self.document(), 'python',
            resources.CUSTOM_SCHEME)

        self.connect(self, SIGNAL("cursorPositionChanged()"),
            self.highlight_current_line)
        self.highlight_current_line()
Exemple #11
0
    def keyPressEvent(self, event):
        #if self.completer.popup().isVisible():
            #if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Tab):
                #event.ignore()
                #self.completer.popup().hide()
                #return
            #elif event.key in (Qt.Key_Space, Qt.Key_Escape, Qt.Key_Backtab):
                #self.completer.popup().hide()

        self._check_event_on_selection(event)
        if self._pre_key_press.get(event.key(), lambda x: False)(event):
            return

        if event.text() in (set(BRACES.values()) - set(["'", '"'])):
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor)
            brace = cursor.selection().toPlainText()
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
            braceClose = cursor.selection().toPlainText()
            if BRACES.get(brace, False) == event.text() and \
              braceClose == event.text():
                self.moveCursor(QTextCursor.Right)
                return

        QPlainTextEdit.keyPressEvent(self, event)

        if event.text() in BRACES:
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.StartOfLine,
                QTextCursor.KeepAnchor)
            self.textCursor().insertText(
                BRACES[event.text()])
            self.moveCursor(QTextCursor.Left)
Exemple #12
0
 def mousePressEvent(self, event):
     """
     When the execution fail, allow to press the links in the traceback,
     to go to the line when the error occur.
     """
     QPlainTextEdit.mousePressEvent(self, event)
     self.go_to_error(event)
Exemple #13
0
 def mouseMoveEvent(self, event):
     position = event.pos()
     cursor = self.cursorForPosition(position)
     block = cursor.block()
     checkers = sorted(self._neditable.registered_checkers,
         key=lambda x: x[2], reverse=True)
     for items in checkers:
         checker, color, _ = items
         if block.blockNumber() in checker.checks:
             message = '\n'.join(checker.checks[block.blockNumber()])
             QToolTip.showText(self.mapToGlobal(position), message, self)
     if event.modifiers() == Qt.ControlModifier:
         cursor.select(QTextCursor.WordUnderCursor)
         selection_start = cursor.selectionStart()
         selection_end = cursor.selectionEnd()
         cursor.setPosition(selection_start - 1)
         cursor.setPosition(selection_end + 1, QTextCursor.KeepAnchor)
         if cursor.selectedText()[-1:] in ('(', '.') or \
         cursor.selectedText()[:1] in ('.', '@'):
             self.extraSelections = []
             selection = QTextEdit.ExtraSelection()
             lineColor = QColor(resources.CUSTOM_SCHEME.get('linkNavigate',
                         resources.COLOR_SCHEME['linkNavigate']))
             selection.format.setForeground(lineColor)
             selection.format.setFontUnderline(True)
             selection.cursor = cursor
             self.extraSelections.append(selection)
             self.setExtraSelections(self.extraSelections)
         else:
             self.extraSelections = []
             self.setExtraSelections(self.extraSelections)
     QPlainTextEdit.mouseMoveEvent(self, event)
Exemple #14
0
 def mouseMoveEvent(self, event):
     position = event.pos()
     cursor = self.cursorForPosition(position)
     block = cursor.block()
     if settings.ERRORS_HIGHLIGHT_LINE and \
     (block.blockNumber()) in self.errors.errorsSummary:
         message = '\n'.join(
             self.errors.errorsSummary[block.blockNumber()])
         QToolTip.showText(self.mapToGlobal(position),
             message, self)
     elif settings.CHECK_HIGHLIGHT_LINE and \
     (block.blockNumber()) in self.pep8.pep8checks:
         message = '\n'.join(
             self.pep8.pep8checks[block.blockNumber()])
         QToolTip.showText(self.mapToGlobal(position), message, self)
     if event.modifiers() == Qt.ControlModifier:
         cursor.select(QTextCursor.WordUnderCursor)
         cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
         if cursor.selectedText().endsWith('(') or \
         cursor.selectedText().endsWith('.'):
             cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor)
             self.extraSelections = []
             selection = QTextEdit.ExtraSelection()
             lineColor = QColor(resources.CUSTOM_SCHEME.get('linkNavigate',
                         resources.COLOR_SCHEME['linkNavigate']))
             selection.format.setForeground(lineColor)
             selection.format.setFontUnderline(True)
             selection.cursor = cursor
             self.extraSelections.append(selection)
             self.setExtraSelections(self.extraSelections)
         else:
             self.extraSelections = []
             self.setExtraSelections(self.extraSelections)
     QPlainTextEdit.mouseMoveEvent(self, event)
Exemple #15
0
    def __init__(self, parent=None, text=None,
                 EditorHighlighterClass=PythonHighlighter,
                 indenter=PythonCodeIndenter):
        QPlainTextEdit.__init__(self, parent)
        self.setFrameStyle(QFrame.NoFrame)
        self.setTabStopWidth(4)
        self.setLineWrapMode(QPlainTextEdit.NoWrap)
        font = QFont()
        font.setFamily("lucidasanstypewriter")
        font.setFixedPitch(True)
        font.setPointSize(10)
        self.setFont(font)
        self.highlighter = EditorHighlighterClass(self)
        if text:
            self.setPlainText(text)
        self.frame_style = self.frameStyle()
        self.draw_line = True
        self.print_width = self.fontMetrics().width("x"*78)
        self.line_pen = QPen(QColor("lightgrey"))
        self.last_row = self.last_col = -1
        self.last_block = None
        self.highlight_line = True
        self.highlight_color = self.palette().highlight().color().light(175)
        self.highlight_brush = QBrush(QColor(self.highlight_color))
        self.connect(self, SIGNAL("cursorPositionChanged()"), 
                        self.onCursorPositionChanged)
        self.indenter = indenter(RopeEditorWrapper(self))
        # True if you want to catch Emacs keys in actions
        self.disable_shortcuts = False

        self.prj = get_no_project()
        self.prj.root = None
        self.calltip = CallTip(self)
        self.autocomplete = AutoComplete(self)
Exemple #16
0
    def __init__(self, parent):
        QPlainTextEdit.__init__(self, parent)
        self._parent = parent
        self.setReadOnly(True)
        self.maxValue = 0
        self.actualValue = 0
        #traceback pattern
        self.patLink = re.compile(r'(\s)*File "(.*?)", line \d.+')
        #formats
        self.plain_format = QTextCharFormat()
        self.plain_format.setForeground(QBrush(QColor(
            resources.CUSTOM_SCHEME.get("editor-text",
            resources.COLOR_SCHEME["editor-text"]))))
        self.error_format = QTextCharFormat()
        self.error_format.setAnchor(True)
        self.error_format.setFontUnderline(True)
        self.error_format.setUnderlineStyle(QTextCharFormat.SingleUnderline)
        self.error_format.setUnderlineColor(Qt.red)
        self.error_format.setForeground(Qt.blue)
        self.error_format.setToolTip(self.tr("Click to show the source"))

        self.connect(self, SIGNAL("blockCountChanged(int)"), self._scroll_area)

        css = 'QPlainTextEdit {color: %s; background-color: %s;' \
            'selection-color: %s; selection-background-color: %s;}' \
            % (resources.CUSTOM_SCHEME.get('editor-text',
            resources.COLOR_SCHEME['editor-text']),
            resources.CUSTOM_SCHEME.get('editor-background',
                resources.COLOR_SCHEME['editor-background']),
            resources.CUSTOM_SCHEME.get('editor-selection-color',
                resources.COLOR_SCHEME['editor-selection-color']),
            resources.CUSTOM_SCHEME.get('editor-selection-background',
                resources.COLOR_SCHEME['editor-selection-background']))
        self.setStyleSheet(css)
Exemple #17
0
 def on_actionShow_logfiles_triggered(self):
     self._item.setText(3, '')
     try:
         loglines = self._client.getServiceLogs(self._service,
                                                self._instance)
     except ClientError as err:
         self._item.setText(3, str(err))
         return
     if not loglines:
         self._item.setText(3, 'Service does not return logs')
         return
     dlg = QDialog(self)
     loadUi(dlg, 'details.ui')
     dlg.tabber.clear()
     logs = []
     for logline in loglines:
         filename, content = logline.split(':', 1)
         if not logs or filename != logs[-1][0]:
             logs.append((filename, []))
         logs[-1][1].append(content)
     for filename, content in logs:
         widget = QPlainTextEdit(dlg)
         font = widget.font()
         font.setFamily('Monospace')
         widget.setFont(font)
         widget.setPlainText(''.join(content))
         widget.moveCursor(QTextCursor.End)
         widget.ensureCursorVisible()
         dlg.tabber.addTab(widget, filename)
     dlg.exec_()
Exemple #18
0
    def __init__(self, *args):
        QPlainTextEdit.__init__(self, *args)

        # toPlainText() takes a lot of time on long texts, therefore it is cached
        self._cachedText = None

        self._eol = self._DEFAULT_EOL
        self._indenter = Indenter(self)
        self.lineLengthEdge = None
        self.lineLengthEdgeColor = Qt.red
        self._atomicModificationDepth = 0

        self.drawWhiteSpaceTrailing = True
        self.drawWhiteSpaceAnyIndentation = False

        self._rectangularSelection = RectangularSelection(self)

        """Sometimes color themes will be supported.
        Now black on white is hardcoded in the highlighters.
        Hardcode same palette for not highlighted text
        """
        palette = self.palette()
        palette.setColor(QPalette.Base, QColor('#ffffff'))
        palette.setColor(QPalette.Text, QColor('#000000'))
        self.setPalette(palette)

        self._highlighter = None
        self._bracketHighlighter = BracketHighlighter()

        self._lines = Lines(self)

        self.completionThreshold = self._DEFAULT_COMPLETION_THRESHOLD
        self.completionEnabled = self._DEFAULT_COMPLETION_ENABLED
        self._completer = Completer(self)

        self._initActions()

        self._lineNumberArea = qutepart.sideareas.LineNumberArea(self)
        self._countCache = (-1, -1)
        self._markArea = qutepart.sideareas.MarkArea(self)

        self._bookmarks = qutepart.bookmarks.Bookmarks(self, self._markArea)

        self._userExtraSelections = []  # we draw bracket highlighting, current line and extra selections by user
        self._userExtraSelectionFormat = QTextCharFormat()
        self._userExtraSelectionFormat.setBackground(QBrush(QColor('#ffee00')))

        self.blockCountChanged.connect(self._updateLineNumberAreaWidth)
        self.updateRequest.connect(self._updateSideAreas)
        self.cursorPositionChanged.connect(self._updateExtraSelections)
        self.textChanged.connect(self._dropUserExtraSelections)
        self.textChanged.connect(self._resetCachedText)

        fontFamilies = {'Windows':'Courier New',
                        'Darwin': 'Menlo'}
        fontFamily = fontFamilies.get(platform.system(), 'Monospace')
        self.setFont(QFont(fontFamily))

        self._updateLineNumberAreaWidth(0)
        self._updateExtraSelections()
Exemple #19
0
 def dropEvent(self, event):
     if len(event.mimeData().urls()) > 0:
         path = event.mimeData().urls()[0].path()
         self.emit(SIGNAL("openDropFile(QString)"), path)
         event.ignore()
         event.mimeData = QMimeData()
     QPlainTextEdit.dropEvent(self, event)
     self.undo()
Exemple #20
0
 def mouseReleaseEvent(self, event):
     QPlainTextEdit.mouseReleaseEvent(self, event)
     if event.button() == Qt.LeftButton:
         self.highlight_selected_word()
     block_number = self.textCursor().blockNumber()
     if block_number != self._last_block_position:
         self._last_block_position = block_number
         self.emit(SIGNAL("currentLineChanged(int)"), block_number)
Exemple #21
0
 def keyPressEvent(self, event):
     """Intercept the key event to lets plugin do something if they want"""
     if event.type() ==  QEvent.KeyPress:
         for plugin in filter_plugins_by_capability('beforeKeyPressEvent',self.enabled_plugins):
             plugin.do_beforeKeyPressEvent(self,event)
         QPlainTextEdit.keyPressEvent(self, event)
         for plugin in filter_plugins_by_capability('afterKeyPressEvent',self.enabled_plugins):
             plugin.do_afterKeyPressEvent(self,event)
Exemple #22
0
 def wheelEvent(self, event, forward=True):
     if event.modifiers() == Qt.ControlModifier:
         if event.delta() == 120:
             self.zoom_in()
         elif event.delta() == -120:
             self.zoom_out()
         event.ignore()
     QPlainTextEdit.wheelEvent(self, event)
class ProjectData(QWidget):

    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(translations.TR_PROJECT_NAME), 0, 0)
        self.name = QLineEdit()
        if not len(self._parent.project.name):
            self.name.setText(file_manager.get_basename(
                self._parent.project.path))
        else:
            self.name.setText(self._parent.project.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LOCATION), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent.project.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_TYPE), 2, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent.project.project_type)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_DESCRIPTION), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent.project.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_URL), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent.project.url)
        self.url.setPlaceholderText('https://www.{}.com'.format(getuser()))
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(translations.TR_PROJECT_LICENSE), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItems(LICENCES)
        self.cboLicense.setCurrentIndex(12)
        index = self.cboLicense.findText(self._parent.project.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent.project.extensions))
        grid.addWidget(QLabel(translations.TR_PROJECT_EXTENSIONS), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(translations.TR_PROJECT_INDENTATION), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent.project.indentation)
        self.spinIndentation.setRange(2, 10)
        self.spinIndentation.setValue(4)
        self.spinIndentation.setSingleStep(2)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(translations.TR_PROJECT_USE_TABS)
        self.checkUseTabs.setChecked(self._parent.project.use_tabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Exemple #24
0
    def setFont(self, font):
        pass # suppress dockstring for non-public method
        """Set font and update tab stop width
        """
        QPlainTextEdit.setFont(self, font)
        self._updateTabStopWidth()

        # text on line numbers may overlap, if font is bigger, than code font
        self._lineNumberArea.setFont(font)
Exemple #25
0
    def __init__(self):
        QPlainTextEdit.__init__(self, '>>> ')
        self.setUndoRedoEnabled(False)
        self.apply_editor_style()
        self.setToolTip(self.tr("Show/Hide (F4)"))
        self.moveCursor(QTextCursor.EndOfLine)

        self._patIsWord = re.compile('\w+')
        self.prompt = '>>> '
        self._console = console.Console()
        self._history = []
        self.history_index = 0
        self._current_command = ''
        self._braces = None
        self.imports = ['import __builtin__']
        self.patFrom = re.compile('^(\\s)*from ((\\w)+(\\.)*(\\w)*)+ import')
        self.patImport = re.compile('^(\\s)*import (\\w)+')
        self.patObject = re.compile('[^a-zA-Z0-9_\\.]')
        self.completer = completer_widget.CompleterWidget(self)
        self.okPrefix = QRegExp('[.)}:,\]]')

        self._pre_key_press = {
            Qt.Key_Enter: self._enter_pressed,
            Qt.Key_Return: self._enter_pressed,
            Qt.Key_Tab: self._tab_pressed,
            Qt.Key_Home: self._home_pressed,
            Qt.Key_PageUp: lambda x: True,
            Qt.Key_PageDown: lambda x: True,
            Qt.Key_Left: self._left_pressed,
            Qt.Key_Up: self._up_pressed,
            Qt.Key_Down: self._down_pressed,
            Qt.Key_Backspace: self._backspace,
        }

        #Create Context Menu
        self._create_context_menu()

        #Set Font
        self.set_font()
        #Create Highlighter
        parts_scanner, code_scanner, formats = \
            syntax_highlighter.load_syntax(python_syntax.syntax)
        self.highlighter = syntax_highlighter.SyntaxHighlighter(
            self.document(),
            parts_scanner, code_scanner, formats)

        self.connect(self, SIGNAL("cursorPositionChanged()"),
            self.highlight_current_line)
        self.highlight_current_line()

        self._proc = QProcess(self)
        self.connect(self._proc, SIGNAL("readyReadStandardOutput()"),
            self._python_path_detected)
        self.connect(self._proc, SIGNAL("error(QProcess::ProcessError)"),
            self.process_error)
        self._add_system_path_for_frozen()
Exemple #26
0
 def mousePressEvent(self, event):
     if event.modifiers() == Qt.ControlModifier:
         cursor = self.cursorForPosition(event.pos())
         self.setTextCursor(cursor)
         self.go_to_definition(cursor)
     elif event.button() == Qt.RightButton and \
     not self.textCursor().hasSelection():
         cursor = self.cursorForPosition(event.pos())
         self.setTextCursor(cursor)
     QPlainTextEdit.mousePressEvent(self, event)
Exemple #27
0
 def __init__(self, params, parent=None):
     self._editor_widget = self
     QPlainTextEdit.__init__(self, parent)
     WithSingleIO.__init__(self, params)
     WithCompletion.__init__(self, parent)
     WithWordCompletionMulty_.__init__(self, parent)
     WithFixedFont.__init__(self, parent)
     WithViewPortMargins.__init__(self, parent)
     WithLineNumbers.__init__(self, parent)
     WithLineHighlight.__init__(self, parent)
     WithMqEditIO.__init__(self, params)
Exemple #28
0
    def __init__(self, *args, **kwargs):
        QPlainTextEdit.__init__(self, *args, **kwargs)
        self.setFrameStyle(QPlainTextEdit.NoFrame)
        self.setTextInteractionFlags(Qt.TextBrowserInteraction)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOn)
        self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred)

        font = self.font()
        font.setStyleHint(QFont.Monospace)
        font.setFamily("Monospace")
        self.setFont(font)
class ErrorReportDialog(QDialog):
    def __init__(self, parent, github_url, error):
        flags = Qt.CustomizeWindowHint | Qt.WindowTitleHint | Qt.WindowSystemMenuHint
        QDialog.__init__(self, parent, flags)
        self._setupUi()
        name = QCoreApplication.applicationName()
        version = QCoreApplication.applicationVersion()
        errorText = "Application Name: {0}\nVersion: {1}\n\n{2}".format(name, version, error)
        # Under windows, we end up with an error report without linesep if we don't mangle it
        errorText = errorText.replace('\n', os.linesep)
        self.errorTextEdit.setPlainText(errorText)
        self.github_url = github_url

        self.sendButton.clicked.connect(self.goToGithub)
        self.dontSendButton.clicked.connect(self.reject)

    def _setupUi(self):
        self.setWindowTitle(tr("Error Report"))
        self.resize(553, 349)
        self.verticalLayout = QVBoxLayout(self)
        self.label = QLabel(self)
        self.label.setText(tr("Something went wrong. How about reporting the error?"))
        self.label.setWordWrap(True)
        self.verticalLayout.addWidget(self.label)
        self.errorTextEdit = QPlainTextEdit(self)
        self.errorTextEdit.setReadOnly(True)
        self.verticalLayout.addWidget(self.errorTextEdit)
        msg = tr(
            "Error reports should be reported as Github issues. You can copy the error traceback "
            "above and paste it in a new issue (bonus point if you run a search to make sure the "
            "issue doesn't already exist). What usually really helps is if you add a description "
            "of how you got the error. Thanks!"
            "\n\n"
            "Although the application should continue to run after this error, it may be in an "
            "unstable state, so it is recommended that you restart the application."
        )
        self.label2 = QLabel(msg)
        self.label2.setWordWrap(True)
        self.verticalLayout.addWidget(self.label2)
        self.horizontalLayout = QHBoxLayout()
        self.horizontalLayout.addItem(horizontalSpacer())
        self.dontSendButton = QPushButton(self)
        self.dontSendButton.setText(tr("Close"))
        self.dontSendButton.setMinimumSize(QSize(110, 0))
        self.horizontalLayout.addWidget(self.dontSendButton)
        self.sendButton = QPushButton(self)
        self.sendButton.setText(tr("Go to Github"))
        self.sendButton.setMinimumSize(QSize(110, 0))
        self.sendButton.setDefault(True)
        self.horizontalLayout.addWidget(self.sendButton)
        self.verticalLayout.addLayout(self.horizontalLayout)

    def goToGithub(self):
        open_url(self.github_url)
Exemple #30
0
 def paintEvent(self, e):
     QPlainTextEdit.paintEvent(self, e)
     if self._margin:
         qp = QPainter()
         qp.begin(self.viewport())
         qp.setPen(self._margin.color)
         offset = self.contentOffset()
         qp.drawLine(self.position_margin + offset.x(), 0,
                     self.position_margin + offset.x(),
                     self.viewport().height())
         qp.end()
Exemple #31
0
    def _build_wdgs(self):
        """
        Builds own widgets.
        """

        self.org_lbl = QLabel(self)
        self.org_lbl.setObjectName(u'org_lbl')
        self.org_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.org_lbl.setText(u'organization')
        self.grid_lyt.addWidget(self.org_lbl, 0, 0, 1, 1)

        self.org_cb = QComboBox(self)
        self.org_cb.setObjectName(u'org_cb')
        self.grid_lyt.addWidget(self.org_cb, 0, 1, 1, 1)

        self.no_lbl = QLabel(self)
        self.no_lbl.setObjectName(u'no_lbl')
        self.no_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.no_lbl.setText(u'projectNumber')
        self.grid_lyt.addWidget(self.no_lbl, 1, 0, 1, 1)

        self.no_le = QLineEdit(self)
        self.no_le.setObjectName(u'no_le')
        self.grid_lyt.addWidget(self.no_le, 1, 1, 1, 1)

        self.name_lbl = QLabel(self)
        self.name_lbl.setObjectName(u'name_lbl')
        self.name_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.name_lbl.setText(u'projectName')
        self.grid_lyt.addWidget(self.name_lbl, 2, 0, 1, 1)

        self.name_le = QLineEdit(self)
        self.name_le.setObjectName(u'name_le')
        self.grid_lyt.addWidget(self.name_le, 2, 1, 1, 1)

        self.styr_lbl = QLabel(self)
        self.styr_lbl.setObjectName(u'styr_lbl')
        self.styr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.styr_lbl.setText(u'startYear')
        self.grid_lyt.addWidget(self.styr_lbl, 3, 0, 1, 1)

        self.styr_mde = de.MtyDe(self)
        self.styr_mde.setObjectName(u'styr_mde')
        self.styr_mde.setDisplayFormat('yyyy')
        self.grid_lyt.addWidget(self.styr_mde, 3, 1, 1, 1)

        self.endyr_lbl = QLabel(self)
        self.endyr_lbl.setObjectName(u'endyr_lbl')
        self.endyr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.endyr_lbl.setText(u'endYear')
        self.grid_lyt.addWidget(self.endyr_lbl, 4, 0, 1, 1)

        self.endyr_mde = de.MtyDe(self)
        self.endyr_mde.setObjectName(u'endyr_mde')
        self.endyr_mde.setDisplayFormat('yyyy')
        self.grid_lyt.addWidget(self.endyr_mde, 4, 1, 1, 1)

        self.ldr_lbl = QLabel(self)
        self.ldr_lbl.setObjectName(u'ldr_lbl')
        self.ldr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.ldr_lbl.setText(u'projectLeader')
        self.grid_lyt.addWidget(self.ldr_lbl, 5, 0, 1, 1)

        self.ldr_le = QLineEdit(self)
        self.ldr_le.setObjectName(u'ldr_le')
        self.grid_lyt.addWidget(self.ldr_le, 5, 1, 1, 1)

        self.mbr_lbl = QLabel(self)
        self.mbr_lbl.setObjectName(u'mbr_lbl')
        self.mbr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.mbr_lbl.setText(u'projectMembers')
        self.grid_lyt.addWidget(self.mbr_lbl, 6, 0, 1, 1)

        self.mbr_pte = QPlainTextEdit(self)
        self.mbr_pte.setObjectName(u'mbr_pte')
        self.grid_lyt.addWidget(self.mbr_pte, 6, 1, 1, 1)

        self.fncr_lbl = QLabel(self)
        self.fncr_lbl.setObjectName(u'fncr_lbl')
        self.fncr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.fncr_lbl.setText(u'financer')
        self.grid_lyt.addWidget(self.fncr_lbl, 7, 0, 1, 1)

        self.fncr_le = QLineEdit(self)
        self.fncr_le.setObjectName(u'fncr_le')
        self.grid_lyt.addWidget(self.fncr_le, 7, 1, 1, 1)

        self.rmk_lbl = QLabel(self)
        self.rmk_lbl.setObjectName(u'rmk_lbl')
        self.rmk_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.rmk_lbl.setText(u'remarks')
        self.grid_lyt.addWidget(self.rmk_lbl, 8, 0, 1, 1)

        self.rmk_pte = QPlainTextEdit(self)
        self.rmk_pte.setObjectName(u'rmk_pte')
        self.grid_lyt.addWidget(self.rmk_pte, 8, 1, 1, 1)

        self.mand_wdgs = [
            self.org_cb, self.no_le, self.name_le, self.styr_mde, self.ldr_le,
            self.fncr_le
        ]

        self.iw.set_mand_wdgs(self.mand_wdgs)

        # temporary workaround
        self.no_le.setValidator(
            vald.LenIntVald(self.no_le, -2147483648, 2147483647))

        self._fetch_prj_data()

        # to keep order
        self.input_wdgs = [
            self.org_cb, self.no_le, self.name_le, self.styr_mde,
            self.endyr_mde, self.ldr_le, self.mbr_pte, self.fncr_le,
            self.rmk_pte
        ]

        self.btn_lyt = QHBoxLayout()
        self.grid_lyt.addLayout(self.btn_lyt, 9, 1, 1, 1)

        self.sv_btn = QPushButton(self)
        self.sv_btn.setObjectName(u'sv_btn')
        self.sv_btn.setText(u'Save')
        self.sv_btn.clicked.connect(self._save_prj)
        self.btn_lyt.addWidget(self.sv_btn)

        self.cl_btn = QPushButton(self)
        self.cl_btn.setObjectName(u'ok_btn')
        self.cl_btn.setText(u'Close')
        self.cl_btn.clicked.connect(self.close)
        self.btn_lyt.addWidget(self.cl_btn)
Exemple #32
0
    def __init__(self, neditable):
        QPlainTextEdit.__init__(self)
        itab_item.ITabItem.__init__(self)
        self._neditable = neditable
        self._neditable.set_editor(self)
        #Config Editor
        self.set_flags()
        self.__lines_count = None

        self._sidebarWidget = sidebar_widget.SidebarWidget(self, neditable)

        self.highlighter = None
        self.allows_less_indentation = ['else', 'elif', 'finally', 'except']
        #Set editor style
        self.apply_editor_style()
        self.set_font(settings.FONT_FAMILY, settings.FONT_SIZE)
        #For Highlighting in document
        self.extraSelections = []
        self._selected_word = ''
        self._patIsWord = re.compile('\w+')
        #Brace matching
        self._braces = None
        self.__encoding = None
        #Completer
        self.completer = completer_widget.CodeCompletionWidget(self)
        #Flag to dont bug the user when answer *the modification dialog*
        self.just_saved = False
        #Dict functions for KeyPress
        self.preKeyPress = {
            Qt.Key_Tab: self.__insert_indentation,
            Qt.Key_Backspace: self.__backspace,
            Qt.Key_Home: self.__home_pressed,
            Qt.Key_Enter: self.__ignore_extended_line,
            Qt.Key_Return: self.__ignore_extended_line,
            Qt.Key_Colon: self.__retreat_to_keywords,
            Qt.Key_BracketRight: self.__brace_completion,
            Qt.Key_BraceRight: self.__brace_completion,
            Qt.Key_ParenRight: self.__brace_completion,
            Qt.Key_Apostrophe: self.__quot_completion,
            Qt.Key_QuoteDbl: self.__quot_completion
        }

        self.postKeyPress = {
            Qt.Key_Enter: self.__auto_indent,
            Qt.Key_Return: self.__auto_indent,
            Qt.Key_BracketLeft: self.__complete_braces,
            Qt.Key_BraceLeft: self.__complete_braces,
            Qt.Key_ParenLeft: self.__complete_braces,
            Qt.Key_Apostrophe: self.__complete_quotes,
            Qt.Key_QuoteDbl: self.__complete_quotes
        }

        self._current_line_color = QColor(
            resources.CUSTOM_SCHEME.get(
                'current-line', resources.COLOR_SCHEME['current-line']))

        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                     self._sidebarWidget.update_area)
        #FIXME: Should file saved be handled by neditable??
        self.connect(self, SIGNAL("undoAvailable(bool)"), self._file_saved)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
                     self.highlight_current_line)
        self.connect(self, SIGNAL("blockCountChanged(int)"),
                     self._update_file_metadata)
        self.connect(self._neditable, SIGNAL("checkersUpdated()"),
                     self._show_tab_icon_notification)

        self._mini = None
        if settings.SHOW_MINIMAP:
            self._mini = minimap.MiniMap(self)
            self._mini.show()

        #Indentation
        self.load_project_config()
        #Context Menu Options
        self.__actionFindOccurrences = QAction(self.tr("Find Usages"), self)
        self.connect(self.__actionFindOccurrences, SIGNAL("triggered()"),
                     self._find_occurrences)

        self.set_current_selected()
    def setup_ui(self, dock_widget):
        """
        initiate main Qt building blocks of interface
        :param dock_widget: QDockWidget instance
        """

        dock_widget.setObjectName("dock_widget")
        dock_widget.setAttribute(Qt.WA_DeleteOnClose)

        self.dock_widget_content = QWidget(self)
        self.dock_widget_content.setObjectName("dockWidgetContent")

        self.main_vlayout = QVBoxLayout(self)
        self.dock_widget_content.setLayout(self.main_vlayout)

        # add button to add objects to graphs
        self.button_bar_hlayout = QHBoxLayout(self)

        self.show_manual_input_button = QPushButton(self)
        self.button_bar_hlayout.addWidget(self.show_manual_input_button)
        self.show_manual_input_button.setDisabled(True)

        self.button_bar_hlayout.addWidget(QLabel("filter t/m categorie:"))
        self.category_combo = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.category_combo)

        self.next_endpoint_button = QPushButton(self)
        self.button_bar_hlayout.addWidget(self.next_endpoint_button)
        self.next_endpoint_button.setDisabled(True)

        self.child_selection_strategy_combo = QComboBox(self)
        self.button_bar_hlayout.addWidget(QLabel("doortrekken tot:"))
        self.button_bar_hlayout.addWidget(self.child_selection_strategy_combo)

        spacer_item = QSpacerItem(40,
                                  20,
                                  QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.button_bar_hlayout.addItem(spacer_item)

        # self.button_bar_hlayout.addItem(QLabel("doortrekken tot:"))
        # self.button_bar_hlayout.addItem(self.begroeiings_strategy_combo)

        self.main_vlayout.addLayout(self.button_bar_hlayout)
        # add tabWidget for graphWidgets
        self.contentLayout = QHBoxLayout(self)

        self.tree_table_tab = QTabWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.tree_table_tab.sizePolicy().hasHeightForWidth())
        self.tree_table_tab.setSizePolicy(sizePolicy)
        self.tree_table_tab.setMinimumSize(QSize(850, 0))

        self.contentLayout.addWidget(self.tree_table_tab)

        # startpointTree
        self.startpoint_tree_widget = StartpointTreeWidget(self, self.area_model)
        # sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(
        #     self.legger_tree_widget.sizePolicy().hasHeightForWidth())
        # self.legger_tree_widget.setSizePolicy(sizePolicy)
        # self.legger_tree_widget.setMinimumSize(QSize(750, 0))

        self.tree_table_tab.addTab(self.startpoint_tree_widget, 'startpunten')

        # LeggerTree
        self.legger_tree_widget = LeggerTreeWidget(self, self.legger_model)
        # sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(
        #     self.legger_tree_widget.sizePolicy().hasHeightForWidth())
        # self.legger_tree_widget.setSizePolicy(sizePolicy)
        # self.legger_tree_widget.setMinimumSize(QSize(750, 0))

        self.tree_table_tab.addTab(self.legger_tree_widget, 'hydrovakken')

        # graphs
        self.graph_vlayout = QVBoxLayout(self)

        # Graph
        self.plot_widget = LeggerPlotWidget(
            self, session=self.session,
            legger_model=self.legger_model,
            variant_model=self.variant_model)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.plot_widget.sizePolicy().hasHeightForWidth())
        self.plot_widget.setSizePolicy(sizePolicy)
        self.plot_widget.setMinimumSize(QSize(250, 150))

        self.graph_vlayout.addWidget(self.plot_widget, 2)

        # Sideview Graph
        self.sideview_widget = LeggerSideViewPlotWidget(
            self, session=self.session,
            legger_model=self.legger_model)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.sideview_widget.sizePolicy().hasHeightForWidth())
        self.sideview_widget.setSizePolicy(sizePolicy)
        self.sideview_widget.setMinimumSize(QSize(250, 150))

        self.graph_vlayout.addWidget(self.sideview_widget)

        self.contentLayout.addLayout(self.graph_vlayout, 2)

        self.rightVstack = QVBoxLayout(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        self.begroeiings_combo = QComboBox(self)
        self.begroeiings_strategy_combo = QComboBox(self)
        self.groupBox_begroeiings = QGroupBox(self)
        self.groupBox_begroeiings.setTitle("begroeiingsfilter en voor welk deel")
        vbox_strat = QVBoxLayout()
        vbox_strat.addWidget(self.begroeiings_combo)
        vbox_strat.addWidget(self.begroeiings_strategy_combo)
        self.groupBox_begroeiings.setLayout(vbox_strat)
        self.rightVstack.addWidget(self.groupBox_begroeiings)

        # variantentable
        self.plot_item_table = VariantenTable(self, variant_model=self.variant_model)
        self.plot_item_table.setMinimumWidth(380)

        self.rightVstack.addWidget(self.plot_item_table)

        self.selected_variant_remark = QPlainTextEdit(self)
        self.selected_variant_remark.setFixedHeight(100)
        self.selected_variant_remark.setDisabled(True)

        self.rightVstack.addWidget(self.selected_variant_remark)

        self.contentLayout.addLayout(self.rightVstack, 0)

        self.main_vlayout.addLayout(self.contentLayout)

        # add dockwidget
        dock_widget.setWidget(self.dock_widget_content)
        self.retranslate_ui(dock_widget)
        QMetaObject.connectSlotsByName(dock_widget)
Exemple #34
0
 def setDocument(self, document):
     QPlainTextEdit.setDocument(self, document)
     self.highlighter.setDocument(document)
Exemple #35
0
    def getWidgetFromParameter(self, param):
        # TODO Create Parameter widget class that holds the logic
        # for creating a widget that belongs to the parameter.
        if isinstance(param, ParameterRaster):
            layers = dataobjects.getRasterLayers()
            items = []
            if param.optional:
                items.append((self.NOT_SELECTED, None))
            for layer in layers:
                items.append((self.getExtendedLayerName(layer), layer))
            item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterVector):
            if self.somethingDependsOnThisParameter(
                    param) or self.alg.allowOnlyOpenedLayers:
                item = QComboBox()
                layers = dataobjects.getVectorLayers(param.shapetype)
                layers.sort(key=lambda lay: lay.name())
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(self.getExtendedLayerName(layer), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getVectorLayers(param.shapetype)
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((self.getExtendedLayerName(layer), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterTable):
            if self.somethingDependsOnThisParameter(param):
                item = QComboBox()
                layers = dataobjects.getTables()
                if param.optional:
                    item.addItem(self.NOT_SELECTED, None)
                for layer in layers:
                    item.addItem(layer.name(), layer)
                item.currentIndexChanged.connect(self.updateDependentFields)
                item.name = param.name
            else:
                layers = dataobjects.getTables()
                items = []
                if param.optional:
                    items.append((self.NOT_SELECTED, None))
                for layer in layers:
                    items.append((layer.name(), layer))
                # if already set, put first in list
                for i, (name, layer) in enumerate(items):
                    if layer and layer.source() == param.value:
                        items.insert(0, items.pop(i))
                item = InputLayerSelectorPanel(items, param)
        elif isinstance(param, ParameterBoolean):
            item = QCheckBox()
            if param.default:
                item.setChecked(True)
            else:
                item.setChecked(False)
        elif isinstance(param, ParameterTableField):
            item = QComboBox()
            if param.parent in self.dependentItems:
                items = self.dependentItems[param.parent]
            else:
                items = []
                self.dependentItems[param.parent] = items
            items.append(param.name)
            parent = self.alg.getParameterFromName(param.parent)
            if isinstance(parent, ParameterVector):
                layers = dataobjects.getVectorLayers(parent.shapetype)
            else:
                layers = dataobjects.getTables()
            if len(layers) > 0:
                if param.optional:
                    item.addItem(self.tr('[not set]'))
                item.addItems(self.getFields(layers[0], param.datatype))
        elif isinstance(param, ParameterSelection):
            item = QComboBox()
            item.addItems(param.options)
            item.setCurrentIndex(param.default)
        elif isinstance(param, ParameterFixedTable):
            item = FixedTablePanel(param)
        elif isinstance(param, ParameterRange):
            item = RangePanel(param)
        elif isinstance(param, ParameterFile):
            item = FileSelectionPanel(param.isFolder, param.ext)
        elif isinstance(param, ParameterMultipleInput):
            if param.datatype == ParameterMultipleInput.TYPE_FILE:
                item = MultipleInputPanel(
                    datatype=ParameterMultipleInput.TYPE_FILE)
            else:
                if param.datatype == ParameterMultipleInput.TYPE_RASTER:
                    options = dataobjects.getRasterLayers(sorting=False)
                elif param.datatype == ParameterMultipleInput.TYPE_VECTOR_ANY:
                    options = dataobjects.getVectorLayers(sorting=False)
                else:
                    options = dataobjects.getVectorLayers([param.datatype],
                                                          sorting=False)
                opts = []
                for opt in options:
                    opts.append(self.getExtendedLayerName(opt))
                item = MultipleInputPanel(opts)
        elif isinstance(param, ParameterNumber):
            item = NumberInputPanel(param.default, param.min, param.max,
                                    param.isInteger)
        elif isinstance(param, ParameterExtent):
            item = ExtentSelectionPanel(self.parent, self.alg, param.default)
        elif isinstance(param, ParameterCrs):
            item = CrsSelectionPanel(param.default)
        elif isinstance(param, ParameterString):
            if param.multiline:
                verticalLayout = QVBoxLayout()
                verticalLayout.setSizeConstraint(QLayout.SetDefaultConstraint)
                textEdit = QPlainTextEdit()
                textEdit.setPlainText(param.default)
                verticalLayout.addWidget(textEdit)
                item = textEdit
            else:
                item = QLineEdit()
                item.setText(str(param.default))
        else:
            item = QLineEdit()
            item.setText(str(param.default))

        return item
class ProjectExecution(QWidget):
    def __init__(self, parent):
        super(ProjectExecution, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)

        grid.addWidget(QLabel(self.tr("Main File:")), 0, 0)
        self.path = QLineEdit()
        ui_tools.LineEditButton(
            self.path, self.path.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.path.setText(self._parent._item.mainFile)
        self.path.setReadOnly(True)
        self.btnBrowse = QPushButton(
            QIcon(self.style().standardPixmap(self.style().SP_FileIcon)), '')
        grid.addWidget(self.path, 0, 1)
        grid.addWidget(self.btnBrowse, 0, 2)

        # this should be changed, and ALL pythonPath names to
        # python_custom_interpreter or something like that. this is NOT the
        # PYTHONPATH
        self.txtPythonPath = QLineEdit()
        self.txtPythonPath.setText(self._parent._item.pythonPath)
        self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Python Custom Interpreter:")), 1, 0)
        grid.addWidget(self.txtPythonPath, 1, 1)
        grid.addWidget(self.btnPythonPath, 1, 2)

        # THIS IS THE MODAFUCKA REAL PYTHONPATH BRO, YEAH !!!
        grid.addWidget(QLabel(self.tr("Custom PYTHONPATH:")), 2, 0)
        self.PYTHONPATH = QPlainTextEdit()  # TODO : better widget
        self.PYTHONPATH.setPlainText(self._parent._item.PYTHONPATH)
        self.PYTHONPATH.setToolTip(self.tr("One path per line"))
        grid.addWidget(self.PYTHONPATH, 2, 1)

        # Additional builtins/globals for pyflakes
        grid.addWidget(QLabel(self.tr("Additional builtins/globals:")), 3, 0)
        self.additional_builtins = QLineEdit()
        self.additional_builtins.setText(' '.join(
            self._parent._item.additional_builtins))
        self.additional_builtins.setToolTip(
            self.tr(
                "Space-separated list of symbols that will be considered as "
                "builtin in every file"))
        grid.addWidget(self.additional_builtins, 3, 1)

        self.txtPreExec = QLineEdit()
        ui_tools.LineEditButton(
            self.txtPreExec, self.txtPreExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPreExec.setReadOnly(True)
        self.txtPreExec.setText(self._parent._item.preExecScript)
        self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 4, 0)
        grid.addWidget(self.txtPreExec, 4, 1)
        grid.addWidget(self.btnPreExec, 4, 2)
        self.txtPostExec = QLineEdit()
        ui_tools.LineEditButton(
            self.txtPostExec, self.txtPostExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPostExec.setReadOnly(True)
        self.txtPostExec.setText(self._parent._item.postExecScript)
        self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Post-exec Script:")), 5, 0)
        grid.addWidget(self.txtPostExec, 5, 1)
        grid.addWidget(self.btnPostExec, 5, 2)

        grid.addItem(
            QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding),
            6, 0)

        # Properties
        grid.addWidget(QLabel(self.tr("Properties:")), 7, 0)
        self.txtParams = QLineEdit()
        self.txtParams.setToolTip(
            self.tr("Separate the params with commas (ie: help, verbose)"))
        self.txtParams.setText(self._parent._item.programParams)
        grid.addWidget(QLabel(self.tr("Params (comma separated):")), 8, 0)
        grid.addWidget(self.txtParams, 8, 1)
        #Widgets for virtualenv properties
        self.txtVenvPath = QLineEdit()
        ui_tools.LineEditButton(
            self.txtVenvPath, self.txtVenvPath.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtVenvPath.setText(self._parent._item.venv)
        self._dir_completer = QCompleter()
        self._dir_completer.setModel(QDirModel(self._dir_completer))
        self.txtVenvPath.setCompleter(self._dir_completer)
        self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 9, 0)
        grid.addWidget(self.txtVenvPath, 9, 1)
        grid.addWidget(self.btnVenvPath, 9, 2)

        self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file)
        self.connect(self.btnPythonPath, SIGNAL("clicked()"),
                     self._load_python_path)
        self.connect(self.btnVenvPath, SIGNAL("clicked()"),
                     self._load_python_venv)
        self.connect(self.btnPreExec, SIGNAL("clicked()"),
                     self.select_pre_exec_script)
        self.connect(self.btnPostExec, SIGNAL("clicked()"),
                     self.select_post_exec_script)

    def _load_python_path(self):
        path = QFileDialog.getOpenFileName(self, self.tr("Select Python Path"))
        self.txtPythonPath.setText(path)

    def _load_python_venv(self):
        venv = QFileDialog.getExistingDirectory(
            self, self.tr("Select Virtualenv Folder"))
        if sys.platform == 'win32':
            venv = os.path.join(venv, 'Scripts', 'python.exe')
        else:
            venv = os.path.join(venv, 'bin', 'python')
        #check if venv folder exists
        if not os.path.exists(venv):
            QMessageBox.information(
                self, self.tr("Virtualenv Folder"),
                self.tr("This is not a valid Virtualenv Folder"))
            self.txtVenvPath.setText("")
        else:
            self.txtVenvPath.setText(venv)

    def select_file(self):
        fileName = QFileDialog.getOpenFileName(self,
                                               self.tr("Select Main File"),
                                               self._parent._item.path,
                                               '(*.py);;(*.*)')
        if fileName != '':
            fileName = file_manager.convert_to_relative(
                self._parent._item.path, fileName)
            self.path.setText(fileName)

    def select_pre_exec_script(self):
        fileName = QFileDialog.getOpenFileName(
            self, self.tr("Select Pre Execution Script File"),
            self._parent._item.path, '(*.*)')
        if fileName != '':
            fileName = file_manager.convert_to_relative(
                self._parent._item.path, fileName)
            self.txtPreExec.setText(fileName)

    def select_post_exec_script(self):
        fileName = QFileDialog.getOpenFileName(
            self, self.tr("Select Post Execution Script File"),
            self._parent._item.path, '(*.*)')
        if fileName != '':
            fileName = file_manager.convert_to_relative(
                self._parent._item.path, fileName)
            self.txtPostExec.setText(fileName)
Exemple #37
0
    def __init__(self, filename, project, project_obj=None):
        QPlainTextEdit.__init__(self)
        itab_item.ITabItem.__init__(self)
        #Config Editor
        self.set_flags()
        self.__lines_count = None

        self._sidebarWidget = sidebar_widget.SidebarWidget(self)
        if filename in settings.BREAKPOINTS:
            self._sidebarWidget._breakpoints = settings.BREAKPOINTS[filename]
        if filename in settings.BOOKMARKS:
            self._sidebarWidget._bookmarks = settings.BOOKMARKS[filename]
        self.pep8 = pep8_checker.Pep8Checker(self)
        self.errors = errors_checker.ErrorsChecker(self)

        self.textModified = False
        self.newDocument = True
        self.highlighter = None
        self.syncDocErrorsSignal = False
        self._selected_word = ''
        #Set editor style
        self.apply_editor_style()
        self.set_font(settings.FONT_FAMILY, settings.FONT_SIZE)
        #For Highlighting in document
        self.extraSelections = []
        self.wordSelection = []
        self._patIsWord = re.compile('\w+')
        #Brace matching
        self._braces = None
        self.__encoding = None
        #Completer
        self.completer = completer_widget.CodeCompletionWidget(self)
        #Indentation
        if project_obj is not None:
            self.indent = project_obj.indentation
            self.useTabs = project_obj.useTabs
        else:
            self.indent = settings.INDENT
            self.useTabs = settings.USE_TABS
        #Flag to dont bug the user when answer *the modification dialog*
        self.ask_if_externally_modified = False
        self.just_saved = False
        #Dict functions for KeyPress
        self.preKeyPress = {
            Qt.Key_Tab: self.__insert_indentation,
            Qt.Key_Backspace: self.__backspace,
            Qt.Key_Home: self.__home_pressed,
            Qt.Key_Enter: self.__ignore_extended_line,
            Qt.Key_Return: self.__ignore_extended_line,
            Qt.Key_BracketRight: self.__brace_completion,
            Qt.Key_BraceRight: self.__brace_completion,
            Qt.Key_ParenRight: self.__brace_completion,
            Qt.Key_Apostrophe: self.__quot_completion,
            Qt.Key_QuoteDbl: self.__quot_completion}

        self.postKeyPress = {
            Qt.Key_Enter: self.__auto_indent,
            Qt.Key_Return: self.__auto_indent,
            Qt.Key_BracketLeft: self.__complete_braces,
            Qt.Key_BraceLeft: self.__complete_braces,
            Qt.Key_ParenLeft: self.__complete_braces,
            Qt.Key_Apostrophe: self.__complete_quotes,
            Qt.Key_QuoteDbl: self.__complete_quotes}

        self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
            self._sidebarWidget.update_area)
        self.connect(self, SIGNAL("undoAvailable(bool)"), self._file_saved)
        self.connect(self, SIGNAL("cursorPositionChanged()"),
            self.highlight_current_line)
        self.connect(self.pep8, SIGNAL("finished()"), self.show_pep8_errors)
        self.connect(self.errors, SIGNAL("finished()"),
            self.show_static_errors)
        self.connect(self, SIGNAL("blockCountChanged(int)"),
            self._update_file_metadata)

        self._mini = None
        if settings.SHOW_MINIMAP:
            self._mini = minimap.MiniMap(self)
            self._mini.show()
            self.connect(self, SIGNAL("updateRequest(const QRect&, int)"),
                self._mini.update_visible_area)
        #Set tab usage
        if self.useTabs:
            self.set_tab_usage()

        #Context Menu Options
        self.__actionFindOccurrences = QAction(
            self.tr("Find Usages"), self)
        self.connect(self.__actionFindOccurrences, SIGNAL("triggered()"),
            self._find_occurrences)
Exemple #38
0
    def create_account_dialog(self):
        def coinapult_signup():
            try:
                self.client.createAccount(createLocalKeys=True, changeAuthMethod=True, tag="electrum-gfk36")
                self.client.activateAccount(agree=True)
            except (CoinapultError, CoinapultErrorECC) as ce:
                QMessageBox.warning(None, _("Unable to create Coinapult account because %s" % str(ce),
                                            QString(_("OK"))))

        def signup_done(result):
            self.ca_ok_button.setDisabled(False)
            self.wallet.storage.put("coinapult_ecc_public", str(self.client.ecc_pub_pem))
            self.ecc_pub_key_edit.setText(self.client.ecc_pub_pem)
            self.wallet.storage.put("coinapult_ecc_private", str(self.client.ecc['privkey'].to_pem()))
            self.ecc_priv_key_edit.setText(str(self.client.ecc['privkey'].to_pem()))
            self.config.set_key('coinapult_auth_method', 'ECC', True)
            ecc_pub = self.wallet.storage.get("coinapult_ecc_public", '')
            ecc_priv = self.wallet.storage.get("coinapult_ecc_private", '')
            try:
                self.client = CoinapultClient(ecc={'pubkey': ecc_pub, 'privkey': ecc_priv}, authmethod='ecc')
            except (CoinapultError, CoinapultErrorECC):
                self.client = None
                QMessageBox.warning(None, _('Coinapult Connection failed'),
                                    _('Failed to connect to Coinapult. Locks disabled for this session.'), _('OK'))
            d.accept()

        def on_change_tos(checked):
            if checked:
                self.config.set_key('plugin_coinapult_locks_tos', 'checked')
            else:
                self.config.set_key('plugin_coinapult_locks_tos', 'unchecked')

        def ok_clicked():
            if self.agreed_tos():
                self.ca_ok_button.setDisabled(True)
                self.waiting_dialog = WaitingDialog(d, 'Creating your Coinapult account. One moment please...',
                                                    coinapult_signup, signup_done)
                self.waiting_dialog.start()

        d = QDialog()
        d.setWindowTitle("Create Coinapult Account")
        layout = QGridLayout(d)

        # lable = None
        text_edit = QPlainTextEdit()
        text = open(os.path.dirname(__file__) + '/lib/TERMS.txt').read()
        text_edit.setPlainText(text)
        layout.addWidget(text_edit, 0, 0)
        layout.setRowStretch(0, 8)

        layout.addWidget(QLabel(_("Do you agree to Coinapult's Terms of Service (https://coinapult.com/terms)?: ")),
                         3, 0)
        tos_checkbox = QCheckBox()
        tos_checkbox.setEnabled(True)
        tos_checkbox.setChecked(self.config.get('plugin_coinapult_locks_tos', 'unchecked') != 'unchecked')
        tos_checkbox.stateChanged.connect(on_change_tos)
        layout.addWidget(tos_checkbox, 3, 1)

        layout.addWidget(
            QLabel(_("<font color='red'>This will overwrite any Coinapult API keys in your wallet.<br>"
                     "If you do not have backups of your API keys, this will lock you out of your "  # TODO This isn't actually stored in the wallet yet...
                     "account!</font>")), 4, 0)

        self.ca_ok_button = QPushButton(_("OK"))
        self.ca_ok_button.clicked.connect(ok_clicked)
        layout.addWidget(self.ca_ok_button, 5, 1)

        if d.exec_():
            return True
        else:
            return False
    def __init__(self):
        super().__init__()
        gui.label(self.controlArea, self, "from pandas:")
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.allSQLSelectWidgets.append(self)  # set default settings
        self.domain = None
        self.recentConnections = list()
        self.recentConnections.append("(none)")

        self.queryFile = None
        self.query = ''
        self.lastQuery = None
        if self.lastQuery is not None:
            self.query = self.lastQuery

        sources = pyodbc.dataSources()
        dsns = list(sources.keys())
        dsns.sort()

        for dsn in dsns:
            self.recentConnections.append("DSN={dsn}".format(dsn=dsn))

        self.connectString = self.recentConnections[0]

        self.connectBox = gui.widgetBox(self.controlArea, "Database")

        self.connectLineEdit = gui.lineEdit(self.connectBox,
                                            self,
                                            'connectString',
                                            callback=None)
        self.connectCombo = gui.comboBox(self.connectBox,
                                         self,
                                         'connectString',
                                         items=self.recentConnections,
                                         valueType=str,
                                         sendSelectedValue=True)
        self.button = gui.button(self.connectBox,
                                 self,
                                 'connect',
                                 callback=self.connectDB,
                                 disabled=0)
        # query
        self.splitCanvas = QSplitter(QtCore.Qt.Vertical, self.mainArea)
        self.mainArea.layout().addWidget(self.splitCanvas)

        self.textBox = gui.widgetBox(self, 'HiveQL')
        self.splitCanvas.addWidget(self.textBox)
        self.queryTextEdit = QPlainTextEdit(self.query, self)
        self.textBox.layout().addWidget(self.queryTextEdit)

        self.selectBox = gui.widgetBox(self.controlArea, "Select statement")
        # self.selectSubmitBox = QHGroupBox("", self.selectBox)
        # self.queryTextEdit.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
        # self.queryTextEdit.setMinimumWidth(300)
        # self.connect(self.queryTextEdit, SIGNAL('returnPressed()'), self.executeQuery)
        gui.button(self.selectBox, self, "Open...", callback=self.openScript)
        gui.button(self.selectBox, self, "Save...", callback=self.saveScript)
        self.selectBox.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        gui.button(self.selectBox,
                   self,
                   'format SQL!',
                   callback=self.format_sql,
                   disabled=0)
        gui.button(self.selectBox,
                   self,
                   'execute!',
                   callback=self.executeQuery,
                   disabled=0)
        self.domainBox = gui.widgetBox(self.controlArea, "Domain")
        self.domainLabel = gui.label(self.domainBox, self, '')
        # info
        self.infoBox = gui.widgetBox(self.controlArea, "Info")
        self.info = []
        self.info.append(gui.label(self.infoBox, self, 'No data loaded.'))
        self.info.append(gui.label(self.infoBox, self, ''))
        self.resize(300, 300)

        self.cnxn = None
Exemple #40
0
 def mouseReleaseEvent(self, event):
     QPlainTextEdit.mouseReleaseEvent(self, event)
     if event.button() == Qt.LeftButton:
         self.highlight_selected_word()
Exemple #41
0
 def __init__(self, parent):
     QPlainTextEdit.__init__(self, parent)
     self.highlighter = QtScriptHighlighter(self)
Exemple #42
0
class PrjDlg(QDialog):
    """
    A dialog for adding new project.
    """
    def __init__(self, mc, iw):
        """
        Constructor.

        :param mc: A reference to the main class.
        :type mc: object
        :param iw: A reference to the insert window.
        :type iw: QMainWindow
        """

        super(QDialog, self).__init__()

        self.mc = mc
        self.iw = iw

        self._setup_self()

    def _setup_self(self):
        """
        Sets up self.
        """

        self.setObjectName(u'PrjDlg')

        self.setSizePolicy(QSizePolicy.Minimum, QSizePolicy.Minimum)
        self.setWindowTitle(u'Add Project')

        self.grid_lyt = QGridLayout(self)
        self.grid_lyt.setObjectName(u'grid_lyt')
        self.grid_lyt.setColumnMinimumWidth(1, 300)

        self._build_wdgs()

    def _build_wdgs(self):
        """
        Builds own widgets.
        """

        self.org_lbl = QLabel(self)
        self.org_lbl.setObjectName(u'org_lbl')
        self.org_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.org_lbl.setText(u'organization')
        self.grid_lyt.addWidget(self.org_lbl, 0, 0, 1, 1)

        self.org_cb = QComboBox(self)
        self.org_cb.setObjectName(u'org_cb')
        self.grid_lyt.addWidget(self.org_cb, 0, 1, 1, 1)

        self.no_lbl = QLabel(self)
        self.no_lbl.setObjectName(u'no_lbl')
        self.no_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.no_lbl.setText(u'projectNumber')
        self.grid_lyt.addWidget(self.no_lbl, 1, 0, 1, 1)

        self.no_le = QLineEdit(self)
        self.no_le.setObjectName(u'no_le')
        self.grid_lyt.addWidget(self.no_le, 1, 1, 1, 1)

        self.name_lbl = QLabel(self)
        self.name_lbl.setObjectName(u'name_lbl')
        self.name_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.name_lbl.setText(u'projectName')
        self.grid_lyt.addWidget(self.name_lbl, 2, 0, 1, 1)

        self.name_le = QLineEdit(self)
        self.name_le.setObjectName(u'name_le')
        self.grid_lyt.addWidget(self.name_le, 2, 1, 1, 1)

        self.styr_lbl = QLabel(self)
        self.styr_lbl.setObjectName(u'styr_lbl')
        self.styr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.styr_lbl.setText(u'startYear')
        self.grid_lyt.addWidget(self.styr_lbl, 3, 0, 1, 1)

        self.styr_mde = de.MtyDe(self)
        self.styr_mde.setObjectName(u'styr_mde')
        self.styr_mde.setDisplayFormat('yyyy')
        self.grid_lyt.addWidget(self.styr_mde, 3, 1, 1, 1)

        self.endyr_lbl = QLabel(self)
        self.endyr_lbl.setObjectName(u'endyr_lbl')
        self.endyr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.endyr_lbl.setText(u'endYear')
        self.grid_lyt.addWidget(self.endyr_lbl, 4, 0, 1, 1)

        self.endyr_mde = de.MtyDe(self)
        self.endyr_mde.setObjectName(u'endyr_mde')
        self.endyr_mde.setDisplayFormat('yyyy')
        self.grid_lyt.addWidget(self.endyr_mde, 4, 1, 1, 1)

        self.ldr_lbl = QLabel(self)
        self.ldr_lbl.setObjectName(u'ldr_lbl')
        self.ldr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.ldr_lbl.setText(u'projectLeader')
        self.grid_lyt.addWidget(self.ldr_lbl, 5, 0, 1, 1)

        self.ldr_le = QLineEdit(self)
        self.ldr_le.setObjectName(u'ldr_le')
        self.grid_lyt.addWidget(self.ldr_le, 5, 1, 1, 1)

        self.mbr_lbl = QLabel(self)
        self.mbr_lbl.setObjectName(u'mbr_lbl')
        self.mbr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.mbr_lbl.setText(u'projectMembers')
        self.grid_lyt.addWidget(self.mbr_lbl, 6, 0, 1, 1)

        self.mbr_pte = QPlainTextEdit(self)
        self.mbr_pte.setObjectName(u'mbr_pte')
        self.grid_lyt.addWidget(self.mbr_pte, 6, 1, 1, 1)

        self.fncr_lbl = QLabel(self)
        self.fncr_lbl.setObjectName(u'fncr_lbl')
        self.fncr_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.fncr_lbl.setText(u'financer')
        self.grid_lyt.addWidget(self.fncr_lbl, 7, 0, 1, 1)

        self.fncr_le = QLineEdit(self)
        self.fncr_le.setObjectName(u'fncr_le')
        self.grid_lyt.addWidget(self.fncr_le, 7, 1, 1, 1)

        self.rmk_lbl = QLabel(self)
        self.rmk_lbl.setObjectName(u'rmk_lbl')
        self.rmk_lbl.setAlignment(Qt.AlignRight | Qt.AlignVCenter)
        self.rmk_lbl.setText(u'remarks')
        self.grid_lyt.addWidget(self.rmk_lbl, 8, 0, 1, 1)

        self.rmk_pte = QPlainTextEdit(self)
        self.rmk_pte.setObjectName(u'rmk_pte')
        self.grid_lyt.addWidget(self.rmk_pte, 8, 1, 1, 1)

        self.mand_wdgs = [
            self.org_cb, self.no_le, self.name_le, self.styr_mde, self.ldr_le,
            self.fncr_le
        ]

        self.iw.set_mand_wdgs(self.mand_wdgs)

        # temporary workaround
        self.no_le.setValidator(
            vald.LenIntVald(self.no_le, -2147483648, 2147483647))

        self._fetch_prj_data()

        # to keep order
        self.input_wdgs = [
            self.org_cb, self.no_le, self.name_le, self.styr_mde,
            self.endyr_mde, self.ldr_le, self.mbr_pte, self.fncr_le,
            self.rmk_pte
        ]

        self.btn_lyt = QHBoxLayout()
        self.grid_lyt.addLayout(self.btn_lyt, 9, 1, 1, 1)

        self.sv_btn = QPushButton(self)
        self.sv_btn.setObjectName(u'sv_btn')
        self.sv_btn.setText(u'Save')
        self.sv_btn.clicked.connect(self._save_prj)
        self.btn_lyt.addWidget(self.sv_btn)

        self.cl_btn = QPushButton(self)
        self.cl_btn.setObjectName(u'ok_btn')
        self.cl_btn.setText(u'Close')
        self.cl_btn.clicked.connect(self.close)
        self.btn_lyt.addWidget(self.cl_btn)

    def _fetch_prj_data(self):
        """
        Fetches data from the NOFA database and populates widgets.
        """

        self.iw.pop_cb(self._prj_cb_dict)

    @property
    def _prj_cb_dict(self):
        """
        Returns a project combo box dictionary.

        :returns:
         | A project combo box dictionary:
         |    - key - combo_box_name
         |    - value - [<fill method>, [<arguments>], <default value>]
        :rtype: dict
        """

        dtst_cb_dict = {
            self.org_cb: [db.get_inst_list, [self.mc.con], self.iw.sel_str]
        }

        return dtst_cb_dict

    def _save_prj(self):
        """
        Saves a project into the database.
        """

        try:
            self.iw.chck_mand_wdgs(self.mand_wdgs, exc.MandNotFldExc)

            prj_list = self.iw.get_wdg_list(self.input_wdgs)

            # temporary fix
            for i in range(3, 5):
                try:
                    prj_list[i] = prj_list[i].year
                except:
                    pass

            id = db.ins_prj(self.mc.con, prj_list)

            db.ins_prj_log(self.mc.con, id, self.mc.con_info[self.mc.usr_str])

            self.iw.pop_prj_cb()
            self.iw.upd_prj(db.get_prj_str(prj_list[2], prj_list[0]))

            QMessageBox.information(self, u'Saved', u'Project saved.')
        except exc.MandNotFldExc as e:
            e.wdg.setFocus()
            QMessageBox.warning(self, u'Mandatory Fields',
                                u'Fill/select all mandatory fields.')
    def __init__(self, parent):
        super(ProjectExecution, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)

        grid.addWidget(QLabel(self.tr("Main File:")), 0, 0)
        self.path = QLineEdit()
        ui_tools.LineEditButton(
            self.path, self.path.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.path.setText(self._parent._item.mainFile)
        self.path.setReadOnly(True)
        self.btnBrowse = QPushButton(
            QIcon(self.style().standardPixmap(self.style().SP_FileIcon)), '')
        grid.addWidget(self.path, 0, 1)
        grid.addWidget(self.btnBrowse, 0, 2)

        # this should be changed, and ALL pythonPath names to
        # python_custom_interpreter or something like that. this is NOT the
        # PYTHONPATH
        self.txtPythonPath = QLineEdit()
        self.txtPythonPath.setText(self._parent._item.pythonPath)
        self.btnPythonPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Python Custom Interpreter:")), 1, 0)
        grid.addWidget(self.txtPythonPath, 1, 1)
        grid.addWidget(self.btnPythonPath, 1, 2)

        # THIS IS THE MODAFUCKA REAL PYTHONPATH BRO, YEAH !!!
        grid.addWidget(QLabel(self.tr("Custom PYTHONPATH:")), 2, 0)
        self.PYTHONPATH = QPlainTextEdit()  # TODO : better widget
        self.PYTHONPATH.setPlainText(self._parent._item.PYTHONPATH)
        self.PYTHONPATH.setToolTip(self.tr("One path per line"))
        grid.addWidget(self.PYTHONPATH, 2, 1)

        # Additional builtins/globals for pyflakes
        grid.addWidget(QLabel(self.tr("Additional builtins/globals:")), 3, 0)
        self.additional_builtins = QLineEdit()
        self.additional_builtins.setText(' '.join(
            self._parent._item.additional_builtins))
        self.additional_builtins.setToolTip(
            self.tr(
                "Space-separated list of symbols that will be considered as "
                "builtin in every file"))
        grid.addWidget(self.additional_builtins, 3, 1)

        self.txtPreExec = QLineEdit()
        ui_tools.LineEditButton(
            self.txtPreExec, self.txtPreExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPreExec.setReadOnly(True)
        self.txtPreExec.setText(self._parent._item.preExecScript)
        self.btnPreExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Pre-exec Script:")), 4, 0)
        grid.addWidget(self.txtPreExec, 4, 1)
        grid.addWidget(self.btnPreExec, 4, 2)
        self.txtPostExec = QLineEdit()
        ui_tools.LineEditButton(
            self.txtPostExec, self.txtPostExec.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtPostExec.setReadOnly(True)
        self.txtPostExec.setText(self._parent._item.postExecScript)
        self.btnPostExec = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Post-exec Script:")), 5, 0)
        grid.addWidget(self.txtPostExec, 5, 1)
        grid.addWidget(self.btnPostExec, 5, 2)

        grid.addItem(
            QSpacerItem(5, 10, QSizePolicy.Expanding, QSizePolicy.Expanding),
            6, 0)

        # Properties
        grid.addWidget(QLabel(self.tr("Properties:")), 7, 0)
        self.txtParams = QLineEdit()
        self.txtParams.setToolTip(
            self.tr("Separate the params with commas (ie: help, verbose)"))
        self.txtParams.setText(self._parent._item.programParams)
        grid.addWidget(QLabel(self.tr("Params (comma separated):")), 8, 0)
        grid.addWidget(self.txtParams, 8, 1)
        #Widgets for virtualenv properties
        self.txtVenvPath = QLineEdit()
        ui_tools.LineEditButton(
            self.txtVenvPath, self.txtVenvPath.clear,
            self.style().standardPixmap(self.style().SP_TrashIcon))
        self.txtVenvPath.setText(self._parent._item.venv)
        self._dir_completer = QCompleter()
        self._dir_completer.setModel(QDirModel(self._dir_completer))
        self.txtVenvPath.setCompleter(self._dir_completer)
        self.btnVenvPath = QPushButton(QIcon(resources.IMAGES['open']), '')
        grid.addWidget(QLabel(self.tr("Virtualenv Folder:")), 9, 0)
        grid.addWidget(self.txtVenvPath, 9, 1)
        grid.addWidget(self.btnVenvPath, 9, 2)

        self.connect(self.btnBrowse, SIGNAL("clicked()"), self.select_file)
        self.connect(self.btnPythonPath, SIGNAL("clicked()"),
                     self._load_python_path)
        self.connect(self.btnVenvPath, SIGNAL("clicked()"),
                     self._load_python_venv)
        self.connect(self.btnPreExec, SIGNAL("clicked()"),
                     self.select_pre_exec_script)
        self.connect(self.btnPostExec, SIGNAL("clicked()"),
                     self.select_post_exec_script)
Exemple #44
0
 def resizeEvent(self, event):
     QPlainTextEdit.resizeEvent(self, event)
     self._sidebarWidget.setFixedHeight(self.height())
     if self._mini:
         self._mini.adjust_to_parent()
    def __init__(self, parent):
        super(ProjectData, self).__init__()
        self._parent = parent
        grid = QGridLayout(self)
        grid.addWidget(QLabel(self.tr("Name:")), 0, 0)
        self.name = QLineEdit()
        if self._parent._item.name == '':
            self.name.setText(
                file_manager.get_basename(self._parent._item.path))
        else:
            self.name.setText(self._parent._item.name)
        grid.addWidget(self.name, 0, 1)
        grid.addWidget(QLabel(self.tr("Project Location:")), 1, 0)
        self.txtPath = QLineEdit()
        self.txtPath.setReadOnly(True)
        self.txtPath.setText(self._parent._item.path)
        grid.addWidget(self.txtPath, 1, 1)
        grid.addWidget(QLabel(self.tr("Project Type:")), 2, 0)
        self.txtType = QLineEdit()
        completer = QCompleter(sorted(settings.PROJECT_TYPES))
        completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion)
        self.txtType.setCompleter(completer)
        self.txtType.setText(self._parent._item.projectType)
        grid.addWidget(self.txtType, 2, 1)
        grid.addWidget(QLabel(self.tr("Description:")), 3, 0)
        self.description = QPlainTextEdit()
        self.description.setPlainText(self._parent._item.description)
        grid.addWidget(self.description, 3, 1)
        grid.addWidget(QLabel(self.tr("URL:")), 4, 0)
        self.url = QLineEdit()
        self.url.setText(self._parent._item.url)
        grid.addWidget(self.url, 4, 1)
        grid.addWidget(QLabel(self.tr("Licence:")), 5, 0)
        self.cboLicense = QComboBox()
        self.cboLicense.addItem('Apache License 2.0')
        self.cboLicense.addItem('Artistic License/GPL')
        self.cboLicense.addItem('Eclipse Public License 1.0')
        self.cboLicense.addItem('GNU General Public License v2')
        self.cboLicense.addItem('GNU General Public License v3')
        self.cboLicense.addItem('GNU Lesser General Public License')
        self.cboLicense.addItem('MIT License')
        self.cboLicense.addItem('Mozilla Public License 1.1')
        self.cboLicense.addItem('Mozilla Public License 2.0')
        self.cboLicense.addItem('New BSD License')
        self.cboLicense.addItem('Other Open Source')
        self.cboLicense.addItem('Other')
        self.cboLicense.setCurrentIndex(4)
        index = self.cboLicense.findText(self._parent._item.license)
        self.cboLicense.setCurrentIndex(index)
        grid.addWidget(self.cboLicense, 5, 1)

        self.txtExtensions = QLineEdit()
        self.txtExtensions.setText(', '.join(self._parent._item.extensions))
        grid.addWidget(QLabel(self.tr("Supported Extensions:")), 6, 0)
        grid.addWidget(self.txtExtensions, 6, 1)

        grid.addWidget(QLabel(self.tr("Indentation: ")), 7, 0)
        self.spinIndentation = QSpinBox()
        self.spinIndentation.setValue(self._parent._item.indentation)
        self.spinIndentation.setMinimum(1)
        grid.addWidget(self.spinIndentation, 7, 1)
        self.checkUseTabs = QCheckBox(self.tr("Use Tabs."))
        self.checkUseTabs.setChecked(self._parent._item.useTabs)
        grid.addWidget(self.checkUseTabs, 7, 2)
Exemple #46
0
 def resizeEvent(self, event):
     QPlainTextEdit.resizeEvent(self, event)
     self._sidebarWidget.setFixedHeight(self.height())
Exemple #47
0
    from PyQt4.QtGui import (QApplication, QPlainTextEdit, QFileDialog,
                             QMainWindow)
    import pqIMC
    app = QApplication(sys.argv)  # create an app
    IMC = pqIMC.tricorder()  # create inter-module communicator
    pqMsgs.IMC = IMC
    IMC.bookType = QString(u"html")
    M = QMainWindow()
    pqMsgs.makeBarIn(M.statusBar())
    utname = QFileDialog.getOpenFileName(M, "UNIT TEST DATA FOR FLOW", ".")
    utfile = QFile(utname)
    if not utfile.open(QIODevice.ReadOnly):
        raise IOError, unicode(utfile.errorString())
    utinfo = QFileInfo(utfile)
    IMC.bookDirPath = utinfo.absolutePath()
    utstream = QTextStream(utfile)
    utstream.setCodec("UTF-8")
    utqs = utstream.readAll()
    IMC.editWidget = QPlainTextEdit()
    IMC.editWidget.setPlainText(utqs)
    IMC.editWidget.show()
    W = htmlPreview()
    M.setCentralWidget(W)
    M.show()
    W.docWillChange()
    W.docHasChanged()
    #t = unicode(W.getSimpleText())
    #print(t)
    #W.doneWithText()
    app.exec_()
class OWSparkDataFrame(SharedSparkContext, OWWidget):
    priority = 2
    allSQLSelectWidgets = []
    settingsList = ["lastQuery"]
    name = "DataFrame"
    description = "Create a Spark Dataframe from an SparkSQL source"
    icon = "../icons/sql.png"

    outputs = [("DataFrame", pyspark.sql.DataFrame, widget.Dynamic)]
    out_df = None
    settingsHandler = settings.DomainContextHandler()

    def __init__(self):
        super().__init__()
        gui.label(self.controlArea, self, "Spark DataFrame")
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.allSQLSelectWidgets.append(self)  # set default settings
        self.domain = None

        self.queryFile = None
        self.query = ''
        self.lastQuery = None
        # self.loadSettings()
        if self.lastQuery is not None:
            self.query = self.lastQuery

        # query
        self.splitCanvas = QSplitter(QtCore.Qt.Vertical, self.mainArea)
        self.mainArea.layout().addWidget(self.splitCanvas)

        self.textBox = gui.widgetBox(self, 'SparkSQL')
        self.splitCanvas.addWidget(self.textBox)
        self.queryTextEdit = QPlainTextEdit(self.query, self)
        self.textBox.layout().addWidget(self.queryTextEdit)

        self.selectBox = gui.widgetBox(self.controlArea, "Select statement")
        self.selectBox.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        gui.button(self.selectBox,
                   self,
                   'format SQL!',
                   callback=self.format_sql,
                   disabled=0)
        gui.button(self.selectBox,
                   self,
                   'execute!',
                   callback=self.executeQuery,
                   disabled=0)

        # info
        self.infoBox = gui.widgetBox(self.controlArea, "Info")
        self.info = []
        self.info.append(gui.label(self.infoBox, self, 'No data loaded.'))
        self.info.append(gui.label(self.infoBox, self, ''))
        self.resize(300, 300)

    def destroy(self, destroyWindow, destroySubWindows):
        self.allSQLSelectWidgets.remove(self)
        self.destroy(self, destroyWindow, destroySubWindows)

    def activateLoadedSettings(self):
        self.query = self.lastQuery

    def setInfo(self, info):
        pass
        # for (i, s) in enumerate(info):
        #    self.info[i].setText(s)

    def setMeta(self):
        pass
        # domain = self.data.domain
        # s = "Attrs:\n    " + "\n    ".join([str(i) for i in domain.attributes]) + "\n" + "Class:" + str(domain.classVar)
        # self.domainLabel.setText(s)
        # for i in domain.getmetas():
        # self.propertyCheckBoxes[i].set()

    # Execute a query, create data from it and send it over the data channel
    def executeQuery(self):
        if not self.sc or not self.hc:
            return

        query = self.queryTextEdit.toPlainText()

        if query is None:
            return None

        self.out_df = self.hc.sql(query)
        self.send("DataFrame", self.out_df)
        self.lastQuery = query

    def format_sql(self):
        query = str(self.queryTextEdit.toPlainText())
        str_sql = str(format_sql(query))
        self.queryTextEdit.clear()
        self.queryTextEdit.insertPlainText(str_sql)
Exemple #49
0
class SkinsTab(QWidget):
    def __init__(self):
        QWidget.__init__(self)
        vbox = QVBoxLayout(self)

        #Top Bar
        hbox = QHBoxLayout()
        self.radioDefault = QRadioButton("Default Skin")
        self.radioCustom = QRadioButton("Custom")
        self.comboSkins = QComboBox()
        self.skins = loader.load_gui_skins()
        for item in self.skins:
            self.comboSkins.addItem(item)
        hbox.addWidget(self.radioDefault)
        hbox.addWidget(self.radioCustom)
        hbox.addWidget(self.comboSkins)
        #Text Area
        self.txtStyle = QPlainTextEdit()
        self.txtStyle.setReadOnly(True)

        #Settings
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        if settings.value('default', True).toBool():
            self.radioDefault.setChecked(True)
            self.comboSkins.setEnabled(False)
        else:
            self.radioCustom.setChecked(True)
            index = self.comboSkins.findText(
                settings.value('selectedSkin', '').toString())
            self.comboSkins.setCurrentIndex(index)
            content = self.skins[str(self.comboSkins.currentText())]
            self.txtStyle.setPlainText(content)
        settings.endGroup()
        settings.endGroup()

        vbox.addLayout(hbox)
        vbox.addWidget(self.txtStyle)
        vbox.addWidget(QLabel('Requires restart the IDE'))

        #Signals
        self.connect(self.radioDefault, SIGNAL("clicked()"),
                     self._default_clicked)
        self.connect(self.radioCustom, SIGNAL("clicked()"),
                     self._custom_clicked)

    def _default_clicked(self):
        self.comboSkins.setEnabled(False)
        self.txtStyle.setPlainText('')

    def _custom_clicked(self):
        self.comboSkins.setEnabled(True)
        content = self.skins[str(self.comboSkins.currentText())]
        self.txtStyle.setPlainText(content)

    def save(self):
        settings = QSettings()
        settings.beginGroup('preferences')
        settings.beginGroup('skins')
        settings.setValue('default', self.radioDefault.isChecked())
        settings.setValue('selectedSkin', self.comboSkins.currentText())
        settings.endGroup()
        settings.endGroup()
Exemple #50
0
 def resizeEvent(self, event):
     self._create_line()
     QPlainTextEdit.resizeEvent(self, event)
    def __init__(self, parent=None):
        super(TalkDetailsWidget, self).__init__(parent)

        self.layout = QGridLayout()
        self.setLayout(self.layout)

        self.buttonLayout = QHBoxLayout()

        saveIcon = QIcon.fromTheme("document-save")
        self.saveButton = QPushButton('Save Talk')
        self.saveButton.setIcon(saveIcon)
        self.buttonLayout.addWidget(self.saveButton)

        self.layout.addLayout(self.buttonLayout, 0, 1, 1, 1)

        self.titleLabel = QLabel('Title')
        self.titleLineEdit = QLineEdit()
        self.presenterLabel = QLabel('Presenter')
        self.presenterLineEdit = QLineEdit()
        self.layout.addWidget(self.titleLabel, 1, 0, 1, 1)
        self.layout.addWidget(self.titleLineEdit, 1, 1, 1, 1)
        self.layout.addWidget(self.presenterLabel, 1, 2, 1, 1)
        self.layout.addWidget(self.presenterLineEdit, 1, 3, 1, 1)

        self.eventLabel = QLabel('Event')
        self.eventLineEdit = QLineEdit()
        self.categoryLabel = QLabel('Category')
        self.categoryLineEdit = QLineEdit()

        self.layout.addWidget(self.eventLabel, 2, 0, 1, 1)
        self.layout.addWidget(self.eventLineEdit, 2, 1, 1, 1)
        self.layout.addWidget(self.categoryLabel, 2, 2, 1, 1)
        self.layout.addWidget(self.categoryLineEdit, 2, 3, 1, 1)

        self.roomLabel = QLabel('Room')
        self.roomLineEdit = QLineEdit()
        self.dateLayout = QHBoxLayout()
        self.dateLabel = QLabel('Date')
        self.dateEdit = QDateEdit()
        currentDate = QDate()
        self.dateEdit.setDate(currentDate.currentDate())
        self.dateEdit.setCalendarPopup(True)

        self.layout.addWidget(self.roomLabel, 3, 0, 1, 1)
        self.layout.addWidget(self.roomLineEdit, 3, 1, 1, 1)
        self.dateLayout.addWidget(self.dateEdit)
        self.layout.addWidget(self.dateLabel, 3, 2, 1, 1)
        self.layout.addLayout(self.dateLayout, 3, 3, 1, 1)

        self.startTimeLayout = QHBoxLayout()
        self.startTimeLabel = QLabel('Start Time')
        self.startTimeEdit = QTimeEdit()
        self.startTimeLayout.addWidget(self.startTimeEdit)
        self.endTimeLayout = QHBoxLayout()
        self.endTimeLabel = QLabel('End Time')
        self.endTimeEdit = QTimeEdit()
        self.endTimeLayout.addWidget(self.endTimeEdit)

        self.layout.addWidget(self.startTimeLabel, 4, 0, 1, 1)
        self.layout.addLayout(self.startTimeLayout, 4, 1, 1, 1)
        self.layout.addWidget(self.endTimeLabel, 4, 2, 1, 1)
        self.layout.addLayout(self.endTimeLayout, 4, 3, 1, 1)

        self.descriptionLabel = QLabel('Description')
        self.descriptionLabel.setAlignment(Qt.AlignTop)
        self.descriptionTextEdit = QPlainTextEdit()
        self.layout.addWidget(self.descriptionLabel, 5, 0, 1, 1)
        self.layout.addWidget(self.descriptionTextEdit, 5, 1, 1, 3)
Exemple #52
0
    def keyPressEvent(self, event):
        if self.completer.popup().isVisible():
            if event.key() in (Qt.Key_Enter, Qt.Key_Return, Qt.Key_Tab):
                event.ignore()
                self.completer.popup().hide()
                return
            elif event.key in (Qt.Key_Space, Qt.Key_Escape, Qt.Key_Backtab):
                self.completer.popup().hide()
        if event.key() in (Qt.Key_Enter, Qt.Key_Return):
            self._write_command()
            return
        if self._get_cursor_position() < 0:
            self.setCursorPosition(0)
        if event.key() == Qt.Key_Tab:
            self.textCursor().insertText(' ' * settings.INDENT)
            return
        if event.key() == Qt.Key_Home:
            if event.modifiers() == Qt.ShiftModifier:
                self.setCursorPosition(0, QTextCursor.KeepAnchor)
            else:
                self.setCursorPosition(0)
            return
        if event.key() == Qt.Key_PageUp:
            return
        elif event.key() == Qt.Key_Left and self._get_cursor_position() == 0:
            return
        elif event.key() == Qt.Key_Up:
            self._set_command(self._get_prev_history_entry())
            return
        elif event.key() == Qt.Key_Down:
            self._set_command(self._get_next_history_entry())
            return

        if event.key() == Qt.Key_Tab:
            if self.textCursor().hasSelection():
                self.indent_more()
                return
            else:
                self.textCursor().insertText(' ' * settings.INDENT)
                return
        elif event.key() == Qt.Key_Backspace:
            if self.textCursor().hasSelection():
                QPlainTextEdit.keyPressEvent(self, event)
                return
            elif self._get_cursor_position() == 0:
                return
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor,
                                settings.INDENT)
            text = unicode(cursor.selection().toPlainText())
            if text == ' ' * settings.INDENT:
                cursor.removeSelectedText()
                return True
        elif event.key() == Qt.Key_Home:
            if event.modifiers() == Qt.ShiftModifier:
                move = QTextCursor.KeepAnchor
            else:
                move = QTextCursor.MoveAnchor
            if self.textCursor().atBlockStart():
                self.moveCursor(QTextCursor.WordRight, move)
                return
        elif event.key() in (Qt.Key_Enter, Qt.Key_Return) and \
          event.modifiers() == Qt.ShiftModifier:
            return
        elif unicode(event.text()) in \
        (set(BRACES.values()) - set(["'", '"'])):
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.Left, QTextCursor.KeepAnchor)
            brace = unicode(cursor.selection().toPlainText())
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor)
            braceClose = unicode(cursor.selection().toPlainText())
            if BRACES.get(brace, False) == unicode(event.text()) and \
              braceClose == unicode(event.text()):
                self.moveCursor(QTextCursor.Right)
                return
        selection = self.textCursor().selectedText()

        QPlainTextEdit.keyPressEvent(self, event)

        if unicode(event.text()) in BRACES:
            cursor = self.textCursor()
            cursor.movePosition(QTextCursor.StartOfLine,
                                QTextCursor.KeepAnchor)
            self.textCursor().insertText(BRACES[unicode(event.text())])
            self.moveCursor(QTextCursor.Left)
            self.textCursor().insertText(selection)
        completionPrefix = self._text_under_cursor()
        if completionPrefix.contains(self.okPrefix):
            completionPrefix = completionPrefix.remove(self.okPrefix)
        if event.key() == Qt.Key_Period or (event.key() == Qt.Key_Space and \
        event.modifiers() == Qt.ControlModifier):
            self.completer.setCompletionPrefix(completionPrefix)
            self._resolve_completion_argument()
        elif event.key() == Qt.Key_Space and \
        self.completer.popup().isVisible():
            self.completer.popup().hide()
        if self.completer.popup().isVisible() and \
        completionPrefix != self.completer.completionPrefix():
            self.completer.setCompletionPrefix(completionPrefix)
            self.completer.popup().setCurrentIndex(
                self.completer.completionModel().index(0, 0))
            self.completer.setCurrentRow(0)
            self._resolve_completion_argument()
Exemple #53
0
 def keyReleaseEvent(self, event):
     if event.key() == Qt.Key_Control:
         self.highlight_current_line()
         self.highlight_selected_word()
     QPlainTextEdit.keyReleaseEvent(self, event)
Exemple #54
0
    def __init__(self, parent):
        super(TextLogger, self).__init__()

        self.widget = QPlainTextEdit(parent)
        self.widget.setReadOnly(True)
Exemple #55
0
class MainPage(QWidget):
    """
    """
    def __init__(self, parent):
        """
        """
        super(MainPage, self).__init__()
        self.__core = parent
        
        if DEBUGMODE: self.core().debug().addLogWarning("Debug mode activated")
        self.createWidget()
        
    def core(self):
        """
        """
        return self.__core
        
    def createWidget(self):
        """
        """
        self.inDataEdit = QPlainTextEdit()
        
        exportButton = QPushButton("&Import")
        exportButton.clicked.connect(self.onImport)

        createTsLayout = QHBoxLayout()
        createTsLayout.addWidget(exportButton)
        
        mainLayout = QVBoxLayout()
        mainLayout.addWidget(QLabel("Imported/Exported json data: "))
        mainLayout.addWidget(self.inDataEdit)
        mainLayout.addLayout(createTsLayout)
        
        self.setLayout(mainLayout)
        
    def onReloadSettings(self):
        """
        Called by the core when settings are updated
        """
        pass
        
    def insertData(self, data):
        """
        Called by the core when new data are received
        """
        self.core().debug().addLogSuccess( "new data received: %s" % data)
        self.inDataEdit.setPlainText( "%s" % data)

    def onImport(self):
        """
        Export data
        """
        self.core().debug().addLogSuccess( "exporting data" )
        # import selenium example
        # {
            # "steps": [ 
                        # { "action-name": "OPEN BROWSER", "action-description": "", "action-params": "", "action-value": "https://www.google.fr"},
                        # { "action-name": "CLICK ELEMENT", "action-description": "", "action-params": "id=test", "action-value": ""}
                    # ]                
        # }
        
        # import sikuli example
        # {
            # "steps": [ 
                        # { "action-name": "CLICK ON",  "action-description": "", "image-base64": "iVBORw0KGgoAAAANSUhEUgAAAEgAAAAYCAIAAADWASznAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAASdEVYdFNvZnR3YXJlAEdyZWVuc2hvdF5VCAUAAAK9SURBVFhH3Zhda9NQGMdPk9565Y1XCvsOBkREEEEZCjIYjslATFDxZggKo+CFnyAbG2MX+hn2wpbdbrdt19LKKoTaObRpN0JWF/uWtjk+T3LSppkbZVCxefhdPOd/npfzH11hI1TdpZ+m6dwN+jo62oAFMKLu5vP5XC5HaGwsWDHSxMZs285mMsR+FQ0Z9POMruuk8zIaNmavWpZF2lI0fFBKifUiGj7QWPM5Hz7QWH2G/2c0t1VYaW8LAd1B6sAdVaygfhnQWPUZ/38gtR1jzaB+GdCYOcX3WFFwuBsludpVSqrz4/TEmIxHyPFWafy1cYpvpJngRnvFK0tLgdvOltBfrDQGWXG2xgNkUpnkGXNY19kUMF/GKZg7CdVkc5KvpTBtLbNKqrluldoFjSkJxF6jJ5qb+JlkLQyphXdKzT0OsiJQw+YgcCbGBOfyawOX9cWeaCw5T4FkgqvuYWotccZ7ZyJVquc39or9jd40f0tnQ3AeIFp4YjMHWRGo8QMq0Z9wLpV1bG6vC10FWXSekhQhN5OYNhc5/Z2Mvw+aXDm/sVfsz33TWO4GKmITM8V0JwywIlDjB2Ry/JhjLLiblNOu0hUTIuSnCUybC9zxW2diUTb8Nf2NxprzlDWhr9E3jeGOQoUZY0MGWBGs8QEyKY1zPWadUi/aq0Jp3pkYF+G2Ese0Me+VFWX9gsZx4XeRHd3ARm+avur7aHlzfKJSGWTF2RoPkEnxQWTI3DR/wqKtk6A+RNDYj/uR4SDWYTwL1XwTuB0usJIc3ouEDzR2cDcSMg4fXmm1WuTbnUjIOPo4jX9ofp+4nr9NQgPYsW07k8mQWmqn9OFp4dE19RYZacACGAE77J85X7LZcrlcr/u+w0YzwAIYATtfczlN08hBoZDb30+nUslEIhEfyYBnw+PBAhgBO0fl8olh/AEFAxxb9lhHWwAAAABJRU5ErkJggg==", "opt-c": "0.6" }
                    # ]                
        # }
        
        # import remote-tests
        # supported file PY_EXT, PNG_EXT, TXT_EXT, TEST_UNIT_EXT, TEST_SUITE_EXT, TEST_PLAN_EXT, TEST_GLOBAL_EXT, TEST_CONFIG_EXT, TEST_DATA_EXT
        # content must be encoded in base 64
        # {
            # "files": [ 
                        # { "file-path": "/A/B/test.tux", "content-file": "SGVsbG8gd29ybGQuIEJvbmpvdXIgw6Agdm91cyE="}     
                    # ]                       
        # }
        
        jsonStr = self.inDataEdit.toPlainText()
        try:
            jsonObj = json.loads(jsonStr)
        except Exception as e:
            QMessageBox.warning(self, "Plugin %s" % Settings.instance().readValue( key = 'Plugin/name' ), "Bad json message!" )
          
        if not DEBUGMODE: 
            self.core().sendMessage( cmd='import', data = jsonObj )
            self.core().hide()
Exemple #56
0
class CustomCodeFrame(QFrame):
    poke_code = pyqtSignal(str, int,
                           QByteArray)  # code_set_label, code_id, new_bytes
    log = pyqtSignal(str, str)  # msg, color

    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)

    def setAlternateBGColor(self):
        self.setStyleSheet(
            'CustomCodeFrame { background-color:rgb(248,248,248) }')

    def setErrorBGColor(self):
        self.txt_codes.setStyleSheet('background-color: rgb(255,128,128)')
        self.tmr_reset_bg_clr.start()

    def resetBGColor(self):
        if self.tmr_reset_bg_clr.isActive():
            self.tmr_reset_bg_clr.stop()
            self.txt_codes.setStyleSheet('background-color: white')

    @pyqtSlot()
    def onPoke(self):
        try:
            parse_custom_codes(self.cs, str(self.txt_codes.toPlainText()))
        except SyntaxError, e:
            self.log.emit(str(e), 'red')
            self.setErrorBGColor()
            return

        if len(self.cs.c) <= 0:
            self.log.emit('POKE failed: no codes found', 'red')
            self.setErrorBGColor()
            return

        # Sequentially poke codes
        for code in self.cs.c:
            raw_bytes = struct.pack('>Q', code.dft_value)[-code.num_bytes:]
            self.poke_code.emit(code.label, code.id, QByteArray(raw_bytes))
Exemple #57
0
 def eventFilter(self, object, event):
     if object is self.viewport():
         self.lineNumberArea.update()
         return False
     return QPlainTextEdit.eventFilter(object, event)
Exemple #58
0
 def resizeEvent(self, e):
     self.lineNumberArea.setFixedHeight(self.height())
     QPlainTextEdit.resizeEvent(self, e)
class OWodbcTable(OWWidget):
    priority = 3
    allSQLSelectWidgets = []
    settingsList = ["recentConnections", "lastQuery"]
    name = "ODBC"
    description = "Create a Table from an ODBC datasource"
    icon = "../icons/sql.png"
    inputs = []
    outputs = [("Data", Orange.data.Table, widget.Default),
               ("Feature Definitions", Orange.data.Domain, widget.Default),
               ("Pandas", pd.DataFrame, widget.Default)]

    settingsHandler = settings.DomainContextHandler()

    def __init__(self):
        super().__init__()
        gui.label(self.controlArea, self, "from pandas:")
        self.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.allSQLSelectWidgets.append(self)  # set default settings
        self.domain = None
        self.recentConnections = list()
        self.recentConnections.append("(none)")

        self.queryFile = None
        self.query = ''
        self.lastQuery = None
        if self.lastQuery is not None:
            self.query = self.lastQuery

        sources = pyodbc.dataSources()
        dsns = list(sources.keys())
        dsns.sort()

        for dsn in dsns:
            self.recentConnections.append("DSN={dsn}".format(dsn=dsn))

        self.connectString = self.recentConnections[0]

        self.connectBox = gui.widgetBox(self.controlArea, "Database")

        self.connectLineEdit = gui.lineEdit(self.connectBox,
                                            self,
                                            'connectString',
                                            callback=None)
        self.connectCombo = gui.comboBox(self.connectBox,
                                         self,
                                         'connectString',
                                         items=self.recentConnections,
                                         valueType=str,
                                         sendSelectedValue=True)
        self.button = gui.button(self.connectBox,
                                 self,
                                 'connect',
                                 callback=self.connectDB,
                                 disabled=0)
        # query
        self.splitCanvas = QSplitter(QtCore.Qt.Vertical, self.mainArea)
        self.mainArea.layout().addWidget(self.splitCanvas)

        self.textBox = gui.widgetBox(self, 'HiveQL')
        self.splitCanvas.addWidget(self.textBox)
        self.queryTextEdit = QPlainTextEdit(self.query, self)
        self.textBox.layout().addWidget(self.queryTextEdit)

        self.selectBox = gui.widgetBox(self.controlArea, "Select statement")
        # self.selectSubmitBox = QHGroupBox("", self.selectBox)
        # self.queryTextEdit.setSizePolicy(QSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred))
        # self.queryTextEdit.setMinimumWidth(300)
        # self.connect(self.queryTextEdit, SIGNAL('returnPressed()'), self.executeQuery)
        gui.button(self.selectBox, self, "Open...", callback=self.openScript)
        gui.button(self.selectBox, self, "Save...", callback=self.saveScript)
        self.selectBox.setSizePolicy(
            QSizePolicy(QSizePolicy.MinimumExpanding,
                        QSizePolicy.MinimumExpanding))
        gui.button(self.selectBox,
                   self,
                   'format SQL!',
                   callback=self.format_sql,
                   disabled=0)
        gui.button(self.selectBox,
                   self,
                   'execute!',
                   callback=self.executeQuery,
                   disabled=0)
        self.domainBox = gui.widgetBox(self.controlArea, "Domain")
        self.domainLabel = gui.label(self.domainBox, self, '')
        # info
        self.infoBox = gui.widgetBox(self.controlArea, "Info")
        self.info = []
        self.info.append(gui.label(self.infoBox, self, 'No data loaded.'))
        self.info.append(gui.label(self.infoBox, self, ''))
        self.resize(300, 300)

        self.cnxn = None

    def destroy(self, destroyWindow, destroySubWindows):
        self.allSQLSelectWidgets.remove(self)
        self.destroy(self, destroyWindow, destroySubWindows)

    def activateLoadedSettings(self):
        # print "activating", self.recentQueries, ", ",self.recentConnections
        self.query = self.lastQuery
        self.setConnectionList()

    def selectConnection(self, n):
        if n < len(self.recentConnections):
            name = self.recentConnections[n]
            self.recentConnections.remove(name)
            self.recentConnections.insert(0, name)
        if len(self.recentConnections) > 0:
            self.setConnectionList()
            self.connectDB(self.recentConnections[0])

    def setInfo(self, info):
        for (i, s) in enumerate(info):
            self.info[i].setText(s)

    def setMeta(self):
        domain = self.data.domain
        # s = "Attrs:\n    " + "\n    ".join([str(i) for i in domain.attributes]) + "\n" + "Class:" + str(domain.classVar)
        # self.domainLabel.setText(s)
        # for i in domain.getmetas():
        # self.propertyCheckBoxes[i].set()

    # checks whether any file widget knows of any variable from the current domain
    def attributesOverlap(self, domain):
        for fw in self.allFileWidgets:
            if fw != self and getattr(fw, "dataDomain", None):
                for var in domain:
                    if var in fw.dataDomain:
                        return True
        return False

    # Execute a query, create data from it and send it over the data channel
    def executeQuery(self, query=None, throughReload=0, DK=None, DC=None):

        self.connectDB()
        query = self.queryTextEdit.toPlainText()

        if query is None:
            query = str(self.queryTextEdit.toPlainText())
        # try:
        self.pandas = psql.read_sql_query(query, self.cnxn)
        # except Exception:
        #    self.setInfo(('Query failed:', str('')))
        #    df = pd.DataFrame()

        self.data = convert_dataframe_to_orange(self.pandas)

        self.send("Data", self.data)
        self.send("Pandas", self.pandas)
        self.setInfo(
            ('Query returned', 'Read ' + str(len(self.data)) + ' examples!'))
        self.send("Feature Definitions", self.data.domain)
        self.setMeta()
        self.lastQuery = query

    def format_sql(self):
        query = str(self.queryTextEdit.toPlainText())
        str_sql = str(format_sql(query))
        self.queryTextEdit.clear()
        self.queryTextEdit.insertPlainText(str_sql)

    def connectDB(self):
        if self.connectString is None:
            self.connectString = str(self.connectString)
        if self.connectString in self.recentConnections:
            self.recentConnections.remove(self.connectString)
        self.recentConnections.insert(0, self.connectString)
        print(self.connectString)
        self.cnxn = pyodbc.connect(self.connectString, autocommit=True)

    # set the query combo box
    def setConnectionList(self):
        self.connectCombo.clear()
        if not self.recentConnections:
            self.connectCombo.insertItem("(none)")
        else:
            self.connectLineEdit.setText(self.recentConnections[0])
        for connection in self.recentConnections:
            self.connectCombo.insertItem(connection)
        self.connectCombo.updateGeometry()

    def openScript(self, filename=None):
        if self.queryFile is None:
            self.queryFile = ''
        if filename == None:
            self.queryFile = QFileDialog.getOpenFileName(
                self, 'Open SQL file', self.queryFile,
                'SQL files (*.sql)\nAll files(*.*)')
        else:
            self.queryFile = filename

        if self.queryFile == "": return

        f = open(self.queryFile, 'r')
        self.queryTextEdit.setPlainText(f.read())
        f.close()

    def saveScript(self):
        if self.queryFile is None:
            self.queryFile = ''
        self.queryFile = QFileDialog.getSaveFileName(
            self, 'Save SQL file', self.queryFile,
            'SQL files (*.sql)\nAll files(*.*)')

        if self.queryFile:
            fn = ""
            head, tail = os.path.splitext(self.queryFile)
            if not tail:
                fn = head + ".sql"
            else:
                fn = self.queryFile
            f = open(fn, 'w')
            f.write(self.queryTextEdit.toPlainText())
            f.close()
class LeggerWidget(QDockWidget):
    """Legger Network widget with tree tables, cross section and sideview and
    legger profile selection"""
    # todo:
    #   - category filter on map and tree instead of shortcut
    #   - improve performance 'initial loop tree'

    closingWidget = pyqtSignal()

    def __init__(self, parent=None, iface=None, path_legger_db=None):
        """Constructor."""
        super(LeggerWidget, self).__init__(parent)

        # store arguments
        self.iface = iface
        self.path_legger_db = path_legger_db

        # init parameters
        self.measured_model = ProfileModel()
        self.variant_model = ProfileModel()
        self.legger_model = LeggerTreeModel()
        self.area_model = AreaTreeModel()

        if not path_legger_db:
            messagebar_message("Database selectie", "Selecteer eerst een legger database", level=1)
            raise Exception("Selecteer eerst een legger database")

        # create session (before setup_ui)
        db = LeggerDatabase(
            {'db_path': path_legger_db},
            'spatialite'
        )
        db.create_and_check_fields()
        self.session = db.get_session()
        # todo: request something to test connection and through error message otherwise
        hydro_object_count = self.session.query(HydroObject).count()

        if hydro_object_count == 0:
            messagebar_message("Database selectie", "Database bevat geen hydrovakken", level=1)
            raise Exception("Database bevat geen hydrovakken")

        # initial values
        self.selected_hydrovak = None
        self.active_begroeiings_variant = SHOW_ALL
        self.active_begroeiings_variant_strategy = None

        # setup ui
        self.setup_ui(self)

        self.legger_model.setTreeWidget(self.legger_tree_widget)
        self.area_model.setTreeWidget(self.startpoint_tree_widget)

        self.category_combo.insertItems(0, ['4', '3', '2', '1'])
        self.category_combo.setCurrentIndex(0)
        self.category_filter = 4

        self.begroeiings_varianten = OrderedDict(
            [(SHOW_ALL, 'all'), (PRE_SELECTED, 'pre_selected'), ] +
            [(v.naam, v) for v in self.session.query(BegroeiingsVariant)]
        )

        self.begroeiings_combo.insertItems(
            0, self.begroeiings_varianten.keys())

        self.begroeiings_variant_strategies = OrderedDict((
            ('alleen dit hydrovak', 'only_this_hydrovak'),
            ('alle bovenstroomse hydrovakken', 'all_upstream'),
        ))

        self.begroeiings_strategy_combo.insertItems(0, self.begroeiings_variant_strategies.keys())
        self.begroeiings_strategy_combo.setCurrentIndex(0)

        self.child_selection_strategies = OrderedDict((
            ('gekozen traject tot waarde', 'selected_branch_till_value'),
            ('gekozen traject tot eind', 'selected_branch_till_end'),
            ('alleen dit hydrovak', 'selected_hydrovak'),
            ('bovenstrooms (met zijtakken) tot waarde ', 'upstream_till_value'),
            ('bovenstrooms (met zijtakken) tot eind', 'upstream_till_end'),
        ))

        self.child_selection_strategy_combo.insertItems(0, self.child_selection_strategies.keys())
        self.child_selection_strategy_combo.setCurrentIndex(0)

        # create line layer and add to map
        self.layer_manager = LeggerMapManager(self.iface, self.path_legger_db)

        self.line_layer = self.layer_manager.get_line_layer(add_to_map=True)
        self.vl_tree_layer = self.layer_manager.get_virtual_tree_layer(add_to_map=True)
        self.vl_endpoint_layer = self.layer_manager.get_endpoint_layer(add_to_map=True)
        self.vl_track_layer = self.layer_manager.get_track_layer(add_to_map=True)
        self.vl_hover_layer = self.layer_manager.get_hover_layer(add_to_map=True)
        self.vl_selected_layer = self.layer_manager.get_selected_layer(add_to_map=True)
        self.vl_startpoint_hover_layer = self.layer_manager.get_hover_startpoint_layer(add_to_map=True)

        self.map_visualisation = LeggerMapVisualisation(
            self.iface, self.line_layer.crs())

        # init network
        line_direct = self.layer_manager.get_line_layer(geometry_col='line')
        field_nr = line_direct.fieldNameIndex('direction')
        director = QgsLineVectorLayerDirector(
            line_direct, field_nr, '2', '1', '3', 3)

        self.network = NewNetwork(
            line_direct, self.line_layer, director, None, self.vl_tree_layer, self.vl_endpoint_layer
        )

        # add listeners
        self.category_combo.currentIndexChanged.connect(self.category_change)
        self.variant_model.dataChanged.connect(self.data_changed_variant)
        self.legger_model.dataChanged.connect(self.data_changed_legger_tree)
        self.area_model.dataChanged.connect(self.data_changed_area_model)
        self.show_manual_input_button.clicked.connect(
            self.show_manual_input_window)
        self.next_endpoint_button.clicked.connect(
            self.set_next_endpoint)
        self.begroeiings_combo.currentIndexChanged.connect(self.onSelectBegroeiingsVariant)

        # self.begroeiings_strategy_combo.currentIndexChanged.connect(self.onSelectBegroeiingsVariantStrategy)

        # create and init startpoint (AreaTree) model
        def loop_over(parent, data):
            for child in data['children']:
                area = area_class(child)
                item = AreaTreeItem(area, parent)
                parent.appendChild(item)
                loop_over(item, child)

        # get startingpoints and select first
        sp_tree = self.network.get_start_arc_tree()

        root = AreaTreeItem(None, None)
        loop_over(root, sp_tree)
        self.area_model.setNewTree(root.childs)

        # initial, select first area
        first_area = root.child(0)
        self.area_model.setDataItemKey(first_area, 'selected', True)

    def category_change(self, nr):
        """
        filters the tree and re-initialize legger tree
        nr: nr of selected option (hydrovak category) of combobox
        return: -
        """
        self.category_filter = int(self.category_combo.currentText())
        root = LeggerTreeItem(None, None)
        self.network.get_tree_data(root, self.category_filter)
        self.legger_model.setNewTree(root.childs)
        self.legger_model.set_column_sizes_on_view(self.legger_tree_widget)
        if len(root.childs) > 0:
            self.loop_tree(root.childs[0], initial=True)

    def show_manual_input_window(self):
        self._new_window = NewWindow(
            self.legger_model.selected,
            self.session,
            callback_on_save=self.update_available_profiles)
        self._new_window.show()

    def set_next_endpoint(self):
        """
        select the next endpoint in a traject with no selected variant
        called by the next_endpoint_button

        returns: -
        """
        sp = self.legger_model.sp
        if sp is None:
            messagebar_message('Fout',
                               'Selecteer eerst een startpunt (kolom sp)',
                               level=1,  # Warning
                               duration=15)
            return

        missing_values, endpoint = self.legger_model.find_endpoint_traject_without_legger_profile(sp)
        if not missing_values or endpoint is None:
            messagebar_message('Eindpunt selectie',
                               'Geen traject gevonden met ontbrekende legger',
                               duration=15)
        else:
            self.legger_model.open_till_endpoint(endpoint, close_other=True)
            self.legger_model.setDataItemKey(endpoint, 'ep', True)

    def loop_tree(self,
                  node,
                  depth=None,
                  initial=False,
                  hover=False,
                  begroeiingsvariant=None,
                  variant_id=None,
                  child_strategy='selected_branch_till_value',
                  begroeiings_strategy='pre_selected',
                  traject_nodes=None):
        """
        recursive loop over younger items where depth can be applied according to
        available profiles

        initial (bool): initiele loop om aantal berekende velden te bepalen
        child_strategy (str):
                options:
                   - 'selected_branch_till_value',
                   - 'selected_branch_till_end',
                   - 'selected_hydrovak',
                   - 'upstream_till_value',
                   - 'upstream_till_end'
        begroeiings_strategy (str):
                options:
                    - 'only_this_hydrovak'
                    - 'all_upstream'
                    - 'minimum' --> not implemented yet
                    - 'maximum' --> not implemented yet
        :return:
        """
        output_hydrovakken = [node]
        if initial:
            variant_id = node.hydrovak.get('selected_variant_id')
            depth = node.hydrovak.get('selected_depth')
        elif (variant_id is None and child_strategy in ['selected_branch_till_value', 'upstream_till_value'] and
              node.hydrovak.get('selected_variant_id')):
            # stop here, already value there
            return

        if initial and variant_id is None:
            pass
        elif node.hydrovak['variant_min_depth'] is None:
            # no variants available, so skip this one and continue downstream
            pass
        else:
            # get selected variant. if variant_id is None, try based on depth and begroeiingsvariant
            if variant_id is not None:
                profile_variant = self.session.query(Varianten).filter(Varianten.id == variant_id)
                if begroeiingsvariant is None or begroeiingsvariant == 'all' and profile_variant.count():
                    begroeiingsvariant = profile_variant[0].begroeiingsvariant_id
            else:
                # use given begroeiingsvariant if stategy is all_upstream otherwise use begroeiingsgraad
                # set on hydrovak or the default begroeiingsgraad
                # (correct begroeiingsvariant of first hydrovak is selected by setting variant_id)
                #  "type(begroeiingsvariant) != str" is to filter out setting 'all'
                if begroeiings_strategy == 'all_upstream' and begroeiingsvariant is not None and type(
                        begroeiingsvariant) != str:
                    profile_variant = self.session.query(Varianten).filter(
                        Varianten.hydro_id == node.hydrovak.get('hydro_id'),
                        Varianten.begroeiingsvariant_id == begroeiingsvariant,
                        Varianten.diepte < depth + precision,
                        Varianten.diepte > depth - precision
                    )
                else:
                    profile_variant = self.session.query(Varianten).filter(
                        Varianten.hydro_id == node.hydrovak.get('hydro_id'),
                        or_(Varianten.hydro.has(
                            HydroObject.begroeiingsvariant_id == Varianten.begroeiingsvariant_id),
                            and_(Varianten.hydro.has(HydroObject.begroeiingsvariant_id == None),
                                 Varianten.begroeiingsvariant.has(is_default=True))),
                        Varianten.diepte < depth + precision,
                        Varianten.diepte > depth - precision
                    )

            if profile_variant.count() > 0:

                if hover:
                    # self.legger_model.setDataItemKey(node, 'sel d', depth)
                    self.legger_model.setDataItemKey(node, 'selected_depth_tmp', depth)
                else:
                    # get all info to display in legger table
                    over_depth = node.hydrovak.get('depth') - depth if node.hydrovak.get('depth') is not None else None
                    profilev = profile_variant.first()
                    width = profilev.waterbreedte
                    over_width = node.hydrovak.get('width') - width \
                        if node.hydrovak.get('width') is not None else None

                    figuren = profilev.figuren
                    score = None
                    if len(figuren) > 0:
                        figuur = figuren[0]
                        over_width = "{0:.2f}".format(figuur.t_overbreedte_l + figuur.t_overbreedte_r) \
                            if figuur.t_overbreedte_l is not None else over_width
                        score = "{0:.2f}".format(figuur.t_fit)
                        over_depth = "{0:.2f}".format(
                            figuur.t_overdiepte) if figuur.t_overdiepte is not None else over_depth
                    else:
                        over_depth = "{}*".format(try_round(over_depth, 2, '-'))
                        over_width = "{}*".format(try_round(over_width, 2, '-'))

                    verhang = try_round(profilev.verhang, 1, '-')
                    self.legger_model.setDataItemKey(node, 'selected_depth', depth)
                    self.legger_model.setDataItemKey(node, 'selected_width', width)
                    self.legger_model.setDataItemKey(node, 'selected_variant_id', profilev.id)
                    self.legger_model.setDataItemKey(node, 'selected_begroeiingsvariant_id',
                                                     profilev.begroeiingsvariant_id)
                    self.legger_model.setDataItemKey(node, 'verhang', verhang)
                    self.legger_model.setDataItemKey(node, 'score', score)
                    self.legger_model.setDataItemKey(node, 'over_depth', over_depth)
                    self.legger_model.setDataItemKey(node, 'over_width', over_width)

                    if not initial:
                        # save selected variant
                        selected = self.session.query(GeselecteerdeProfielen).filter(
                            GeselecteerdeProfielen.hydro_id == node.hydrovak.get('hydro_id')).first()
                        if selected:
                            selected.variant = profilev
                        else:
                            selected = GeselecteerdeProfielen(
                                hydro_id=node.hydrovak.get('hydro_id'),
                                variant_id=profilev.id
                            )
                        self.session.add(selected)
            elif not initial:
                # no variant which fits criteria. stop iteration here
                return

        if begroeiings_strategy == 'only_this_hydrovak':
            begroeiingsvariant = None
        elif begroeiings_strategy == 'all_upstream':
            # keep variant as it is
            pass
        # elif begroeiings_strategy == 'minimum':
        #     pass
        # elif begroeiings_strategy == 'maximum':
        #     pass

        if child_strategy == 'selected_hydrovak':
            loop_childs = []
        elif child_strategy in ['upstream_till_value', 'upstream_till_end'] or initial:
            loop_childs = node.younger()
        else:  # 'selected_branch_till_value', 'selected_branch_till_end'
            if traject_nodes is None or len(traject_nodes) == 0:
                loop_childs = []
            else:
                child = traject_nodes.pop(0)
                loop_childs = [child]

        for young in loop_childs:
            hydrovakken = self.loop_tree(
                young,
                depth=depth,
                initial=initial,
                hover=hover,
                begroeiingsvariant=begroeiingsvariant,
                child_strategy=child_strategy,
                begroeiings_strategy=begroeiings_strategy,
                traject_nodes=traject_nodes,
            )
            if hydrovakken is not None:
                output_hydrovakken += hydrovakken

        return output_hydrovakken

    def data_changed_legger_tree(self, index, to_index):
        """
        changes during selection and hover of hydrovak / legger tree
        index (QIndex): index of changed field
        """

        # activate draw
        node = self.legger_model.data(index, role=Qt.UserRole)

        if self.legger_model.columns[index.column()].get('field') == 'hover':
            ids = [feat.id() for feat in self.vl_hover_layer.getFeatures()]
            self.vl_hover_layer.dataProvider().deleteFeatures(ids)

            if node.hydrovak.get('hover'):
                features = []

                feat = QgsFeature()
                feat.setGeometry(node.hydrovak.get('feature').geometry())

                try:
                    feat.setAttributes([
                        node.hydrovak.get('feature')['id']])

                    features.append(feat)
                    self.vl_hover_layer.dataProvider().addFeatures(features)
                except KeyError:
                    pass

            self.vl_hover_layer.commitChanges()
            self.vl_hover_layer.updateExtents()
            self.vl_hover_layer.triggerRepaint()

        elif self.legger_model.columns[index.column()].get('field') == 'selected':
            if self.legger_model.data(index, role=Qt.CheckStateRole) == Qt.Unchecked:
                self.save_remarks()
                self.selected_variant_remark.setPlainText('')
                self.selected_variant_remark.setDisabled(True)

                ids = [feat.id() for feat in self.vl_selected_layer.getFeatures()]
                self.vl_selected_layer.dataProvider().deleteFeatures(ids)

            if node.hydrovak.get('selected'):
                if node.hydrovak.get('tak'):
                    self.legger_model.setDataItemKey(node.younger()[1], 'selected', Qt.Checked)
                else:
                    features = []

                    feat = QgsFeature()
                    feat.setGeometry(node.hydrovak.get('feature').geometry())

                    feat.setAttributes([
                        node.hydrovak.get('feature')['id']])

                    features.append(feat)
                    self.vl_selected_layer.dataProvider().addFeatures(features)

            self.vl_selected_layer.commitChanges()
            self.vl_selected_layer.updateExtents()
            self.vl_selected_layer.triggerRepaint()

            if node.hydrovak.get('tak'):
                pass
            elif node.hydrovak.get('selected'):
                self.on_select_edit_hydrovak(self.legger_model.data(index, role=Qt.UserRole))
                self.show_manual_input_button.setDisabled(False)

            elif (self.legger_model.selected is None or
                  self.legger_model.data(index, role=Qt.UserRole) == self.legger_model.selected):
                self.variant_model.removeRows(0, len(self.variant_model.rows))
                self.show_manual_input_button.setDisabled(True)

        elif self.legger_model.columns[index.column()].get('field') in ['ep', 'sp']:
            # clear current track
            if self.legger_model.sp is None or self.legger_model.ep is None:
                ids = [feat.id() for feat in self.vl_track_layer.getFeatures()]
                self.vl_track_layer.dataProvider().deleteFeatures(ids)
                self.vl_track_layer.commitChanges()
                self.vl_track_layer.triggerRepaint()
            elif node.hydrovak.get('tak'):
                if self.legger_model.columns[index.column()].get('field') == 'ep':
                    self.legger_model.setDataItemKey(node.younger()[1], 'ep', Qt.Checked)
                if self.legger_model.columns[index.column()].get('field') == 'sp':
                    self.legger_model.setDataItemKey(node.younger()[1], 'sp', Qt.Checked)
            elif self.legger_model.sp and self.legger_model.ep:
                features = []

                def loop_rec(node):
                    if node.hydrovak.get('tak'):
                        node = node.older()
                    else:
                        feat = QgsFeature()
                        feat.setGeometry(node.hydrovak.get('feature').geometry())

                        feat.setAttributes([
                            node.hydrovak.get('feature')['id']])

                        features.append(feat)

                    if node != self.legger_model.sp:
                        loop_rec(node.older())

                loop_rec(self.legger_model.ep)

                self.vl_track_layer.dataProvider().addFeatures(features)
                self.vl_track_layer.commitChanges()
                self.vl_track_layer.updateExtents()
                self.vl_track_layer.triggerRepaint()

            if self.legger_model.sp is not None:
                self.next_endpoint_button.setDisabled(False)
            else:
                self.next_endpoint_button.setDisabled(True)

    def data_changed_area_model(self, index, to_index):
        """
        changes during selection and hover of area (start point) table

        index (QIndex): index of changed field
        """

        if self.area_model.columns[index.column()].get('field') == 'selected':
            # clear display elements

            if self.area_model.data(index, role=Qt.CheckStateRole) == Qt.Checked:
                self.variant_model.removeRows(0, len(self.variant_model.rows))
                self.legger_model.set_column_value('hover', False)
                self.legger_model.set_column_value('selected', False)
                self.legger_model.set_column_value('ep', False)
                self.legger_model.set_column_value('sp', False)

                area_item = self.area_model.data(index, role=Qt.UserRole)

                self.network.set_tree_start_arc(area_item.area.get('arc_nr'))

                self.legger_model.clear()

                root = LeggerTreeItem(None, None)
                self.network.get_tree_data(root, self.category_filter)
                self.legger_model.setNewTree(root.childs)
                self.legger_model.set_column_sizes_on_view(self.legger_tree_widget)
                if len(root.childs) > 0:
                    self.loop_tree(root.childs[0], initial=True)

                canvas = self.iface.mapCanvas()
                extent = self.vl_tree_layer.extent()
                if extent:
                    extent.scale(1.2)
                    canvas.setExtent(extent)
        elif self.area_model.columns[index.column()].get('field') == 'hover':
            ids = [feat.id() for feat in self.vl_startpoint_hover_layer.getFeatures()]
            self.vl_startpoint_hover_layer.dataProvider().deleteFeatures(ids)

            value = self.area_model.data(index, role=Qt.DisplayRole)

            if self.area_model.data(index, role=Qt.CheckStateRole) == Qt.Checked:
                features = []

                node = self.area_model.data(index, role=Qt.UserRole)
                feat = QgsFeature()

                feat.setGeometry(QgsGeometry.fromPoint(node.area.get('point')))
                feat.setAttributes([
                    node.area.get('vertex_id')])
                features.append(feat)

                self.vl_startpoint_hover_layer.dataProvider().addFeatures(features)

            self.vl_startpoint_hover_layer.commitChanges()
            self.vl_startpoint_hover_layer.updateExtents()
            self.vl_startpoint_hover_layer.triggerRepaint()

    def data_changed_variant(self, index):
        """
        changes during selection and hover of variant table

        index (QIndex): index of changed field
        """
        item = self.variant_model.rows[index.row()]
        if self.variant_model.columns[index.column()].name == 'active':
            if item.active.value:
                # only one selected at the time
                item.color.value = list(item.color.value)[:3] + [255]
                for row in self.variant_model.rows:
                    if row.active.value and row != item:
                        row.active.value = False

                depth = item.depth.value
                selected_variant_id = item.name.value
                traject = []

                if self.legger_model.ep:
                    traject = self.legger_model.ep.up(self.legger_model.selected)
                    traject.reverse()
                    if len(traject) > 0:
                        traject.pop(0)
                else:
                    messagebar_message(
                        'Traject nodig',
                        'Selecteer eerst een traject (sp en ep) voordat diepte kan worden doorgetrokken.',
                        1,
                        15)
                    return

                self.loop_tree(
                    self.legger_model.selected,
                    depth=depth,
                    initial=False,
                    variant_id=selected_variant_id,
                    begroeiingsvariant=self.get_begroeiings_variant(),
                    child_strategy=self.get_child_selection_strategy(),
                    begroeiings_strategy=self.get_begroeiings_strategy(),
                    traject_nodes=traject
                )
                self.session.commit()
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())
            else:
                item.color.value = list(item.color.value)[:3] + [20]
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())

        elif self.variant_model.columns[index.column()].name == 'hover':
            if item.hover.value:
                # only one selected at the time
                item.color.value = list(item.color.value)[:3] + [255]
                for row in self.variant_model.rows:
                    if row.hover.value and row != item:
                        row.hover.value = False

                depth = item.depth.value
                selected_variant_id = item.name.value
                traject = []
                self.legger_model.set_column_value('selected_depth_tmp', None)

                if self.legger_model.ep:
                    traject = self.legger_model.ep.up(self.legger_model.selected)
                    traject.reverse()
                    if len(traject) > 0:
                        traject.pop(0)

                else:
                    messagebar_message(
                        'Traject nodig',
                        'Selecteer eerst een traject (sp en ep) voordat diepte kan worden doorgetrokken.',
                        1,
                        15)
                    return

                hydrovakken = self.loop_tree(
                    self.legger_model.selected,
                    depth=depth,
                    initial=False,
                    hover=True,
                    variant_id=selected_variant_id,
                    begroeiingsvariant=self.get_begroeiings_variant(),
                    child_strategy=self.get_child_selection_strategy(),
                    begroeiings_strategy=self.get_begroeiings_strategy(),
                    traject_nodes=traject
                )

                # set map visualisation of selected hydrovakken
                self.network._virtual_tree_layer.setSubsetString(
                    '"hydro_id" in (\'{ids}\')'.format(
                        ids='\',\''.join([str(hydrovak.hydrovak['hydro_id']) for hydrovak in hydrovakken])))
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())
            else:
                self.legger_model.set_column_value('selected_depth_tmp', None)
                # reset map visualisation
                self.network._virtual_tree_layer.setSubsetString('')
                # trigger repaint of sideview
                self.sideview_widget.draw_selected_lines(self.sideview_widget._get_data())

    def on_select_edit_hydrovak(self, item):
        """
        set elements after selection of a hydrovak for profile selection

        item (LeggerTreeItem): selected hydrovak LeggerTreeItem
        return: -
        """

        hydro_object = self.session.query(HydroObject).filter_by(id=item.hydrovak.get('hydro_id')).first()
        if hydro_object is None:
            self.selected_variant_remark.setPlainText('')
            self.selected_variant_remark.setDisabled(True)
            return None

        self.selected_hydrovak = item

        self.selected_hydrovak = item
        self.selected_hydrovak_db = hydro_object

        self.selected_variant_remark.setDisabled(False)
        self.selected_variant_remark.setPlainText(item.hydrovak.get('selected_remarks'))
        self.update_available_variants()

    def save_remarks(self):
        if self.selected_hydrovak:
            if self.selected_hydrovak_db:
                self.selected_hydrovak_db.opmerkingen = self.selected_variant_remark.toPlainText()
                self.session.add(self.selected_hydrovak_db)
                self.session.commit()

                self.legger_model.setDataItemKey(
                    self.selected_hydrovak,
                    'selected_remarks',
                    self.selected_variant_remark.toPlainText())

    def update_available_variants(self):

        item = self.selected_hydrovak
        hydro_object = self.selected_hydrovak_db
        self.variant_model.removeRows(0, len(self.variant_model.rows))

        selected_variant_id = item.hydrovak.get('selected_variant_id')

        var = self.session.query(Varianten) \
            .join(BegroeiingsVariant) \
            .outerjoin(ProfielFiguren) \
            .filter(Varianten.hydro == hydro_object) \
            .order_by(Varianten.diepte)

        if self.active_begroeiings_variant == SHOW_ALL:
            pass
        elif self.active_begroeiings_variant == PRE_SELECTED:
            var = var.filter(or_(Varianten.begroeiingsvariant == hydro_object.begroeiingsvariant,
                                 Varianten.id == selected_variant_id))
        elif self.active_begroeiings_variant is not None:
            var = var.filter(or_(BegroeiingsVariant.naam == self.active_begroeiings_variant,
                                 Varianten.id == selected_variant_id))

        from legger import settings
        verhang = 3.0
        color_map = (
            (1.0, settings.LOW_COLOR),
            (3.0, settings.OK_COLOR),
            (4.0, settings.HIGH_COLOR),
        )
        profs = []
        for profile in var.all():
            active = selected_variant_id == profile.id
            over_width = None
            over_depth = None

            if profile.figuren:
                over_width = profile.figuren[0].t_overbreedte_l + profile.figuren[0].t_overbreedte_r
                over_depth = profile.figuren[0].t_overdiepte
            else:
                if profile.hydro.kenmerken and profile.hydro.kenmerken[0].diepte is not None and profile.diepte is not None:
                    over_depth = profile.hydro.kenmerken[0].diepte - profile.diepte
                if profile.hydro.kenmerken and profile.hydro.kenmerken[0].breedte is not None and profile.waterbreedte is not None:
                    over_width = profile.hydro.kenmerken[0].breedte - profile.waterbreedte

            profs.append({
                'name': profile.id,
                'active': active,  # digits differ far after the
                'depth': profile.diepte,
                'begroeiingsvariant': profile.begroeiingsvariant.naam,
                'score': profile.figuren[0].t_fit if profile.figuren else None,
                'over_depth': over_depth if over_depth is not None else None,
                'over_width': over_width if over_depth is not None else None,
                'over_width_color': [255, 0, 0] if over_width < 0 else [255, 255, 255],
                'verhang': profile.verhang,
                'color': interpolated_color(value=profile.verhang, color_map=color_map,
                                            alpha=(255 if active else 80)),
                'points': [
                    (-0.5 * profile.waterbreedte, hydro_object.streefpeil),
                    (-0.5 * profile.bodembreedte, hydro_object.streefpeil - profile.diepte),
                    (0.5 * profile.bodembreedte, hydro_object.streefpeil - profile.diepte),
                    (0.5 * profile.waterbreedte, hydro_object.streefpeil),
                ]
            })
        self.variant_model.insertRows(profs)

    def update_available_profiles(self, item, variant):
        """
            used for updating ranges after adding a profile manually
        """

        # update variant table
        self.on_select_edit_hydrovak(item)
        diepte = float(variant.diepte)

        if item.hydrovak.get('variant_max_depth') is None or diepte > item.hydrovak.get('variant_max_depth'):
            self.legger_model.setDataItemKey(item, 'variant_max_depth', diepte)

        if item.hydrovak.get('variant_min_depth') is None or diepte < item.hydrovak.get('variant_min_depth'):
            self.legger_model.setDataItemKey(item, 'variant_min_depth', diepte)

    def onSelectBegroeiingsVariant(self):
        self.active_begroeiings_variant = self.begroeiings_combo.currentText()
        self.update_available_variants()

    def get_begroeiings_variant(self):
        return self.begroeiings_varianten[self.begroeiings_combo.currentText()]

    def get_begroeiings_strategy(self):
        return self.begroeiings_variant_strategies[self.begroeiings_strategy_combo.currentText()]

    def get_child_selection_strategy(self):

        return self.child_selection_strategies[self.child_selection_strategy_combo.currentText()]

    def closeEvent(self, event):
        """
        close event for widget, including removal of layers and disconnection of listeners
        event: close event
        return: None
        """
        self.save_remarks()

        if self.vl_tree_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_tree_layer)
        if self.line_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.line_layer)
        if self.vl_endpoint_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_endpoint_layer)
        if self.vl_track_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_track_layer)
        if self.vl_hover_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_hover_layer)
        if self.vl_selected_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_selected_layer)
        if self.vl_startpoint_hover_layer in QgsMapLayerRegistry.instance().mapLayers().values():
            QgsMapLayerRegistry.instance().removeMapLayer(self.vl_startpoint_hover_layer)

        self.category_combo.currentIndexChanged.disconnect(self.category_change)
        self.show_manual_input_button.clicked.disconnect(self.show_manual_input_window)
        self.next_endpoint_button.clicked.disconnect(self.set_next_endpoint)
        self.variant_model.dataChanged.disconnect(self.data_changed_variant)
        self.legger_model.dataChanged.disconnect(self.data_changed_legger_tree)
        self.area_model.dataChanged.disconnect(self.data_changed_area_model)
        self.begroeiings_combo.currentIndexChanged.disconnect(self.onSelectBegroeiingsVariant)

        self.legger_model.setTreeWidget(None)

        self.closingWidget.emit()
        event.accept()

    def setup_ui(self, dock_widget):
        """
        initiate main Qt building blocks of interface
        :param dock_widget: QDockWidget instance
        """

        dock_widget.setObjectName("dock_widget")
        dock_widget.setAttribute(Qt.WA_DeleteOnClose)

        self.dock_widget_content = QWidget(self)
        self.dock_widget_content.setObjectName("dockWidgetContent")

        self.main_vlayout = QVBoxLayout(self)
        self.dock_widget_content.setLayout(self.main_vlayout)

        # add button to add objects to graphs
        self.button_bar_hlayout = QHBoxLayout(self)

        self.show_manual_input_button = QPushButton(self)
        self.button_bar_hlayout.addWidget(self.show_manual_input_button)
        self.show_manual_input_button.setDisabled(True)

        self.button_bar_hlayout.addWidget(QLabel("filter t/m categorie:"))
        self.category_combo = QComboBox(self)
        self.button_bar_hlayout.addWidget(self.category_combo)

        self.next_endpoint_button = QPushButton(self)
        self.button_bar_hlayout.addWidget(self.next_endpoint_button)
        self.next_endpoint_button.setDisabled(True)

        self.child_selection_strategy_combo = QComboBox(self)
        self.button_bar_hlayout.addWidget(QLabel("doortrekken tot:"))
        self.button_bar_hlayout.addWidget(self.child_selection_strategy_combo)

        spacer_item = QSpacerItem(40,
                                  20,
                                  QSizePolicy.Expanding,
                                  QSizePolicy.Minimum)
        self.button_bar_hlayout.addItem(spacer_item)

        # self.button_bar_hlayout.addItem(QLabel("doortrekken tot:"))
        # self.button_bar_hlayout.addItem(self.begroeiings_strategy_combo)

        self.main_vlayout.addLayout(self.button_bar_hlayout)
        # add tabWidget for graphWidgets
        self.contentLayout = QHBoxLayout(self)

        self.tree_table_tab = QTabWidget(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(
            self.tree_table_tab.sizePolicy().hasHeightForWidth())
        self.tree_table_tab.setSizePolicy(sizePolicy)
        self.tree_table_tab.setMinimumSize(QSize(850, 0))

        self.contentLayout.addWidget(self.tree_table_tab)

        # startpointTree
        self.startpoint_tree_widget = StartpointTreeWidget(self, self.area_model)
        # sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(
        #     self.legger_tree_widget.sizePolicy().hasHeightForWidth())
        # self.legger_tree_widget.setSizePolicy(sizePolicy)
        # self.legger_tree_widget.setMinimumSize(QSize(750, 0))

        self.tree_table_tab.addTab(self.startpoint_tree_widget, 'startpunten')

        # LeggerTree
        self.legger_tree_widget = LeggerTreeWidget(self, self.legger_model)
        # sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        # sizePolicy.setHorizontalStretch(0)
        # sizePolicy.setVerticalStretch(0)
        # sizePolicy.setHeightForWidth(
        #     self.legger_tree_widget.sizePolicy().hasHeightForWidth())
        # self.legger_tree_widget.setSizePolicy(sizePolicy)
        # self.legger_tree_widget.setMinimumSize(QSize(750, 0))

        self.tree_table_tab.addTab(self.legger_tree_widget, 'hydrovakken')

        # graphs
        self.graph_vlayout = QVBoxLayout(self)

        # Graph
        self.plot_widget = LeggerPlotWidget(
            self, session=self.session,
            legger_model=self.legger_model,
            variant_model=self.variant_model)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.plot_widget.sizePolicy().hasHeightForWidth())
        self.plot_widget.setSizePolicy(sizePolicy)
        self.plot_widget.setMinimumSize(QSize(250, 150))

        self.graph_vlayout.addWidget(self.plot_widget, 2)

        # Sideview Graph
        self.sideview_widget = LeggerSideViewPlotWidget(
            self, session=self.session,
            legger_model=self.legger_model)
        sizePolicy = QSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(1)
        sizePolicy.setVerticalStretch(1)
        sizePolicy.setHeightForWidth(
            self.sideview_widget.sizePolicy().hasHeightForWidth())
        self.sideview_widget.setSizePolicy(sizePolicy)
        self.sideview_widget.setMinimumSize(QSize(250, 150))

        self.graph_vlayout.addWidget(self.sideview_widget)

        self.contentLayout.addLayout(self.graph_vlayout, 2)

        self.rightVstack = QVBoxLayout(self)
        sizePolicy = QSizePolicy(QSizePolicy.Fixed, QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)

        self.begroeiings_combo = QComboBox(self)
        self.begroeiings_strategy_combo = QComboBox(self)
        self.groupBox_begroeiings = QGroupBox(self)
        self.groupBox_begroeiings.setTitle("begroeiingsfilter en voor welk deel")
        vbox_strat = QVBoxLayout()
        vbox_strat.addWidget(self.begroeiings_combo)
        vbox_strat.addWidget(self.begroeiings_strategy_combo)
        self.groupBox_begroeiings.setLayout(vbox_strat)
        self.rightVstack.addWidget(self.groupBox_begroeiings)

        # variantentable
        self.plot_item_table = VariantenTable(self, variant_model=self.variant_model)
        self.plot_item_table.setMinimumWidth(380)

        self.rightVstack.addWidget(self.plot_item_table)

        self.selected_variant_remark = QPlainTextEdit(self)
        self.selected_variant_remark.setFixedHeight(100)
        self.selected_variant_remark.setDisabled(True)

        self.rightVstack.addWidget(self.selected_variant_remark)

        self.contentLayout.addLayout(self.rightVstack, 0)

        self.main_vlayout.addLayout(self.contentLayout)

        # add dockwidget
        dock_widget.setWidget(self.dock_widget_content)
        self.retranslate_ui(dock_widget)
        QMetaObject.connectSlotsByName(dock_widget)

    def retranslate_ui(self, dock_widget):
        pass
        dock_widget.setWindowTitle(_translate(
            "DockWidget", "Legger", None))
        self.show_manual_input_button.setText(_translate(
            "DockWidget", "Voeg profiel toe", None))
        self.next_endpoint_button.setText(_translate(
            "DockWidget", "Volgend eindpunt", None))