Example #1
0
 def __init__(self):
     TreeItem.__init__(self, 'shogun-logo-50x50px-round-blue.png',
                       'Shogun Connections')
     self.actiontype = 'topitem'
     font = QFont('Arial', 14)
     font.setBold(True)
     self.setFont(0, font)
Example #2
0
    def __init__(self, parent=None):
        super(LCDefineDegradationWidget, self).__init__(parent)

        self.setupUi(self)

        self.classes = [self.tr("Tree-covered"),
                        self.tr("Grassland"),
                        self.tr("Cropland"),
                        self.tr("Wetland"),
                        self.tr("Artificial"),
                        self.tr("Bare land"),
                        self.tr("Water body")]
        self.deg_def_matrix.setRowCount(len(self.classes))
        self.deg_def_matrix.setColumnCount(len(self.classes))
        self.deg_def_matrix.setHorizontalHeaderLabels(self.classes)
        self.deg_def_matrix.setVerticalHeaderLabels(self.classes)

        self.trans_matrix_default = [0, -1, -1, -1, -1, -1, 0, # Tree-covered
                                     1, 0, 1, -1, -1, -1, 0, # grassland
                                     1, -1, 0, -1, -1, -1, 0, # cropland
                                     -1, -1, -1, 0, -1, -1, 0, # wetland
                                     1, 1, 1, 1, 0, 1, 0, # artificial
                                     1, 1, 1, 1, -1, 0, 0, # Other land
                                     0, 0, 0, 0, 0, 0, 0] # water body
        for row in range(0, self.deg_def_matrix.rowCount()):
            for col in range(0, self.deg_def_matrix.columnCount()):
                line_edit = TransMatrixEdit()
                line_edit.setValidator(QRegExpValidator(QRegExp("[-0+]")))
                line_edit.setAlignment(Qt.AlignHCenter)
                self.deg_def_matrix.setCellWidget(row, col, line_edit)
        self.trans_matrix_set()

        # Setup the vertical label for the rows of the table
        label_lc_baseline_year = VerticalLabel(self)
        label_lc_baseline_year.setText(QtWidgets.QApplication.translate("DlgCalculateLC", "Land cover in initial year ", None))
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Minimum)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.label_lc_target_year.sizePolicy().hasHeightForWidth())
        label_lc_baseline_year.setSizePolicy(sizePolicy)
        font = QFont()
        font.setBold(True)
        font.setWeight(75)
        label_lc_baseline_year.setFont(font)
        self.lc_trans_table_layout.addWidget(label_lc_baseline_year, 1, 0, 1, 1, Qt.AlignCenter)

        self.deg_def_matrix.setStyleSheet('QTableWidget {border: 0px;}')
        self.deg_def_matrix.horizontalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}')
        self.deg_def_matrix.verticalHeader().setStyleSheet('QHeaderView::section {background-color: white;border: 0px;}')

        self.deg_def_matrix.horizontalHeader().setResizeMode(QtWidgets.QHeaderView.Stretch)
        self.deg_def_matrix.verticalHeader().setResizeMode(QtWidgets.QHeaderView.Stretch)

        self.btn_transmatrix_reset.clicked.connect(self.trans_matrix_set)
        self.btn_transmatrix_loadfile.clicked.connect(self.trans_matrix_loadfile)
        self.btn_transmatrix_savefile.clicked.connect(self.trans_matrix_savefile)

        self.legend_deg.setStyleSheet('QLineEdit {background: #AB2727;} QLineEdit:hover {border: 1px solid gray; background: #AB2727;}')
        self.legend_imp.setStyleSheet('QLineEdit {background: #45A146;} QLineEdit:hover {border: 1px solid gray; background: #45A146;}')
        self.legend_stable.setStyleSheet('QLineEdit {background: #FFFFE0;} QLineEdit:hover {border: 1px solid gray; background: #FFFFE0;}')
    def fill_collection(self, key, collection, parent):
        """
        Fill a collection of LADM_COL objects
        """
        parent.insertChildren(parent.childCount(), 1,
                              self.rootItem.columnCount())
        collection_parent = parent.child(parent.childCount() - 1)
        collection_parent.setData(
            0,
            "{} ({})".format(DICT_PLURAL[key] if key in DICT_PLURAL else key,
                             len(collection)))
        collection_parent.setData(0, {"type": key}, Qt.UserRole)
        res = collection_parent.setData(
            0,
            QIcon(DICT_PACKAGE_ICON[DICT_TABLE_PACKAGE[key]])
            if key in DICT_TABLE_PACKAGE else None, Qt.DecorationRole)

        for object in collection:
            # Fill LADM_COL object
            collection_parent.insertChildren(collection_parent.childCount(), 1,
                                             self.rootItem.columnCount())
            object_parent = collection_parent.child(
                collection_parent.childCount() - 1)
            object_parent.setData(0, "t_id: {}".format(object['id']))
            object_parent.setData(0, {
                "type": key,
                "id": object['id'],
                "value": object['id']
            }, Qt.UserRole)
            object_parent.setData(0, key, Qt.ToolTipRole)
            font = QFont()
            font.setBold(True)
            object_parent.setData(0, font, Qt.FontRole)
            self.fill_model(object['attributes'], object_parent)
Example #4
0
    def load_items(self):
        self.trw_quality_rules.setUpdatesEnabled(
            False)  # Don't render until we're ready
        self.trw_quality_rules.clear()

        font = QFont()
        font.setBold(True)

        for group, items in self.items_dict.items():
            children = []
            group_item = QTreeWidgetItem([group])
            group_item.setData(0, Qt.BackgroundRole,
                               QBrush(QColor(219, 219, 219, 255)))
            group_item.setData(0, Qt.FontRole, font)
            icon = QIcon(":/Asistente-LADM_COL/resources/images/{}.png".format(
                items['icon']))
            group_item.setData(0, Qt.DecorationRole, icon)

            for rule in items['rules']:
                rule_item = QTreeWidgetItem([rule['text']])
                rule_item.setData(0, Qt.UserRole, rule['id'])

                children.append(rule_item)

            group_item.addChildren(children)
            self.trw_quality_rules.addTopLevelItem(group_item)

        # Make group items non selectable and expanded
        for i in range(self.trw_quality_rules.topLevelItemCount()):
            self.trw_quality_rules.topLevelItem(i).setFlags(
                Qt.ItemIsEnabled)  # Not selectable
            self.trw_quality_rules.topLevelItem(i).setExpanded(True)

        self.trw_quality_rules.setUpdatesEnabled(True)  # Now render!
Example #5
0
    def __init__(self, data=None):
        """Constructor."""
        super(ProfileWidget, self).__init__()

        # Attributes
        self.widget_items = []
        # Set data
        if data:
            self.data = data
        # Set header
        self.header_tree_widget = QTreeWidgetItem(
            [tr('Classification'),
             tr('Affected'),
             tr('Displacement Rate')])
        header_font = QFont()
        header_font.setBold(True)
        header_font.setPointSize(14)
        self.header_tree_widget.setFont(0, header_font)
        self.header_tree_widget.setFont(1, header_font)
        self.header_tree_widget.setFont(2, header_font)
        self.setHeaderItem(self.header_tree_widget)
        self.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.header().setSectionResizeMode(1, QHeaderView.Fixed)
        self.header().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.header().setSectionsMovable(False)
Example #6
0
    def __update_available_rules(self):
        self.trw_qrs.setUpdatesEnabled(False)  # Don't render until we're ready

        # Grab some context data
        top_level_items_expanded_info = dict()
        for i in range(self.trw_qrs.topLevelItemCount()):
            top_level_items_expanded_info[self.trw_qrs.topLevelItem(i).text(0)] = self.trw_qrs.topLevelItem(i).isExpanded()

        # Save selection
        self.__update_selected_items()

        # Iterate qr types adding children
        self.trw_qrs.blockSignals(True)  # We don't want to get itemSelectionChanged here
        self.trw_qrs.clear()
        self.trw_qrs.blockSignals(False)

        bold_font = QFont()
        bold_font.setBold(True)

        sorted_types = sorted(self.__controller.get_qrs_tree_data().keys())
        for type_enum in sorted_types:
            children = []
            type_item = QTreeWidgetItem([self.__controller.get_tr_string(type_enum)])

            # Filter by search text
            list_qrs = self.__filter_by_search_text(type_enum, self.txt_search.text())

            for qr in list_qrs:
                qr_item = QTreeWidgetItem([qr.name()])
                qr_item.setData(0, Qt.UserRole, qr.id())
                qr_item.setData(0, Qt.ToolTipRole, "{}\n{}".format(qr.name(), qr.id()))
                children.append(qr_item)

            if children:
                icon_name = self.__icon_names[type_enum.value]
                icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format(icon_name))
                type_item.setData(0, Qt.DecorationRole, icon)
                type_item.setData(0, Qt.FontRole, bold_font)
                type_item.addChildren(children)
                self.trw_qrs.addTopLevelItem(type_item)

        # Set selection
        iterator = QTreeWidgetItemIterator(self.trw_qrs, QTreeWidgetItemIterator.Selectable)
        self.trw_qrs.blockSignals(True)  # We don't want to get itemSelectionChanged here
        while iterator.value():
            item = iterator.value()
            if item.data(0, Qt.UserRole) in self.__selected_items_list:
                item.setSelected(True)

            iterator += 1

        self.trw_qrs.blockSignals(False)

        # Make type items non selectable
        # Set expand taking previous states into account
        for i in range(self.trw_qrs.topLevelItemCount()):
            self.trw_qrs.topLevelItem(i).setFlags(Qt.ItemIsEnabled)  # Not selectable
            self.trw_qrs.topLevelItem(i).setExpanded(top_level_items_expanded_info.get(self.trw_qrs.topLevelItem(i).text(0), True))

        self.trw_qrs.setUpdatesEnabled(True)  # Now render!
    def fill_collection(self, key, collection, parent, plural, icons):
        """
        Fill a collection of LADM_COL objects
        """
        parent.insertChildren(parent.childCount(), 1,
                              self.rootItem.columnCount())
        collection_parent = parent.child(parent.childCount() - 1)
        collection_parent.setData(
            0, "{} ({})".format(plural[key] if key in plural else key,
                                len(collection)))
        collection_parent.setData(0, {"type": key}, Qt.UserRole)
        dict_table_package = LayerConfig.get_dict_table_package(self.names)

        res = collection_parent.setData(
            0,
            QIcon(icons[dict_table_package[key]])
            if key in dict_table_package else None, Qt.DecorationRole)

        for object in collection:
            # Fill LADM_COL object
            collection_parent.insertChildren(collection_parent.childCount(), 1,
                                             self.rootItem.columnCount())
            object_parent = collection_parent.child(
                collection_parent.childCount() - 1)
            object_parent.setData(0, "t_id: {}".format(object['id']))
            object_parent.setData(0, {
                "type": key,
                "id": object['id'],
                "value": object['id']
            }, Qt.UserRole)
            object_parent.setData(0, key, Qt.ToolTipRole)
            font = QFont()
            font.setBold(True)
            object_parent.setData(0, font, Qt.FontRole)
            self.fill_model(object['attributes'], object_parent)
Example #8
0
    def setupUi(self, Dialog):
        Dialog.setObjectName("Dialog")
        Dialog.resize(
            QtCore.QSize(QtCore.QRect(0, 0, 440, 660).size()).expandedTo(
                Dialog.minimumSizeHint()))

        self.gridlayout = QGridLayout(Dialog)
        self.gridlayout.setObjectName("gridlayout")

        font = QFont()
        font.setPointSize(15)
        font.setWeight(50)
        font.setBold(True)

        self.label_2 = QLabel(Dialog)
        self.label_2.setFont(font)
        self.label_2.setTextFormat(QtCore.Qt.RichText)
        self.label_2.setObjectName("label_2")
        self.gridlayout.addWidget(self.label_2, 1, 1, 1, 2)

        self.textEdit = QTextEdit(Dialog)

        palette = QPalette()

        brush = QBrush(QColor(0, 0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Active, QPalette.Base, brush)

        brush = QBrush(QColor(0, 0, 0, 0))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Inactive, QPalette.Base, brush)

        brush = QBrush(QColor(255, 255, 255))
        brush.setStyle(QtCore.Qt.SolidPattern)
        palette.setBrush(QPalette.Disabled, QPalette.Base, brush)
        self.textEdit.setPalette(palette)
        self.textEdit.setAutoFillBackground(True)
        self.textEdit.width = 320
        self.textEdit.height = 360
        self.textEdit.setFrameShape(QFrame.NoFrame)
        self.textEdit.setFrameShadow(QFrame.Plain)
        self.textEdit.setReadOnly(True)
        self.textEdit.setObjectName("textEdit")
        self.textEdit.setTextInteractionFlags(QtCore.Qt.TextBrowserInteraction)

        self.gridlayout.addWidget(self.textEdit, 2, 1, 5, 2)

        self.pushButton = QPushButton(Dialog)
        self.pushButton.setObjectName("pushButton")
        self.gridlayout.addWidget(self.pushButton, 4, 2, 1, 1)

        spacerItem = QSpacerItem(20, 40, QSizePolicy.Minimum,
                                 QSizePolicy.Expanding)
        self.gridlayout.addItem(spacerItem, 3, 1, 1, 1)

        self.retranslateUi(Dialog)
        self.pushButton.clicked.connect(Dialog.reject)
        QtCore.QMetaObject.connectSlotsByName(Dialog)
    def showFeatureAttributes(self):
        conflictItem = self.lastSelectedItem
        self.oursgeom = None
        self.theirsgeom = None
        geoms = (self.oursgeom, self.theirsgeom)
        self.currentConflictedAttributes = []
        attribs = list(conflictItem.origin.keys())
        self.attributesTable.setRowCount(len(attribs))

        self.conflicted = []
        for idx, name in enumerate(attribs):
            font = QFont()
            font.setBold(True)
            font.setWeight(75)
            item = QTableWidgetItem(name)
            item.setFont(font)
            self.attributesTable.setItem(idx, 3, item);

            self.attributesTable.setItem(idx, 4, ValueItem(None, False));

            try:
                values = (conflictItem.origin[name], conflictItem.local[name], conflictItem.remote[name])
            except Exception: #Local has been deleted
                self._afterSolve(False)
                self.solveModifyAndDelete(conflictItem.conflict.path, self.REMOTE)
                return
            except TypeError: #Remote has been deleted
                self._afterSolve(False)
                self.solveModifyAndDelete(conflictItem.conflict.path,self.LOCAL)
                return
            try:
                geom = QgsGeometry.fromWkt(values[0])
            except:
                geom = None
            if geom is not None:
                self.theirsgeom = QgsGeometry().fromWkt(values[1])
                self.oursgeom = QgsGeometry.fromWkt(values[2])
                geoms = (self.oursgeom, self.theirsgeom)

            ok = values[0] == values[1] or values[1] == values[2] or values[0] == values[2]

            for i, v in enumerate(values):
                self.attributesTable.setItem(idx, i, ValueItem(v, not ok, geoms));

            if not ok:
                self.conflicted.append(name)
            else:
                if values[0] == values[1]:
                    newvalue = values[2]
                else:
                    newvalue = values[1]
                self.attributesTable.setItem(idx, 4, ValueItem(newvalue, False, geoms));

        self.attributesTable.resizeRowsToContents()
        self.attributesTable.horizontalHeader().setMinimumSectionSize(150)
        self.attributesTable.horizontalHeader().setStretchLastSection(True)
    def commitClicked(self):
        feature = self.listWidget.currentItem().feature
        geom = None
        self.attributesTable.setRowCount(len(feature))
        for idx, attrname in enumerate(feature):
            value = feature[attrname]
            font = QFont()
            font.setBold(True)
            font.setWeight(75)
            item = QTableWidgetItem(attrname)
            item.setFont(font)
            self.attributesTable.setItem(idx, 0, item)
            self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value)))
            if geom is None:
                try:
                    geom = QgsGeometry.fromWkt(value)
                except:
                    pass

        self.attributesTable.resizeRowsToContents()
        self.attributesTable.horizontalHeader().setMinimumSectionSize(150)
        self.attributesTable.horizontalHeader().setStretchLastSection(True)

        settings = QSettings()
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')
        types = ["Point", "LineString", "Polygon"]
        layers = []
        if geom is not None:
            geomtype = types[int(geom.type())]
            layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp",
                                         "memory")
            pr = layer.dataProvider()
            feat = QgsFeature()
            feat.setGeometry(geom)
            pr.addFeatures([feat])
            layer.updateExtents()
            layer.selectAll()
            layer.setExtent(layer.boundingBoxOfSelected())
            layer.invertSelection()
            symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol.setColor(Qt.green)
            symbol.setAlpha(0.5)
            if QGis.QGIS_VERSION_INT < 29900:
                layer.setRendererV2(QgsSingleSymbolRendererV2(symbol))
            else:
                layer.setRenderer(QgsSingleSymbolRenderer(symbol))
            self.mapCanvas.setRenderFlag(False)
            self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)])
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            self.mapCanvas.setExtent(layer.extent())
            self.mapCanvas.setRenderFlag(True)
            layers.append(layer)
        else:
            self.mapCanvas.setLayerSet([])
        settings.setValue('/Projections/defaultBehaviour', prjSetting)
Example #11
0
 def __init__(self, ressource):
     TreeItem.__init__(self, 'applications-logo.png', 'Applications')
     self.ressource = ressource
     self.applications = self.ressource.getApplicationIdsAndNames()
     self.applicationlist = []
     self.actiontype = 'applicationsItem'
     font = QFont('Arial', 10)
     font.setBold(True)
     self.setFont(0, font)
     self.populate()
Example #12
0
 def __init__(self, shogunRessource):
     self.ressource = shogunRessource
     self.name = shogunRessource.name
     TreeItem.__init__(self, 'shogun-logo-25x-25px.png', self.name)
     self.isConnected = False
     self.actiontype = 'connection'
     font = QFont('Arial', 12)
     font.setBold(True)
     self.setFont(0, font)
     self.populateTree(shogunRessource)
Example #13
0
 def __init__(self, ressource):
     TreeItem.__init__(self, 'layers-logo.png', 'Layers')
     self.ressource = ressource
     self.layers = self.ressource.getLayerIdsAndNames()
     self.layerlist = []
     self.actiontype = 'layersItem'
     font = QFont('Arial', 10)
     font.setBold(True)
     self.setFont(0, font)
     self.populate()
    def commitClicked(self):
        feature = self.listWidget.currentItem().feature
        geom = None
        self.attributesTable.setRowCount(len(feature))
        for idx, attrname in enumerate(feature):
            value = feature[attrname]
            font = QFont()
            font.setBold(True)
            font.setWeight(75)
            item = QTableWidgetItem(attrname)
            item.setFont(font)
            self.attributesTable.setItem(idx, 0, item);
            self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value)));
            if geom is None:
                try:
                    geom = QgsGeometry.fromWkt(value)
                except:
                    pass

        self.attributesTable.resizeRowsToContents()
        self.attributesTable.horizontalHeader().setMinimumSectionSize(150)
        self.attributesTable.horizontalHeader().setStretchLastSection(True)

        settings = QSettings()
        prjSetting = settings.value('/Projections/defaultBehaviour')
        settings.setValue('/Projections/defaultBehaviour', '')
        types = ["Point", "LineString", "Polygon"]
        layers = []
        if geom is not None:
            geomtype = types[int(geom.type())]
            layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp", "memory")
            pr = layer.dataProvider()
            feat = QgsFeature()
            feat.setGeometry(geom)
            pr.addFeatures([feat])
            layer.updateExtents()
            layer.selectAll()
            layer.setExtent(layer.boundingBoxOfSelected())
            layer.invertSelection()
            symbol = QgsSymbolV2.defaultSymbol(layer.geometryType())
            symbol.setColor(Qt.green)
            symbol.setAlpha(0.5)
            if QGis.QGIS_VERSION_INT < 29900:
                layer.setRendererV2(QgsSingleSymbolRendererV2(symbol))
            else:
                layer.setRenderer(QgsSingleSymbolRenderer(symbol))
            self.mapCanvas.setRenderFlag(False)
            self.mapCanvas.setLayerSet([QgsMapCanvasLayer(layer)])
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            self.mapCanvas.setExtent(layer.extent())
            self.mapCanvas.setRenderFlag(True)
            layers.append(layer)
        else:
            self.mapCanvas.setLayerSet([])
        settings.setValue('/Projections/defaultBehaviour', prjSetting)
Example #15
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

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

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

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

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

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

        self.setLexer(self.lexer)
    def commitClicked(self):
        feature = self.listWidget.currentItem().feature()
        geom = feature.geometry()
        attributes = feature.attributes()
        self.attributesTable.setRowCount(len(attributes))
        props = [f.name() for f in feature.fields()]
        for idx in range(len(props)):
            value = attributes[idx]
            font = QFont()
            font.setBold(True)
            font.setWeight(75)
            item = QTableWidgetItem(props[idx])
            item.setFont(font)
            self.attributesTable.setItem(idx, 0, item)
            self.attributesTable.setItem(idx, 1, QTableWidgetItem(str(value)))

        self.attributesTable.resizeRowsToContents()
        self.attributesTable.horizontalHeader().setMinimumSectionSize(150)
        self.attributesTable.horizontalHeader().setStretchLastSection(True)

        self.removeLayer()
        types = ["Point", "LineString", "Polygon"]
        geomtype = types[int(geom.type())]
        self.layer = loadLayerNoCrsDialog(geomtype + "?crs=EPSG:4326", "temp",
                                          "memory")
        pr = self.layer.dataProvider()
        feat = QgsFeature()
        feat.setGeometry(geom)
        pr.addFeatures([feat])
        self.layer.updateExtents()
        self.layer.selectAll()
        self.layer.setExtent(self.layer.boundingBoxOfSelected())
        self.layer.invertSelection()
        symbol = QgsSymbol.defaultSymbol(self.layer.geometryType())
        symbol.setColor(Qt.green)
        symbol.setOpacity(0.5)
        self.layer.setRenderer(QgsSingleSymbolRenderer(symbol))
        self.mapCanvas.setRenderFlag(False)
        self.mapCanvas.setLayers([self.layer])
        QgsProject.instance().addMapLayer(self.layer, False)
        self.mapCanvas.setExtent(self.layer.extent())
        self.mapCanvas.setRenderFlag(True)
        self.mapCanvas.refresh()
Example #17
0
    def data(self, index, role):  # pylint: disable=missing-function-docstring,too-many-return-statements
        if not index.isValid():
            return None
        node = index.internalPointer()

        if node.checkable() and index.column() == 0:
            if role == Qt.CheckStateRole:
                return Qt.Checked if node.checked() else Qt.Unchecked
            return None

        if role == Qt.DisplayRole:
            return node.data(index.column())
        if role == Qt.UserRole:
            return node.user_data()
        if role == Qt.FontRole and node.show_bold():
            f = QFont()
            f.setBold(True)
            return f
        return None
Example #18
0
    def data(self, index, role):
        if not index.isValid():
            return None
        node = index.internalPointer()

        if node.checkable() and index.column() == 0:
            if role == Qt.CheckStateRole:
                return Qt.Checked if node.checked() else Qt.Unchecked
            return None
        else:
            if role == Qt.DisplayRole:
                return node.data(index.column())
            elif role == Qt.UserRole:
                return node.user_data()
            elif role == Qt.FontRole and node.show_bold():
                f = QFont()
                f.setBold(True)
                return f
        return None
Example #19
0
    def _creaFila(self, text1, text2):
        lbl1 = QLabel(text1)
        lbl2 = QLabel(text2)

        # Per si hi ha algun enllaç
        lbl1.setOpenExternalLinks(True)
        lbl2.setOpenExternalLinks(True)

        # SizePolicy
        lbl1.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)
        lbl2.setSizePolicy(QSizePolicy.Maximum, QSizePolicy.Maximum)

        # Fonts
        # Fem una còpia de la font dels textos per posar-la en negreta
        fontNoms = QFont(QvConstants.FONTTEXT)
        fontNoms.setBold(True)
        lbl1.setFont(fontNoms)
        lbl2.setFont(QvConstants.FONTTEXT)

        self._lay.addWidget(lbl1, self._i, 0, Qt.AlignTop | Qt.AlignRight)
        self._lay.addWidget(lbl2, self._i, 1, Qt.AlignTop)

        self._i += 1
Example #20
0
    def __init__(self, data=None):
        """Constructor."""
        super(ProfileWidget, self).__init__()

        # Attributes
        self.widget_items = []
        # Set data
        if data:
            self.data = data
        # Set header
        self.header_tree_widget = QTreeWidgetItem(
            [tr('Classification'), tr('Affected'), tr('Displacement Rate')])
        header_font = QFont()
        header_font.setBold(True)
        header_font.setPointSize(14)
        self.header_tree_widget.setFont(0, header_font)
        self.header_tree_widget.setFont(1, header_font)
        self.header_tree_widget.setFont(2, header_font)
        self.setHeaderItem(self.header_tree_widget)
        self.header().setSectionResizeMode(0, QHeaderView.Stretch)
        self.header().setSectionResizeMode(1, QHeaderView.Fixed)
        self.header().setSectionResizeMode(2, QHeaderView.ResizeToContents)
        self.header().setSectionsMovable(False)
Example #21
0
    def fill_collection(self, key, collection, parent, plural, icons):
        """
        Fill a collection of LADM-COL objects
        """
        display_name = self._normalize_display(key, plural)
        key = self._normalize_key(key)
        collection_parent = self._create_new_item(parent)
        collection_parent.setData(
            0, "{} ({})".format(display_name, len(collection)))
        collection_parent.setData(
            0, {
                "type":
                key,
                "collapse":
                key not in [self.names.LC_PLOT_T, self.names.LC_PARCEL_T]
            }, Qt.UserRole)
        dict_table_package = LayerConfig.get_dict_table_package(self.names)

        res = collection_parent.setData(
            0,
            QIcon(icons[dict_table_package[key]])
            if key in dict_table_package else None, Qt.DecorationRole)

        for object in collection:
            # Fill LADM-COL object
            object_parent = self._create_new_item(collection_parent)
            object_parent.setData(0, "t_id: {}".format(object['id']))
            object_parent.setData(0, {
                "type": key,
                "id": object['id'],
                "value": object['id']
            }, Qt.UserRole)
            object_parent.setData(0, key, Qt.ToolTipRole)
            font = QFont()
            font.setBold(True)
            object_parent.setData(0, font, Qt.FontRole)
            self.fill_model(object['attributes'], object_parent)
Example #22
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

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

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

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

        self.setLexer(self.lexer)
Example #23
0
    def setLexers(self):
        self.lexer = QsciLexerPython()

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

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

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

        self.setLexer(self.lexer)
Example #24
0
class ScriptEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

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

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

        self.setCommonOptions()
        self.initShortcuts()

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

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

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

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

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

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

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

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

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

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

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

        self.setFonts(10)

    def setFonts(self, size):

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

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

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

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

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

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

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

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

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

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

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

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

            self.api = QsciAPIs(self.lexer)

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

        self.setLexer(self.lexer)
Example #25
0
class ScriptEdit(QsciScintilla):

    DEFAULT_COLOR = "#4d4d4c"
    KEYWORD_COLOR = "#8959a8"
    CLASS_COLOR = "#4271ae"
    METHOD_COLOR = "#4271ae"
    DECORATION_COLOR = "#3e999f"
    NUMBER_COLOR = "#c82829"
    COMMENT_COLOR = "#8e908c"
    COMMENT_BLOCK_COLOR = "#8e908c"
    BACKGROUND_COLOR = "#ffffff"
    CURSOR_COLOR = "#636363"
    CARET_LINE_COLOR = "#efefef"
    SINGLE_QUOTE_COLOR = "#718c00"
    DOUBLE_QUOTE_COLOR = "#718c00"
    TRIPLE_SINGLE_QUOTE_COLOR = "#eab700"
    TRIPLE_DOUBLE_QUOTE_COLOR = "#eab700"
    MARGIN_BACKGROUND_COLOR = "#efefef"
    MARGIN_FOREGROUND_COLOR = "#636363"
    SELECTION_BACKGROUND_COLOR = "#d7d7d7"
    SELECTION_FOREGROUND_COLOR = "#303030"
    MATCHED_BRACE_BACKGROUND_COLOR = "#b7f907"
    MATCHED_BRACE_FOREGROUND_COLOR = "#303030"
    EDGE_COLOR = "#efefef"
    FOLD_COLOR = "#efefef"

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

        self.lexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

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

        settings = QgsSettings()

        # Default font
        font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.setMatchedBraceBackgroundColor(
            QColor(
                settings.value(
                    "pythonConsole/matchedBraceBackgroundColorEditor",
                    QColor(self.MATCHED_BRACE_BACKGROUND_COLOR))))
        self.setMatchedBraceForegroundColor(
            QColor(
                settings.value(
                    "pythonConsole/matchedBraceForegroundColorEditor",
                    QColor(self.MATCHED_BRACE_FOREGROUND_COLOR))))

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

        self.setSelectionForegroundColor(
            QColor(
                settings.value("pythonConsole/selectionForegroundColorEditor",
                               QColor(self.SELECTION_FOREGROUND_COLOR))))
        self.setSelectionBackgroundColor(
            QColor(
                settings.value("pythonConsole/selectionBackgroundColorEditor",
                               QColor(self.SELECTION_BACKGROUND_COLOR))))

        # Show line numbers
        fontmetrics = QFontMetrics(font)
        self.setMarginWidth(1, fontmetrics.width("0000") + 5)
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(
            QColor(
                settings.value("pythonConsole/marginForegroundColorEditor",
                               QColor(self.MARGIN_FOREGROUND_COLOR))))
        self.setMarginsBackgroundColor(
            QColor(
                settings.value("pythonConsole/marginBackgroundColorEditor",
                               QColor(self.MARGIN_BACKGROUND_COLOR))))
        self.setIndentationGuidesForegroundColor(
            QColor(
                settings.value("pythonConsole/marginForegroundColorEditor",
                               QColor(self.MARGIN_FOREGROUND_COLOR))))
        self.setIndentationGuidesBackgroundColor(
            QColor(
                settings.value("pythonConsole/marginBackgroundColorEditor",
                               QColor(self.MARGIN_BACKGROUND_COLOR))))

        # Highlight current line
        caretLineColorEditor = settings.value(
            "pythonConsole/caretLineColorEditor",
            QColor(self.CARET_LINE_COLOR))
        cursorColorEditor = settings.value("pythonConsole/cursorColorEditor",
                                           QColor(self.CURSOR_COLOR))
        self.setCaretLineVisible(True)
        self.setCaretWidth(2)
        self.setCaretLineBackgroundColor(caretLineColorEditor)
        self.setCaretForegroundColor(cursorColorEditor)

        # Folding
        self.setFolding(QsciScintilla.PlainFoldStyle)
        foldColor = QColor(
            settings.value("pythonConsole/foldColorEditor",
                           QColor(self.FOLD_COLOR)))
        self.setFoldMarginColors(foldColor, foldColor)

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(
            QColor(
                settings.value("pythonConsole/edgeColorEditor",
                               QColor(self.EDGE_COLOR))))

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

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

        self.setFonts(10)
        self.initLexer()

    def setFonts(self, size):
        # Load font from Python console settings
        settings = QgsSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', size))

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

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

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

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

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

    def initLexer(self):
        settings = QgsSettings()
        self.lexer = QsciLexerPython()

        font = QFontDatabase.systemFont(QFontDatabase.FixedFont)

        loadFont = settings.value("pythonConsole/fontfamilytextEditor")
        if loadFont:
            font.setFamily(loadFont)
        fontSize = settings.value("pythonConsole/fontsizeEditor", type=int)
        if fontSize:
            font.setPointSize(fontSize)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(
            QColor(
                settings.value("pythonConsole/defaultFontColorEditor",
                               QColor(self.DEFAULT_COLOR))))
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/commentFontColorEditor",
                               QColor(self.COMMENT_COLOR))), 1)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/numberFontColorEditor",
                               QColor(self.NUMBER_COLOR))), 2)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/keywordFontColorEditor",
                               QColor(self.KEYWORD_COLOR))), 5)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/classFontColorEditor",
                               QColor(self.CLASS_COLOR))), 8)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/methodFontColorEditor",
                               QColor(self.METHOD_COLOR))), 9)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/decorFontColorEditor",
                               QColor(self.DECORATION_COLOR))), 15)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/commentBlockFontColorEditor",
                               QColor(self.COMMENT_BLOCK_COLOR))), 12)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/singleQuoteFontColorEditor",
                               QColor(self.SINGLE_QUOTE_COLOR))), 4)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/doubleQuoteFontColorEditor",
                               QColor(self.DOUBLE_QUOTE_COLOR))), 3)
        self.lexer.setColor(
            QColor(
                settings.value(
                    "pythonConsole/tripleSingleQuoteFontColorEditor",
                    QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6)
        self.lexer.setColor(
            QColor(
                settings.value(
                    "pythonConsole/tripleDoubleQuoteFontColorEditor",
                    QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7)
        self.lexer.setColor(
            QColor(
                settings.value("pythonConsole/defaultFontColorEditor",
                               QColor(self.DEFAULT_COLOR))), 13)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)
        self.lexer.setFont(font, QsciLexerPython.UnclosedString)

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

        self.api = QsciAPIs(self.lexer)

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

        self.setLexer(self.lexer)
Example #26
0
    def __update_available_rules(self):
        self.trw_qrs.setUpdatesEnabled(False)  # Don't render until we're ready

        # Grab some context data
        top_level_items_expanded_info = dict()
        for i in range(self.trw_qrs.topLevelItemCount()):
            top_level_items_expanded_info[self.trw_qrs.topLevelItem(i).text(
                QR_COLUMN)] = self.trw_qrs.topLevelItem(i).isExpanded()

        # Save selection before clearing tree to restate it later (if needed)
        self.__update_selected_item()

        # Iterate qr types adding children
        self.trw_qrs.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        self.trw_qrs.clear()
        self.trw_qrs.blockSignals(False)

        bold_font = QFont()
        bold_font.setBold(True)

        sorted_types = sorted(
            self.__controller.get_general_results_tree_data().keys())
        for type_enum in sorted_types:
            children = []
            type_item = QTreeWidgetItem(
                [self.__controller.get_tr_string(type_enum)])

            # Filter by search text
            list_qrs = self.__filter_by_search_text(type_enum,
                                                    self.txt_search.text())

            for qr in list_qrs:
                qr_item = QTreeWidgetItem([qr.name(), ''])
                qr_item.setData(QR_COLUMN, Qt.UserRole, qr.id())
                qr_item.setData(QR_COLUMN, Qt.ToolTipRole,
                                "{}\n{}".format(qr.name(), qr.id()))

                # Let's listen some QR's relevant signals to update our view when needed
                self.__partial_connections.append([
                    qr,
                    qr.progress_changed.connect(
                        partial(self.__set_qr_progress, qr.id()))
                ])
                self.__partial_connections.append([
                    qr,
                    qr.validation_finished.connect(
                        partial(self.__set_qr_validation_result, qr))
                ])

                children.append(qr_item)

            if children:
                icon_name = self.__icon_names[type_enum.value]
                icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format(
                    icon_name))
                type_item.setData(0, Qt.DecorationRole, icon)
                type_item.setData(0, Qt.FontRole, bold_font)
                type_item.addChildren(children)
                self.trw_qrs.addTopLevelItem(type_item)

                # After we've set the children, we can set custom item widgets
                self.__set_children_custom_widget(type_enum, type_item,
                                                  list_qrs)
            else:
                type_item = None

        # Set selection
        self.trw_qrs.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        item = self.__get_item_by_qr_key(self.__selected_item)
        if item:
            item.setSelected(True)
        self.trw_qrs.blockSignals(False)

        # Make type items non selectable
        # Set expand taking previous states into account
        for i in range(self.trw_qrs.topLevelItemCount()):
            self.trw_qrs.topLevelItem(i).setFlags(
                Qt.ItemIsEnabled)  # Not selectable
            self.trw_qrs.topLevelItem(i).setExpanded(
                top_level_items_expanded_info.get(
                    self.trw_qrs.topLevelItem(i).text(QR_COLUMN), True))

        self.trw_qrs.setUpdatesEnabled(True)  # Now render!
Example #27
0
class ScriptEdit(QsciScintilla):

    DEFAULT_COLOR = "#4d4d4c"
    KEYWORD_COLOR = "#8959a8"
    CLASS_COLOR = "#4271ae"
    METHOD_COLOR = "#4271ae"
    DECORATION_COLOR = "#3e999f"
    NUMBER_COLOR = "#c82829"
    COMMENT_COLOR = "#8e908c"
    COMMENT_BLOCK_COLOR = "#8e908c"
    BACKGROUND_COLOR = "#ffffff"
    CURSOR_COLOR = "#636363"
    CARET_LINE_COLOR = "#efefef"
    SINGLE_QUOTE_COLOR = "#718c00"
    DOUBLE_QUOTE_COLOR = "#718c00"
    TRIPLE_SINGLE_QUOTE_COLOR = "#eab700"
    TRIPLE_DOUBLE_QUOTE_COLOR = "#eab700"
    MARGIN_BACKGROUND_COLOR = "#efefef"
    MARGIN_FOREGROUND_COLOR = "#636363"
    SELECTION_BACKGROUND_COLOR = "#d7d7d7"
    SELECTION_FOREGROUND_COLOR = "#303030"
    MATCHED_BRACE_BACKGROUND_COLOR = "#b7f907"
    MATCHED_BRACE_FOREGROUND_COLOR = "#303030"
    EDGE_COLOR = "#efefef"
    FOLD_COLOR = "#efefef"

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

        self.lexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

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

        settings = QgsSettings()

        # Default font
        font = QFontDatabase.systemFont(QFontDatabase.FixedFont)
        self.setFont(font)
        self.setMarginsFont(font)

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)
        self.setMatchedBraceBackgroundColor(QColor(settings.value("pythonConsole/matchedBraceBackgroundColorEditor", QColor(self.MATCHED_BRACE_BACKGROUND_COLOR))))
        self.setMatchedBraceForegroundColor(QColor(settings.value("pythonConsole/matchedBraceForegroundColorEditor", QColor(self.MATCHED_BRACE_FOREGROUND_COLOR))))

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

        self.setSelectionForegroundColor(QColor(settings.value("pythonConsole/selectionForegroundColorEditor", QColor(self.SELECTION_FOREGROUND_COLOR))))
        self.setSelectionBackgroundColor(QColor(settings.value("pythonConsole/selectionBackgroundColorEditor", QColor(self.SELECTION_BACKGROUND_COLOR))))

        # Show line numbers
        fontmetrics = QFontMetrics(font)
        self.setMarginWidth(1, fontmetrics.width("0000") + 5)
        self.setMarginLineNumbers(1, True)
        self.setMarginsForegroundColor(QColor(settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR))))
        self.setMarginsBackgroundColor(QColor(settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR))))
        self.setIndentationGuidesForegroundColor(QColor(settings.value("pythonConsole/marginForegroundColorEditor", QColor(self.MARGIN_FOREGROUND_COLOR))))
        self.setIndentationGuidesBackgroundColor(QColor(settings.value("pythonConsole/marginBackgroundColorEditor", QColor(self.MARGIN_BACKGROUND_COLOR))))

        # Highlight current line
        caretLineColorEditor = settings.value("pythonConsole/caretLineColorEditor", QColor(self.CARET_LINE_COLOR))
        cursorColorEditor = settings.value("pythonConsole/cursorColorEditor", QColor(self.CURSOR_COLOR))
        self.setCaretLineVisible(True)
        self.setCaretWidth(2)
        self.setCaretLineBackgroundColor(caretLineColorEditor)
        self.setCaretForegroundColor(cursorColorEditor)

        # Folding
        self.setFolding(QsciScintilla.PlainFoldStyle)
        foldColor = QColor(settings.value("pythonConsole/foldColorEditor", QColor(self.FOLD_COLOR)))
        self.setFoldMarginColors(foldColor, foldColor)

        # Mark column 80 with vertical line
        self.setEdgeMode(QsciScintilla.EdgeLine)
        self.setEdgeColumn(80)
        self.setEdgeColor(QColor(settings.value("pythonConsole/edgeColorEditor", QColor(self.EDGE_COLOR))))

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

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

        self.setFonts(10)
        self.initLexer()

    def setFonts(self, size):
        # Load font from Python console settings
        settings = QgsSettings()
        fontName = settings.value('pythonConsole/fontfamilytext', 'Monospace')
        fontSize = int(settings.value('pythonConsole/fontsize', size))

        self.defaultFont = QFont(fontName)
        self.defaultFont.setFixedPitch(True)
        self.defaultFont.setPointSize(fontSize)
        self.defaultFont.setStyleHint(QFont.TypeWriter)
        self.defaultFont.setBold(False)

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

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

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

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

    def initLexer(self):
        settings = QgsSettings()
        self.lexer = QsciLexerPython()

        font = QFontDatabase.systemFont(QFontDatabase.FixedFont)

        loadFont = settings.value("pythonConsole/fontfamilytextEditor")
        if loadFont:
            font.setFamily(loadFont)
        fontSize = settings.value("pythonConsole/fontsizeEditor", type=int)
        if fontSize:
            font.setPointSize(fontSize)

        self.lexer.setDefaultFont(font)
        self.lexer.setDefaultColor(QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))))
        self.lexer.setColor(QColor(settings.value("pythonConsole/commentFontColorEditor", QColor(self.COMMENT_COLOR))), 1)
        self.lexer.setColor(QColor(settings.value("pythonConsole/numberFontColorEditor", QColor(self.NUMBER_COLOR))), 2)
        self.lexer.setColor(QColor(settings.value("pythonConsole/keywordFontColorEditor", QColor(self.KEYWORD_COLOR))), 5)
        self.lexer.setColor(QColor(settings.value("pythonConsole/classFontColorEditor", QColor(self.CLASS_COLOR))), 8)
        self.lexer.setColor(QColor(settings.value("pythonConsole/methodFontColorEditor", QColor(self.METHOD_COLOR))), 9)
        self.lexer.setColor(QColor(settings.value("pythonConsole/decorFontColorEditor", QColor(self.DECORATION_COLOR))), 15)
        self.lexer.setColor(QColor(settings.value("pythonConsole/commentBlockFontColorEditor", QColor(self.COMMENT_BLOCK_COLOR))), 12)
        self.lexer.setColor(QColor(settings.value("pythonConsole/singleQuoteFontColorEditor", QColor(self.SINGLE_QUOTE_COLOR))), 4)
        self.lexer.setColor(QColor(settings.value("pythonConsole/doubleQuoteFontColorEditor", QColor(self.DOUBLE_QUOTE_COLOR))), 3)
        self.lexer.setColor(QColor(settings.value("pythonConsole/tripleSingleQuoteFontColorEditor", QColor(self.TRIPLE_SINGLE_QUOTE_COLOR))), 6)
        self.lexer.setColor(QColor(settings.value("pythonConsole/tripleDoubleQuoteFontColorEditor", QColor(self.TRIPLE_DOUBLE_QUOTE_COLOR))), 7)
        self.lexer.setColor(QColor(settings.value("pythonConsole/defaultFontColorEditor", QColor(self.DEFAULT_COLOR))), 13)
        self.lexer.setFont(font, 1)
        self.lexer.setFont(font, 3)
        self.lexer.setFont(font, 4)
        self.lexer.setFont(font, QsciLexerPython.UnclosedString)

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

        self.api = QsciAPIs(self.lexer)

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

        self.setLexer(self.lexer)
Example #28
0
class SqlEdit(QsciScintilla):
    LEXER_PYTHON = 0
    LEXER_R = 1

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

        self.mylexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

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

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

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.initLexer()

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

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

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

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

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

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

        self.setLexer(self.mylexer)

    def lexer(self):
        return self.mylexer

    def setMarginVisible(self, visible):
        pass
Example #29
0
# coding=utf-8
"""Fonts which are used in InaSAFE."""

from qgis.PyQt.QtGui import QFont

big_font = QFont()
big_font.setPointSize(80)

bold_font = QFont()
bold_font.setItalic(True)
bold_font.setBold(True)
bold_font.setWeight(75)
Example #30
0
    def update_available_layers(self):
        self.trw_layers.setUpdatesEnabled(
            False)  # Don't render until we're ready

        # Grab some context data
        show_domains = self.chk_show_domains.isChecked()
        show_structures = self.chk_show_structures.isChecked()
        show_associations = self.chk_show_associations.isChecked()
        top_level_items_expanded_info = []
        for i in range(self.trw_layers.topLevelItemCount()):
            top_level_items_expanded_info.append(
                self.trw_layers.topLevelItem(i).isExpanded())

        # Save selection
        self.update_selected_items()

        # Iterate models adding children
        self.trw_layers.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        self.trw_layers.clear()
        self.trw_layers.blockSignals(False)

        sorted_models = sorted(self.models_tree.keys())
        for model in sorted_models:
            children = []
            model_item = QTreeWidgetItem([model])

            # Filter by search text
            list_tables = self.filter_tables_by_search_text(
                self.models_tree[model].keys(), self.txt_search_text.text())
            sorted_tables = sorted(list_tables)

            for table in sorted_tables:
                current_table_info = self.models_tree[model][table]
                if current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN and not show_domains \
                   or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE and not show_structures \
                   or current_table_info[QueryNames.KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION and not show_associations:
                    continue

                table_item = QTreeWidgetItem([table])
                table_item.setData(0, Qt.UserRole,
                                   self.models_tree[model][table])
                geometry_type = QgsWkbTypes().geometryType(
                    QgsWkbTypes().parseType(current_table_info[
                        QueryNames.GEOMETRY_TYPE_MODEL_BAKER])
                ) if current_table_info[
                    QueryNames.GEOMETRY_TYPE_MODEL_BAKER] else None
                icon_name = self.icon_names[
                    3 if geometry_type is None else geometry_type]

                # Is the layer already loaded in canvas?
                if self.app.core.get_ladm_layer_from_qgis(
                        self._db,
                        current_table_info[QueryNames.TABLE_NAME_MODEL_BAKER],
                        EnumLayerRegistryType.IN_LAYER_TREE) is not None:
                    table_item.setText(
                        0, table + QCoreApplication.translate(
                            "LoadLayersDialog", " [already loaded]"))
                    table_item.setData(0, Qt.ForegroundRole,
                                       QBrush(Qt.lightGray))
                    table_item.setFlags(Qt.ItemIsEnabled)  # Not selectable
                else:  # Laye not in QGIS Layer Tree
                    if not current_table_info[
                            QueryNames.
                            KIND_SETTINGS_MODEL_BAKER]:  # This is a class
                        font = QFont()
                        font.setBold(True)
                        table_item.setData(0, Qt.FontRole, font)

                if current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_DOMAIN:
                    icon_name = self.icon_names[4]
                elif current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_STRUCTURE:
                    if geometry_type is None:
                        icon_name = self.icon_names[5]
                elif current_table_info[
                        QueryNames.
                        KIND_SETTINGS_MODEL_BAKER] == ILI2DBNames.TABLE_PROP_ASSOCIATION:
                    icon_name = self.icon_names[6]
                icon = QIcon(":/Asistente-LADM-COL/resources/images/{}".format(
                    icon_name))
                table_item.setData(0, Qt.DecorationRole, icon)

                children.append(table_item)

            model_item.addChildren(children)
            self.trw_layers.addTopLevelItem(model_item)

        # Set selection
        iterator = QTreeWidgetItemIterator(self.trw_layers,
                                           QTreeWidgetItemIterator.Selectable)
        self.trw_layers.blockSignals(
            True)  # We don't want to get itemSelectionChanged here
        while iterator.value():
            item = iterator.value()
            if item.text(0) in self.selected_items_dict:
                item.setSelected(True)

            iterator += 1

        self.trw_layers.blockSignals(False)

        # Make model items non selectable
        # Set expand taking previous states into account
        for i in range(self.trw_layers.topLevelItemCount()):
            self.trw_layers.topLevelItem(i).setFlags(
                Qt.ItemIsEnabled)  # Not selectable
            self.trw_layers.topLevelItem(i).setExpanded(
                top_level_items_expanded_info[i]
                if top_level_items_expanded_info else True)

        self.trw_layers.setUpdatesEnabled(True)  # Now render!
    def populate_classified_values(
            unassigned_values, assigned_values, default_classes,
            list_unique_values, tree_mapping_widget):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in list_unique_values.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            tree_mapping_widget.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list

        :param list_unique_values: List Widget for unique values
        :type list_unique_values: QListWidget

        :param tree_mapping_widget: Tree Widget for classifying.
        :type tree_mapping_widget: QTreeWidget
        """
        # Populate the unique values list
        list_unique_values.clear()
        list_unique_values.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and str(value) or 'NULL'
            list_item = QListWidgetItem(list_unique_values)
            list_item.setFlags(
                Qt.ItemIsEnabled
                | Qt.ItemIsSelectable
                | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            list_unique_values.addItem(list_item)
        # Populate assigned values tree
        tree_mapping_widget.clear()
        bold_font = QFont()
        bold_font.setItalic(True)
        bold_font.setBold(True)
        bold_font.setWeight(75)
        tree_mapping_widget.invisibleRootItem().setFlags(
            Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(tree_mapping_widget)
            tree_branch.setFlags(
                Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and str(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(
                    Qt.ItemIsEnabled
                    | Qt.ItemIsSelectable
                    | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Example #32
0
    def std_font_to_qfont(font):  # pylint: disable=too-many-branches
        """
        Converts STD font to QFont
        """
        name = font.font_name

        style_name = None

        # we need to sometimes strip 'Italic' or 'Bold' suffixes from the font name stored in the ESRI object
        # in order to match against actual font families
        keep_scanning = True
        while name not in QFontDatabase().families() and keep_scanning:
            keep_scanning = False
            if name.lower().endswith(' italic'):
                name = name[:-len(' italic')]
                keep_scanning = True
            elif name.lower().endswith(' bold'):
                name = name[:-len(' bold')]
                keep_scanning = True
            elif name.lower().endswith(' black'):
                name = name[:-len(' black')]
                style_name = 'Black'

        res = QFont(name)
        res.setWeight(font.weight)
        if font.weight > 400:
            res.setBold(True)

        if font.italic:
            res.setItalic(True)

        # pretty annoying, but because qgis relies on style strings, we need to convert the raw bools to style names if possible...
        if res.italic() and not res.bold():
            styles = QFontDatabase().styles(res.family())
            for s in styles:
                if s.lower() in ['oblique', 'italic']:
                    res.setStyleName(s)
                    break
        elif res.italic() and res.bold():
            styles = QFontDatabase().styles(res.family())
            for s in styles:
                if ('oblique' in s.lower()
                        or 'italic' in s.lower()) and 'bold' in s.lower():
                    res.setStyleName(s)
                    break
        elif res.bold():
            styles = QFontDatabase().styles(res.family())
            for s in styles:
                if s.lower() == 'bold':
                    res.setStyleName(s)
                    break

        if style_name is not None and style_name in QFontDatabase().styles(
                res.family()):
            res.setStyleName(style_name)

        if font.underline:
            res.setUnderline(True)
        if font.strikethrough:
            res.setStrikeOut(True)

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

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

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

        mapunits = self.canvas.mapUnits()

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

        self.setPos(margin, canvasheight - margin)

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

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

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

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

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

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

        if barwidth < 30:
            barwidth = canvaswidth / 4

        while barwidth > canvaswidth / 3:
            barwidth /= 3

        realSize = barwidth * mapunitsperpixel

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

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

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

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

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

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

        return barsize
Example #34
0
class PointRotationItem(QgsMapCanvasItem):
    """
    A map canvas item which shows an angle display and preview of marker rotation
    """
    def __init__(self, canvas):
        super().__init__(canvas)

        self.rotation = 0
        self.pixmap = QPixmap()
        self.item_size = QSizeF()

        self.marker_font = QFont()
        self.marker_font.setPointSize(12)
        self.marker_font.setBold(True)

        self.arrow_path = QPainterPath()

        im = QImage(24, 24, QImage.Format_ARGB32)
        im.fill(Qt.transparent)
        self.set_symbol(im)

    def paint(self, painter, option, widget):
        if not painter:
            return

        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)

        # do a bit of trigonometry to find out how to transform a rotated item such
        # that the center point is at the point feature
        x = 0.0
        y = 0.0

        if self.pixmap.width() > 0 and self.pixmap.height() > 0:
            half_item_diagonal = math.sqrt(
                self.pixmap.width() * self.pixmap.width() +
                self.pixmap.height() * self.pixmap.height()) / 2
            diagonal_angle = math.acos(
                self.pixmap.width() / (half_item_diagonal * 2)) * 180 / math.pi
            x = half_item_diagonal * math.cos(
                (self.rotation - diagonal_angle) * math.pi / 180)
            y = half_item_diagonal * math.sin(
                (self.rotation - diagonal_angle) * math.pi / 180)

        painter.rotate(self.rotation)
        painter.translate(x - self.pixmap.width() / 2.0,
                          -y - self.pixmap.height() / 2.0)
        painter.drawPixmap(0, 0, self.pixmap)

        # draw arrow, using a red line over a thicker white line so that the arrow is visible
        # against a range of backgrounds
        pen = QPen()
        pen.setWidth(GuiUtils.scale_icon_size(4))
        pen.setColor(QColor(Qt.white))
        painter.setPen(pen)
        painter.drawPath(self.arrow_path)
        pen.setWidth(GuiUtils.scale_icon_size(1))
        pen.setColor(QColor(Qt.red))
        painter.setPen(pen)
        painter.drawPath(self.arrow_path)
        painter.restore()

        # draw numeric value beside the symbol
        painter.save()
        painter.setRenderHint(QPainter.Antialiasing, True)

        buffer_pen = QPen()
        buffer_pen.setColor(Qt.white)
        buffer_pen.setWidthF(GuiUtils.scale_icon_size(4))
        fm = QFontMetricsF(self.marker_font)
        label = QPainterPath()
        label.addText(self.pixmap.width(),
                      self.pixmap.height() / 2.0 + fm.height() / 2.0,
                      self.marker_font, str(round(self.rotation, 1)))
        painter.setPen(buffer_pen)
        painter.setBrush(Qt.NoBrush)
        painter.drawPath(label)
        painter.setPen(Qt.NoPen)
        painter.setBrush(QBrush(Qt.black))
        painter.drawPath(label)

        painter.restore()

    def set_point_location(self, p):
        transformed_point = self.toCanvasCoordinates(p)
        self.setPos(transformed_point.x() - self.pixmap.width() / 2.0,
                    transformed_point.y() - self.pixmap.height() / 2.0)

    def set_symbol_rotation(self, rotation: float):
        self.rotation = rotation

    def set_symbol(self, symbol_image: QImage):
        self.pixmap = QPixmap.fromImage(symbol_image)
        fm = QFontMetricsF(self.marker_font)

        # set item size
        self.item_size.setWidth(self.pixmap.width() + fm.width("360"))

        pixmap_height = self.pixmap.height()
        font_height = fm.height()
        if pixmap_height >= font_height:
            self.item_size.setHeight(self.pixmap.height())
        else:
            self.item_size.setHeight(fm.height())

        half_item_width = self.pixmap.width() / 2.0
        self.arrow_path = QPainterPath()
        self.arrow_path.moveTo(half_item_width, pixmap_height)
        self.arrow_path.lineTo(half_item_width, 0)
        self.arrow_path.moveTo(self.pixmap.width() * 0.25,
                               pixmap_height * 0.25)
        self.arrow_path.lineTo(half_item_width, 0)
        self.arrow_path.lineTo(self.pixmap.width() * 0.75,
                               pixmap_height * 0.25)
    def populate_classified_values(
            unassigned_values, assigned_values, default_classes,
            list_unique_values, tree_mapping_widget):
        """Populate lstUniqueValues and treeClasses.from the parameters.

        :param unassigned_values: List of values that haven't been assigned
            to a class. It will be put in list_unique_values.
        :type unassigned_values: list

        :param assigned_values: Dictionary with class as the key and list of
            value as the value of the dictionary. It will be put in
            tree_mapping_widget.
        :type assigned_values: dict

        :param default_classes: Default classes from unit.
        :type default_classes: list

        :param list_unique_values: List Widget for unique values
        :type list_unique_values: QListWidget

        :param tree_mapping_widget: Tree Widget for classifying.
        :type tree_mapping_widget: QTreeWidget
        """
        # Populate the unique values list
        list_unique_values.clear()
        list_unique_values.setSelectionMode(
            QAbstractItemView.ExtendedSelection)
        for value in unassigned_values:
            value_as_string = value is not None and str(value) or 'NULL'
            list_item = QListWidgetItem(list_unique_values)
            list_item.setFlags(
                Qt.ItemIsEnabled
                | Qt.ItemIsSelectable
                | Qt.ItemIsDragEnabled)
            list_item.setData(Qt.UserRole, value)
            list_item.setText(value_as_string)
            list_unique_values.addItem(list_item)
        # Populate assigned values tree
        tree_mapping_widget.clear()
        bold_font = QFont()
        bold_font.setItalic(True)
        bold_font.setBold(True)
        bold_font.setWeight(75)
        tree_mapping_widget.invisibleRootItem().setFlags(
            Qt.ItemIsEnabled)
        for default_class in default_classes:
            # Create branch for class
            tree_branch = QTreeWidgetItem(tree_mapping_widget)
            tree_branch.setFlags(
                Qt.ItemIsDropEnabled | Qt.ItemIsEnabled)
            tree_branch.setExpanded(True)
            tree_branch.setFont(0, bold_font)
            if 'name' in default_class:
                default_class_name = default_class['name']
            else:
                default_class_name = default_class['key']
            tree_branch.setText(0, default_class_name)
            tree_branch.setData(0, Qt.UserRole, default_class['key'])
            if 'description' in default_class:
                tree_branch.setToolTip(0, default_class['description'])
            # Assign known values
            for value in assigned_values[default_class['key']]:
                string_value = value is not None and str(value) or 'NULL'
                tree_leaf = QTreeWidgetItem(tree_branch)
                tree_leaf.setFlags(
                    Qt.ItemIsEnabled
                    | Qt.ItemIsSelectable
                    | Qt.ItemIsDragEnabled)
                tree_leaf.setData(0, Qt.UserRole, value)
                tree_leaf.setText(0, string_value)
Example #36
0
class LegendItem(LogItem):
    # margin all around the whole legend item
    LEGEND_ITEM_MARGIN = 5
    # margin between title and legend line
    LEGEND_LINE_MARGIN = 4

    def __init__(self,
                 width,
                 title,
                 min_value=None,
                 max_value=None,
                 unit_of_measure=None,
                 is_vertical=False,
                 parent=None):
        LogItem.__init__(self, parent)
        self.__width = width
        self.__title = title
        self.__min_value = min_value
        self.__max_value = max_value
        self.__uom = unit_of_measure
        self.__is_vertical = is_vertical

        self.__selected = False

        # title font
        self.__font1 = QFont()
        self.__font1.setBold(True)
        self.__font1.setPointSize(10)

        # value font
        self.__font2 = QFont()
        self.__font2.setPointSize(9)

        fm1 = QFontMetrics(self.__font1)
        fm2 = QFontMetrics(self.__font2)
        self.__height = self.LEGEND_LINE_MARGIN * 3 + fm1.height(
        ) + fm2.height() + 10 + self.LEGEND_ITEM_MARGIN

    def set_scale(self, min_value, max_value):
        self.__min_value = min_value
        self.__max_value = max_value

    def boundingRect(self):
        if self.__is_vertical:
            return QRectF(0, 0, self.__height, self.__width)
        else:
            return QRectF(0, 0, self.__width, self.__height)

    def selected(self):
        return self.__selected

    def paint(self, painter, option, widget):
        self.draw_background(painter, outline=False)

        painter.save()
        if self.__is_vertical:
            painter.translate(self.__height / 2, self.__width / 2)
            painter.rotate(-90.0)
            painter.translate(-self.__width / 2, -self.__height / 2)

        painter.setFont(self.__font1)
        fm = painter.fontMetrics()
        # add "..." if needed
        title = fm.elidedText(self.__title, Qt.ElideRight, self.__width)
        w1 = (self.__width - fm.width(title)) / 2
        y = self.LEGEND_ITEM_MARGIN + fm.ascent()
        painter.drawText(w1, y, title)
        y += fm.descent() + self.LEGEND_LINE_MARGIN

        # legend line
        xmin = 0
        xmax = self.__width
        ymax = self.__height
        painter.drawLine(xmin, y + 5, xmax, y + 5)
        painter.drawLine(xmin, y, xmin, ymax)
        painter.drawLine(xmax, y, xmax, ymax)
        y += 10 + self.LEGEND_LINE_MARGIN

        painter.setFont(self.__font2)
        fm = painter.fontMetrics()
        y += fm.ascent()

        if self.__min_value is not None:
            min_str = format_number(float(self.__min_value))
        if self.__max_value is not None:
            max_str = format_number(float(self.__max_value))

        # make sure min and max have distinct values
        if self.__min_value is not None and self.__max_value is not None:
            num_decimals = 1
            while min_str == max_str and num_decimals < 4:
                num_decimals += 1
                min_str = format_number(float(self.__min_value), num_decimals)
                max_str = format_number(float(self.__max_value), num_decimals)

        if self.__min_value is not None:
            painter.drawText(self.LEGEND_ITEM_MARGIN, y, min_str)
        if self.__max_value is not None:
            painter.drawText(
                self.__width - self.LEGEND_ITEM_MARGIN - fm.width(max_str), y,
                max_str)
        if self.__uom is not None:
            t = self.__uom
            painter.drawText((self.__width - fm.width(t)) / 2, y, t)
        painter.restore()
Example #37
0
class ScriptEdit(QsciScintilla):

    LEXER_PYTHON = 0
    LEXER_R = 1

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

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

        self.setCommonOptions()
        self.initShortcuts()

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

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

        self.initLexer()

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

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

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

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

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

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

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

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

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

        self.setFonts(10)

    def setFonts(self, size):

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

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

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

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

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

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

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

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

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

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

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

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

            self.api = QsciAPIs(self.lexer)

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

        self.setLexer(self.lexer)
Example #38
0
class SqlEdit(QsciScintilla):
    LEXER_PYTHON = 0
    LEXER_R = 1

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

        self.mylexer = None
        self.api = None

        self.setCommonOptions()
        self.initShortcuts()

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

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

        self.setBraceMatching(QsciScintilla.SloppyBraceMatch)

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.initLexer()

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

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

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

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

    def autoComplete(self):
        self.autoCompleteFromAll()

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

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

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

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

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

        self.setLexer(self.mylexer)

    def lexer(self):
        return self.mylexer

    def setMarginVisible(self, visible):
        pass
Example #39
0
    def showFeatureAttributes(self):
        conflictItem = self.lastSelectedItem
        try:
            resolvedFeature = self.resolvedConflicts[conflictItem.path][
                conflictItem.fid]
        except KeyError:
            # resolvedFeature = conflictItem.conflict["local"]
            resolvedFeature = self.resolve(self.lastSelectedItem.conflict,
                                           ConflictDialog.LOCAL)
        self.currentConflictedAttributes = []
        attribs = [
            f.name()
            for f in conflictItem.conflict["origin"].fields().toList()
        ]
        attribs.append("geometry")
        self.attributesTable.setRowCount(len(attribs))

        self.conflicted = []
        self.singleChangeProperties = []

        features = [
            conflictItem.conflict["origin"], conflictItem.conflict["remote"],
            conflictItem.conflict["local"], resolvedFeature
        ]
        for idx, name in enumerate(attribs):
            font = QFont()
            font.setBold(True)
            font.setWeight(75)
            item = QTableWidgetItem(name)
            item.setFont(font)
            self.attributesTable.setItem(idx, 3, item)
            self.attributesTable.setItem(idx, 4, ValueItem(None, False))

            if name == "geometry":  # geometry column
                values = []
                if conflictItem.conflict[
                        "origin"] is not None:  # be deleted aware
                    values.append(conflictItem.conflict["origin"].geometry())
                else:
                    values.append(None)
                if conflictItem.conflict["remote"] is not None:
                    values.append(conflictItem.conflict["remote"].geometry())
                else:
                    values.append(None)
                if conflictItem.conflict["local"] is not None:
                    values.append(conflictItem.conflict["local"].geometry())
                else:
                    values.append(None)
            else:
                values = []
                if conflictItem.conflict["origin"] is not None:
                    values.append(conflictItem.conflict["origin"][name])
                else:
                    values.append(None)
                if conflictItem.conflict["remote"] is not None:
                    values.append(conflictItem.conflict["remote"][name])
                else:
                    values.append(None)
                if conflictItem.conflict["local"] is not None:
                    values.append(conflictItem.conflict["local"][name])
                else:
                    values.append(None)
            tocompare = []
            if isinstance(values[0], QgsGeometry):
                tocompare = [
                    v.asWkt() if v is not None else None for v in values
                ]
                ok = tocompare[0] == tocompare[1] or tocompare[1] == tocompare[
                    2] or tocompare[0] == tocompare[2]
                singleChange = ok and (tocompare[0] != tocompare[1]
                                       or tocompare[0] != tocompare[2])
            else:
                ok = values[0] == values[1] or values[1] == values[
                    2] or values[0] == values[2]
                singleChange = ok and (values[0] != values[1]
                                       or values[0] != values[2])

            for i, v in enumerate(values):
                f = features[i]
                geomidx = None
                if name == "geometry" and v is not None:
                    geomidx = tocompare.index(v.asWkt()) + 1
                if f is not None:  # be deleted aware
                    self.attributesTable.setItem(
                        idx, i,
                        ValueItem(v,
                                  not ok,
                                  i + 1,
                                  refidx=geomidx,
                                  singleModified=singleChange))
                else:
                    self.attributesTable.setItem(
                        idx, i,
                        ValueItem(None,
                                  not ok,
                                  i + 1,
                                  deleted=True,
                                  singleModified=singleChange))
            # setup resolved (be deleted aware)
            if name == "geometry":
                v = resolvedFeature.geometry(
                ) if resolvedFeature is not None else None
                if resolvedFeature is not None:
                    #geomidx = len(tocompare) - tocompare[::-1].index(v.asWkt()) - 1
                    geomidx = tocompare[::-1].index(v.asWkt()) + 1
                else:
                    geomidx = None
                self.attributesTable.setItem(
                    idx, 4,
                    ValueItem(v,
                              not ok,
                              idx=geomidx,
                              deleted=resolvedFeature is None,
                              singleModified=singleChange))
            else:
                v = resolvedFeature[
                    name] if resolvedFeature is not None else None
                self.attributesTable.setItem(
                    idx, 4,
                    ValueItem(v,
                              not ok,
                              deleted=resolvedFeature is None,
                              singleModified=singleChange))

            if not ok:
                self.conflicted.append(name)
            if singleChange:
                self.singleChangeProperties.append(name)

        self.attributesTable.horizontalHeader().setMinimumSectionSize(100)
        self.attributesTable.horizontalHeader().setStretchLastSection(True)
        self.attributesTable.resizeColumnsToContents()
        header = self.attributesTable.horizontalHeader()
        for column in range(header.count()):
            header.setSectionResizeMode(
                column, QHeaderView.Fixed
            )  # can set this to ResizeToContents or Stretch
            width = header.sectionSize(column)
            header.setSectionResizeMode(column, QHeaderView.Interactive)
            header.resizeSection(column, min(150, width))