def append_menu_buttons(self):
        """
        Append menus and buttons to appropriate toolbar
        :return:
        """
        # add to QGIS menu
        if PluginSettings.move_to_layers_menu():
            self.iface.addLayerMenu().addMenu(self.menu)
        else:
            # need workaround for WebMenu
            _temp_act = QAction('temp', self.iface.mainWindow())
            self.iface.addPluginToWebMenu("_tmp", _temp_act)
            self.iface.webMenu().addMenu(self.menu)
            self.iface.removePluginWebMenu("_tmp", _temp_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        if PluginSettings.move_to_layers_menu():
            self.tb_action = self.iface.layerToolBar().addWidget(toolbutton)
        else:
            self.tb_action = self.iface.webToolBar().addWidget(toolbutton)
Esempio n. 2
0
    def append_menu_buttons(self):
        """
        Append menus and buttons to appropriate toolbar
        :return:
        """
        # add to QGIS menu
        if PluginSettings.move_to_layers_menu():
            self.iface.addLayerMenu().addMenu(self.menu)
        else:
            # need workaround for WebMenu
            _temp_act = QAction('temp', self.iface.mainWindow())
            self.iface.addPluginToWebMenu("_tmp", _temp_act)
            self.iface.webMenu().addMenu(self.menu)
            self.iface.removePluginWebMenu("_tmp", _temp_act)

        # add to QGIS toolbar
        toolbutton = QToolButton()
        toolbutton.setPopupMode(QToolButton.InstantPopup)
        toolbutton.setMenu(self.menu)
        toolbutton.setIcon(self.menu.icon())
        toolbutton.setText(self.menu.title())
        toolbutton.setToolTip(self.menu.title())
        if PluginSettings.move_to_layers_menu():
            self.tb_action = self.iface.layerToolBar().addWidget(toolbutton)
        else:
            self.tb_action = self.iface.webToolBar().addWidget(toolbutton)
Esempio n. 3
0
    def __init__(self, parent=None):
        super(SettingsDialog, self).__init__(parent)
        self.setupUi(self)
        # self.setFixedSize(self.size())

        self.btnNew.clicked.connect(self.new_connection)
        self.btnEdit.clicked.connect(self.edit_connection)
        self.btnDelete.clicked.connect(self.delete_connection)

        self.populate_connection_list()

        self.chSanitizeRenameFields.setCheckState(
            QtCore.Qt.Checked if NgwApiSettings.get_sanitize_rename_fields() else QtCore.Qt.Unchecked
        )
        self.chSanitizeRenameFields.stateChanged.connect(self.sanitizeOptionsChanged)

        self.chSanitizeFixGeometry.setCheckState(
            QtCore.Qt.Checked if NgwApiSettings.get_sanitize_fix_geometry() else QtCore.Qt.Unchecked
        )
        self.chSanitizeFixGeometry.stateChanged.connect(self.sanitizeOptionsChanged)

        self.cbForceImport.setCheckState(
            QtCore.Qt.Unchecked if NgwApiSettings.get_force_qgis_project_import() else QtCore.Qt.Checked
        )
        self.cbForceImport.stateChanged.connect(self.forceImportChanged)

        self.cbAutoOpenWebMap.setCheckState(
            QtCore.Qt.Checked if PluginSettings.auto_open_web_map_option() else QtCore.Qt.Unchecked
        )
        self.cbAutoOpenWebMap.stateChanged.connect(self.autoOpenWebMapChanged)

        self.cbAutoAddWFS.setCheckState(
            QtCore.Qt.Checked if PluginSettings.auto_add_wfs_option() else QtCore.Qt.Unchecked
        )
        self.cbAutoAddWFS.stateChanged.connect(self.autoAddWFSChanged)
Esempio n. 4
0
    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISProject
        )
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource
        )
        # Hack - qgis delete only one action, we have two same actions
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISProject
        )
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource
        )

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&NextGIS Connect'),
                action)
            self.iface.removeToolBarIcon(action)

        mw = self.iface.mainWindow()
        PluginSettings.set_dock_area(mw.dockWidgetArea(self.dockWidget))
        PluginSettings.set_dock_floating(self.dockWidget.isFloating())
        PluginSettings.set_dock_pos(self.dockWidget.pos())
        PluginSettings.set_dock_size(self.dockWidget.size())
        PluginSettings.set_dock_visibility(self.dockWidget.isVisible())

        self.iface.removeDockWidget(self.dockWidget)
Esempio n. 5
0
    def add_layers_from_ngw(self):
        #import pydevd
        #pydevd.settrace('localhost', port=5566, stdoutToServer=True, stderrToServer=True, suspend=False)

        conn_name = PluginSettings.get_selected_ngw_connection_name()
        if not conn_name:
            error_message = self.tr('You must configure at least one connection!')
            self.iface.messageBar().pushMessage(self.tr('WARNING'),
                                                error_message,
                                                level=QgsMessageBar.WARNING)
            QgsMessageLog.logMessage(error_message, level=QgsMessageLog.WARNING)
            return
        conn_sett = PluginSettings.get_ngw_connection(conn_name)

        #setup ngw api
        rsc_factory = NGWResourceFactory(conn_sett)
        types_reg = rsc_factory.resources_types_registry
        types_reg[NGWFoclStruct.type_id] = NGWFoclStruct
        types_reg[NGWFoclProject.type_id] = NGWFoclProject
        types_reg[NGWSituationPlan.type_id] = NGWSituationPlan

        try:
            root_rsc = rsc_factory.get_root_resource()
        except Exception, e:
            error_message = self.tr('Error on fetch resources: ') + e.message
            self.iface.messageBar().pushMessage(self.tr('ERROR'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)
            QgsMessageLog.logMessage(error_message, level=QgsMessageLog.CRITICAL)
            return
Esempio n. 6
0
    def unload(self):
        # """Removes the plugin menu item and icon from QGIS GUI."""
        # self.iface.legendInterface().removeLegendLayerAction(
        #     self.dockWidget.inner_control.actionImportQGISProject
        # )
        # self.iface.legendInterface().removeLegendLayerAction(
        #     self.dockWidget.inner_control.actionImportQGISResource
        # )
        # Hack - qgis delete only one action, we have two same actions
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource
        )
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource
        )
        self.iface.legendInterface().removeLegendLayerAction(
            self.dockWidget.inner_control.actionImportUpdateStyle
        )

        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&NextGIS Connect'),
                action)
            self.iface.removeToolBarIcon(action)

        mw = self.iface.mainWindow()
        PluginSettings.set_dock_area(mw.dockWidgetArea(self.dockWidget))
        PluginSettings.set_dock_floating(self.dockWidget.isFloating())
        PluginSettings.set_dock_pos(self.dockWidget.pos())
        PluginSettings.set_dock_size(self.dockWidget.size())
        PluginSettings.set_dock_visibility(self.dockWidget.isVisible())

        self.iface.removeDockWidget(self.dockWidget)
 def fill_pages(self):
     # common
     self.chkMoveToLayersMenu.setChecked(PluginSettings.move_to_layers_menu())
     self.chkEnableOTF3857.setChecked(PluginSettings.enable_otf_3857())
     self.chkShowMessagesInBar.setChecked(PluginSettings.show_messages_in_bar())
     # tiled layers
     self.spnConnCount.setValue(PluginSettings.default_tile_layer_conn_count())
     self.spnCacheExp.setValue(QGISSettings.get_default_tile_expiry())
     self.spnNetworkTimeout.setValue(QGISSettings.get_default_network_timeout())
 def saveSettings(self):
     hideDSidList = []
     for groupIndex in range(0, self.rootItem.childCount()):
         groupItem = self.rootItem.child(groupIndex)
         for dsIndex in range(0, groupItem.childCount()):
             dsItem = groupItem.child(dsIndex)
             if dsItem.checkState(self.COLUMN_VISIBILITY) == Qt.Unchecked:
                 hideDSidList.append(dsItem.data(self.COLUMN_GROUP_DS, Qt.UserRole).id)
     PluginSettings.set_hide_ds_id_list(hideDSidList)
Esempio n. 9
0
 def new_connection(self):
     dlg = NGWConnectionEditDialog()
     dlg.leName.setText('Compulink')
     dlg.leUrl.setText('http://gis.compulink.ru/')
     dlg.leUser.setFocus()
     if dlg.exec_():
         conn_sett = dlg.ngw_connection_settings
         PluginSettings.save_ngw_connection(conn_sett)
         self.populate_connection_list()
     del dlg
 def saveSettings(self):
     hideDSidList = []
     for groupIndex in range(0, self.rootItem.childCount()):
         groupItem = self.rootItem.child(groupIndex)
         for dsIndex in range(0, groupItem.childCount()):
             dsItem = groupItem.child(dsIndex)
             if dsItem.checkState(self.COLUMN_VISIBILITY) == Qt.Unchecked:
                 hideDSidList.append(
                     dsItem.data(self.COLUMN_GROUP_DS, Qt.UserRole).id)
     PluginSettings.set_hide_ds_id_list(hideDSidList)
 def remove_server_panel(self):
     mw = self.iface.mainWindow()
     PluginSettings.set_server_dock_area(mw.dockWidgetArea(self.server_toolbox))
     PluginSettings.set_server_dock_visibility(self.server_toolbox.isVisible())
     # PluginSettings.set_dock_floating(self.__quick_tlb.isFloating())
     # PluginSettings.set_dock_pos(self.__quick_tlb.pos())
     # PluginSettings.set_dock_size(self.__quick_tlb.size())
     # PluginSettings.set_dock_geocoder_name(self.__quick_tlb.get_active_geocoder_name())
     self.iface.removeDockWidget(self.server_toolbox)
     del self.server_toolbox
Esempio n. 12
0
 def showBarMessage(self,
                    text,
                    level=QgsMessageBar.INFO,
                    duration=0,
                    title=None):
     if PluginSettings.show_messages_in_bar():
         if title is None:
             title = PluginSettings.product_name()
         self.emit(SIGNAL("showBarMessage(QString, QString, int, int)"),
                   title, text, level, duration)
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources.load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr('Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(), info_message)
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(), error_message)
Esempio n. 14
0
 def fill_pages(self):
     # common
     self.chkMoveToLayersMenu.setChecked(
         PluginSettings.move_to_layers_menu())
     self.chkEnableOTF3857.setChecked(PluginSettings.enable_otf_3857())
     self.chkShowMessagesInBar.setChecked(
         PluginSettings.show_messages_in_bar())
     # tiled layers
     self.spnConnCount.setValue(
         PluginSettings.default_tile_layer_conn_count())
     self.spnCacheExp.setValue(QGISSettings.get_default_tile_expiry())
     self.spnNetworkTimeout.setValue(
         QGISSettings.get_default_network_timeout())
Esempio n. 15
0
    def open_create_web_map(self, index):
        if PluginSettings.auto_open_web_map_option() is False:
            return

        ngw_resource = index.data(Qt.UserRole)
        url = ngw_resource.get_display_url()
        QDesktopServices.openUrl(QUrl(url))
 def save_settings(self):
     # common
     PluginSettings.set_move_to_layers_menu(self.chkMoveToLayersMenu.isChecked())
     PluginSettings.set_enable_otf_3857(self.chkEnableOTF3857.isChecked())
     PluginSettings.set_show_messages_in_bar(self.chkShowMessagesInBar.isChecked())
     # tiled layers
     PluginSettings.set_default_tile_layer_conn_count(self.spnConnCount.value())
     QGISSettings.set_default_tile_expiry(self.spnCacheExp.value())
     QGISSettings.set_default_network_timeout(self.spnNetworkTimeout.value())
Esempio n. 17
0
    def edit_connection(self):
        conn_name = self.cmbConnections.currentText()
        conn_sett = None

        if conn_name is not None:
            conn_sett = PluginSettings.get_ngw_connection(conn_name)

        dlg = NGWConnectionEditDialog(ngw_connection_settings=conn_sett)
        if dlg.exec_():
            conn_sett = dlg.ngw_connection_settings
            # if conn was renamed - remove old
            if conn_name is not None and conn_name != conn_sett.connection_name:
                PluginSettings.remove_ngw_connection(conn_name)
            # save new
            PluginSettings.save_ngw_connection(conn_sett)
            self.populate_connection_list()
        del dlg
Esempio n. 18
0
    def populate_connection_list(self):
        self.cmbConnections.clear()
        self.cmbConnections.addItems(PluginSettings.get_ngw_connection_names())

        last_connection = PluginSettings.get_selected_ngw_connection_name()
        idx = self.cmbConnections.findText(last_connection)
        if idx == -1 and self.cmbConnections.count() > 0:
            self.cmbConnections.setCurrentIndex(0)
        else:
            self.cmbConnections.setCurrentIndex(idx)

        if self.cmbConnections.count() == 0:
            self.btnEdit.setEnabled(False)
            self.btnDelete.setEnabled(False)
        else:
            self.btnEdit.setEnabled(True)
            self.btnDelete.setEnabled(True)
Esempio n. 19
0
    def get_contrib(self):
        QgsApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        try:
            ExtraSources().load_contrib_pack()
            QgsApplication.restoreOverrideCursor()
            info_message = self.tr(
                'Last version of contrib pack was downloaded!')
            QMessageBox.information(self, PluginSettings.product_name(),
                                    info_message)

            self.dsManagerViewModel.resetModel()
        except:
            QgsApplication.restoreOverrideCursor()
            error_message = self.tr('Error on getting contrib pack: %s %s') % (
                sys.exc_type, sys.exc_value)
            QMessageBox.critical(self, PluginSettings.product_name(),
                                 error_message)
    def __setupModelData(self):
        dsList = DataSourcesList().data_sources.values()
        groupInfoList = GroupsList().groups
        groupsItems = []
        groups = []
        for ds in dsList:
            if ds.group in groups:
                group_item = groupsItems[groups.index(ds.group)]
            else:
                group_item = QtGui.QTreeWidgetItem()
                group_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole,
                                   ds.group)
                group_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
                group_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole,
                                   ds.category)
                group_item.setCheckState(self.COLUMN_VISIBILITY, Qt.Unchecked)

                groupInfo = groupInfoList.get(ds.group)
                if groupInfo is not None:
                    group_item.setIcon(self.COLUMN_GROUP_DS,
                                       QIcon(groupInfo.icon))
                else:
                    group_item.setData(
                        self.COLUMN_GROUP_DS, Qt.DisplayRole,
                        ds.group + " (%s!)" % self.tr("group not found"))
                group_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole,
                                   groupInfo)

                groups.append(ds.group)
                groupsItems.append(group_item)
                self.rootItem.addChild(group_item)

            ds_item = QtGui.QTreeWidgetItem()
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole, ds.alias)
            ds_item.setIcon(self.COLUMN_GROUP_DS, QIcon(ds.icon_path))
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole, ds)
            ds_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
            ds_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole, ds.category)

            ds_check_state = Qt.Checked
            if ds.id in PluginSettings.get_hide_ds_id_list():
                ds_check_state = Qt.Unchecked
            ds_item.setCheckState(self.COLUMN_VISIBILITY, ds_check_state)

            if group_item.childCount() != 0 and group_item.checkState(
                    1) != ds_check_state:
                group_item.setCheckState(self.COLUMN_VISIBILITY,
                                         Qt.PartiallyChecked)
            else:
                group_item.setCheckState(self.COLUMN_VISIBILITY,
                                         ds_check_state)

            group_item.addChild(ds_item)
    def build_menu_tree(self):
        # Main Menu
        self.menu.clear()

        self.groups_list = GroupsList()
        self.ds_list = DataSourcesList()

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        ds_hide_list = PluginSettings.get_hide_ds_id_list()

        for ds in data_sources:
            if ds.id in ds_hide_list:
                continue
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        self.menu.addSeparator()
        icon_set_nearest_scale_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        set_nearest_scale_act = QAction(QIcon(icon_set_nearest_scale_path), self.tr('Set proper scale'), self.iface.mainWindow())
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + '/icons/mActionSettings.png'  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path), self.tr('Set SlippyMap scales'), self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        #self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + '/icons/mapservices.png'
        server_panel_act = self.server_toolbox.toggleViewAction()
        server_panel_act.setIcon(QIcon(icon_settings_path))
        server_panel_act.setText(self.tr('Search QMS'))
        self.service_actions.append(server_panel_act)
        self.menu.addAction(server_panel_act)

        icon_settings_path = self.plugin_dir + '/icons/mActionSettings.png'
        settings_act = QAction(QIcon(icon_settings_path), self.tr('Settings'), self.iface.mainWindow())
        self.service_actions.append(settings_act)
        settings_act.triggered.connect(self.show_settings_dialog)
        self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + '/icons/mActionAbout.png'
        info_act = QAction(QIcon(icon_about_path), self.tr('About'), self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)
    def show_selection_dialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        else:
            path = PluginSettings.last_icon_path()

        if self.is_folder:
            folder = QFileDialog.getExistingDirectory(self, self.dialog_title, path)
            if folder:
                self.leText.setText(folder)
                PluginSettings.set_last_icon_path(os.path.dirname(folder))
        else:
            filename = QFileDialog.getOpenFileName(self, self.dialog_title, path, self.ext)
            if filename:
                self.leText.setText(filename)
                PluginSettings.set_last_icon_path(os.path.dirname(filename))
Esempio n. 23
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # i18n support
        override_locale = QSettings().value('locale/overrideFlag', False, type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale', '', type=unicode)

        self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path, locale_full_name[0:2])
        if QFileInfo(self.locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

        # menu && toolbars
        self.menu_name = self.tr(u'&RuGeocoder')
        self.toolbar = self.iface.addToolBar(self.menu_name)
        self.toolbar.setObjectName(u'RuGeocoderToolbar')

        # instances
        self.__converter_dlg = ConverterDialog()
        self.__geocoder_dlg = BatchGeocodingDialog()

        # Dock tree panel
        self.__quick_tlb = QuickGeocodingToolbox(self.iface)
        self.iface.addDockWidget(PluginSettings.dock_area(), self.__quick_tlb)
        self.__quick_tlb.setFloating(PluginSettings.dock_floating())
        self.__quick_tlb.resize(PluginSettings.dock_size())
        self.__quick_tlb.move(PluginSettings.dock_pos())
        self.__quick_tlb.setVisible(PluginSettings.dock_visibility())
        self.__quick_tlb.set_active_geocoder(PluginSettings.dock_geocoder_name())
        self.__quick_tlb.setWindowIcon(QIcon(path.join(_current_path, 'edit-find-project.png')))
Esempio n. 24
0
    def initGui(self):
        # import pydevd
        # pydevd.settrace('localhost', port=5566, stdoutToServer=True, stderrToServer=True, suspend=False)

        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        # Dock tree panel
        self.dockWidget = TreePanel(self.iface, self.iface.mainWindow())
        self.iface.addDockWidget(PluginSettings.dock_area(), self.dockWidget)
        self.dockWidget.setFloating(PluginSettings.dock_floating())
        self.dockWidget.resize(PluginSettings.dock_size())
        self.dockWidget.move(PluginSettings.dock_pos())
        self.dockWidget.setVisible(PluginSettings.dock_visibility())

        # Tools for NGW communicate
        icon_path = self.plugin_dir + '/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Show/Hide NextGIS Connect panel'),
            checkable=True,
            is_checked=PluginSettings.dock_visibility(),
            callback=self.dockWidget.setVisible,
            parent=self.iface.mainWindow())

        # self.iface.legendInterface().addLegendLayerAction(
        #     self.dockWidget.inner_control.actionImportQGISProject,
        #     self.tr(u"NextGIS Connect"),
        #     u"",
        #     QgsMapLayer.RasterLayer,
        #     True
        # )
        # self.iface.legendInterface().addLegendLayerAction(
        #     self.dockWidget.inner_control.actionImportQGISProject,
        #     self.tr(u"NextGIS Connect"),
        #     u"",
        #     QgsMapLayer.VectorLayer,
        #     True
        # )

        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.RasterLayer,
            True
        )
        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.VectorLayer,
            True
        )
        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportUpdateStyle,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.VectorLayer,
            True
        )
Esempio n. 25
0
    def show_selection_dialog(self):
        # Find the file dialog's working directory
        settings = QSettings()
        text = self.leText.text()
        if os.path.isdir(text):
            path = text
        elif os.path.isdir(os.path.dirname(text)):
            path = os.path.dirname(text)
        else:
            path = PluginSettings.last_icon_path()

        if self.is_folder:
            folder = QFileDialog.getExistingDirectory(self, self.dialog_title,
                                                      path)
            if folder:
                self.leText.setText(folder)
                PluginSettings.set_last_icon_path(os.path.dirname(folder))
        else:
            filename = QFileDialog.getOpenFileName(self, self.dialog_title,
                                                   path, self.ext)
            if filename:
                self.leText.setText(filename)
                PluginSettings.set_last_icon_path(os.path.dirname(filename))
    def insert_layer(self):
        #TODO: need factory!
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias), ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            if ds.tms_y_origin_top is not None:
                service_info.yOriginTop = ds.tms_y_origin_top
            service_info.epsg_crs_id = ds.tms_epsg_crs_id
            service_info.postgis_crs_id = ds.tms_postgis_crs_id
            service_info.custom_proj = ds.tms_custom_proj
            layer = TileLayer(self, service_info, False)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u''
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(',')
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += '&layers='+'&layers='.join(layers)+'&styles='*len(layers)
            qgis_wms_uri += '&url=' + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias), KNOWN_DRIVERS.WMS.lower())

        if not layer.isValid():
            error_message = self.tr('Layer %s can\'t be added to the map!') % ds.alias
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)
            QgsMessageLog.logMessage(error_message, level=QgsMessageLog.CRITICAL)
        else:
            # Set attribs
            layer.setAttribution(ds.copyright_text)
            layer.setAttributionUrl(ds.copyright_link)
            # Insert to bottom
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            toc_root = QgsProject.instance().layerTreeRoot()
            toc_root.insertLayer(len(toc_root.children()), layer)
            # Save link
            self.service_layers.append(layer)
            # Set OTF CRS Transform for map
            if PluginSettings.enable_otf_3857() and ds.type == KNOWN_DRIVERS.TMS:
                self.iface.mapCanvas().setCrsTransformEnabled(True)
                self.iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)
Esempio n. 27
0
    def save_settings(self):
        # common
        PluginSettings.set_move_to_layers_menu(
            self.chkMoveToLayersMenu.isChecked())
        PluginSettings.set_enable_otf_3857(self.chkEnableOTF3857.isChecked())
        PluginSettings.set_show_messages_in_bar(
            self.chkShowMessagesInBar.isChecked())
        # tiled layers
        PluginSettings.set_default_tile_layer_conn_count(
            self.spnConnCount.value())
        QGISSettings.set_default_tile_expiry(self.spnCacheExp.value())
        QGISSettings.set_default_network_timeout(
            self.spnNetworkTimeout.value())
        # contrib pack

        # ds visibility
        self.dsManagerViewModel.saveSettings()
    def build_menu_tree(self):
        # Main Menu
        self.menu.clear()

        self.groups_list = GroupsList()
        self.ds_list = DataSourcesList()

        data_sources = self.ds_list.data_sources.values()
        data_sources.sort(key=lambda x: x.alias or x.id)

        ds_hide_list = PluginSettings.get_hide_ds_id_list()

        for ds in data_sources:
            if ds.id in ds_hide_list:
                continue
            ds.action.triggered.connect(self.insert_layer)
            gr_menu = self.groups_list.get_group_menu(ds.group)
            gr_menu.addAction(ds.action)
            if gr_menu not in self.menu.children():
                self.menu.addMenu(gr_menu)

        # Scales, Settings and About actions
        self.menu.addSeparator()
        icon_set_nearest_scale_path = self.plugin_dir + "/icons/mActionSettings.png"  # TODO change icon
        set_nearest_scale_act = QAction(
            QIcon(icon_set_nearest_scale_path), self.tr("Set proper scale"), self.iface.mainWindow()
        )
        set_nearest_scale_act.triggered.connect(self.set_nearest_scale)
        self.menu.addAction(set_nearest_scale_act)  # TODO: uncomment after fix
        self.service_actions.append(set_nearest_scale_act)

        icon_scales_path = self.plugin_dir + "/icons/mActionSettings.png"  # TODO change icon
        scales_act = QAction(QIcon(icon_scales_path), self.tr("Set SlippyMap scales"), self.iface.mainWindow())
        scales_act.triggered.connect(self.set_tms_scales)
        # self.menu.addAction(scales_act)  # TODO: uncomment after fix
        self.service_actions.append(scales_act)

        icon_settings_path = self.plugin_dir + "/icons/mActionSettings.png"
        settings_act = QAction(QIcon(icon_settings_path), self.tr("Settings"), self.iface.mainWindow())
        self.service_actions.append(settings_act)
        settings_act.triggered.connect(self.show_settings_dialog)
        self.menu.addAction(settings_act)

        icon_about_path = self.plugin_dir + "/icons/mActionAbout.png"
        info_act = QAction(QIcon(icon_about_path), self.tr("About"), self.iface.mainWindow())
        self.service_actions.append(info_act)
        info_act.triggered.connect(self.info_dlg.show)
        self.menu.addAction(info_act)
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__)

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(
            self.plugin_dir,
            'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr('Extra dirs for %s can\'t be created: %s %s') % (PluginSettings.product_name(),
                                                                                      sys.exc_type,
                                                                                      sys.exc_value)
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None
Esempio n. 30
0
    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface
        # initialize plugin directory
        self.plugin_dir = os.path.dirname(__file__).decode(
            sys.getfilesystemencoding())

        # initialize locale
        self.translator = QTranslator()

        self.locale = Locale.get_locale()
        locale_path = os.path.join(
            self.plugin_dir, 'i18n',
            'QuickMapServices_{}.qm'.format(self.locale))
        if os.path.exists(locale_path):
            self.translator.load(locale_path)
            if qVersion() > '4.3.3':
                QCoreApplication.installTranslator(self.translator)

        self.custom_translator = CustomTranslator()
        QCoreApplication.installTranslator(self.custom_translator)

        # Create the dialog (after translation) and keep reference
        self.info_dlg = AboutDialog()

        # Check Contrib and User dirs
        try:
            ExtraSources.check_extra_dirs()
        except:
            error_message = self.tr(
                'Extra dirs for %s can\'t be created: %s %s') % (
                    PluginSettings.product_name(), sys.exc_type, sys.exc_value)
            self.iface.messageBar().pushMessage(self.tr('Error'),
                                                error_message,
                                                level=QgsMessageBar.CRITICAL)

        # Declare instance attributes
        self.service_actions = []
        self.service_layers = []  # TODO: id and smart remove
        self._scales_list = None
    def __setupModelData(self):
        dsList = DataSourcesList().data_sources.values()
        groupInfoList = GroupsList().groups
        groupsItems = []
        groups = []
        for ds in dsList:
            if ds.group in groups:
                group_item = groupsItems[groups.index(ds.group)]
            else:
                group_item = QtGui.QTreeWidgetItem()
                group_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole, ds.group)
                group_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
                group_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole, ds.category)
                group_item.setCheckState(self.COLUMN_VISIBILITY, Qt.Unchecked)

                groupInfo = groupInfoList.get(ds.group)
                if groupInfo is not None:
                    group_item.setIcon(self.COLUMN_GROUP_DS, QIcon(groupInfo.icon))
                else:
                    group_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole, ds.group + " (%s!)" % self.tr("group not found"))
                group_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole, groupInfo)

                groups.append(ds.group)
                groupsItems.append(group_item)
                self.rootItem.addChild(group_item)

            ds_item = QtGui.QTreeWidgetItem()
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.DisplayRole, ds.alias)
            ds_item.setIcon(self.COLUMN_GROUP_DS, QIcon(ds.icon_path))
            ds_item.setData(self.COLUMN_GROUP_DS, Qt.UserRole, ds)
            ds_item.setData(self.COLUMN_VISIBILITY, Qt.DisplayRole, "")
            ds_item.setData(self.COLUMN_SOURCE, Qt.DisplayRole, ds.category)

            ds_check_state = Qt.Checked
            if ds.id in PluginSettings.get_hide_ds_id_list():
                ds_check_state = Qt.Unchecked
            ds_item.setCheckState(self.COLUMN_VISIBILITY, ds_check_state)

            if group_item.childCount() != 0 and group_item.checkState(1) != ds_check_state:
                group_item.setCheckState(self.COLUMN_VISIBILITY, Qt.PartiallyChecked)
            else:
                group_item.setCheckState(self.COLUMN_VISIBILITY, ds_check_state)

            group_item.addChild(
                ds_item
            )
Esempio n. 32
0
    def initGui(self):
        # import pydevd
        # pydevd.settrace('localhost', port=5566, stdoutToServer=True, stderrToServer=True, suspend=False)

        """Create the menu entries and toolbar icons inside the QGIS GUI."""
        # Dock tree panel
        self.dockWidget = TreePanel(self.iface, self.iface.mainWindow())
        self.iface.addDockWidget(PluginSettings.dock_area(), self.dockWidget)
        self.dockWidget.setFloating(PluginSettings.dock_floating())
        self.dockWidget.resize(PluginSettings.dock_size())
        self.dockWidget.move(PluginSettings.dock_pos())
        self.dockWidget.setVisible(PluginSettings.dock_visibility())

        # Tools for NGW communicate
        icon_path = self.plugin_dir + '/icon.png'
        self.add_action(
            icon_path,
            text=self.tr(u'Show/Hide NextGIS Connect panel'),
            checkable=True,
            is_checked=PluginSettings.dock_visibility(),
            callback=self.dockWidget.setVisible,
            parent=self.iface.mainWindow())

        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISProject,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.RasterLayer,
            True
        )
        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISProject,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.VectorLayer,
            True
        )

        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.RasterLayer,
            True
        )
        self.iface.legendInterface().addLegendLayerAction(
            self.dockWidget.inner_control.actionImportQGISResource,
            self.tr(u"NextGIS Connect"),
            u"",
            QgsMapLayer.VectorLayer,
            True
        )
Esempio n. 33
0
    def __init__(self, iface):
        # Save reference to the QGIS interface
        self.iface = iface

        # i18n support
        override_locale = QSettings().value('locale/overrideFlag',
                                            False,
                                            type=bool)
        if not override_locale:
            locale_full_name = QLocale.system().name()
        else:
            locale_full_name = QSettings().value('locale/userLocale',
                                                 '',
                                                 type=unicode)

        self.locale_path = '%s/i18n/rugeocoder_%s.qm' % (_current_path,
                                                         locale_full_name[0:2])
        if QFileInfo(self.locale_path).exists():
            self.translator = QTranslator()
            self.translator.load(self.locale_path)
            QCoreApplication.installTranslator(self.translator)

        # menu && toolbars
        self.menu_name = self.tr(u'&RuGeocoder')
        self.toolbar = self.iface.addToolBar(self.menu_name)
        self.toolbar.setObjectName(u'RuGeocoderToolbar')

        # instances
        self.__converter_dlg = ConverterDialog()
        self.__geocoder_dlg = BatchGeocodingDialog()

        # Dock tree panel
        self.__quick_tlb = QuickGeocodingToolbox(self.iface)
        self.iface.addDockWidget(PluginSettings.dock_area(), self.__quick_tlb)
        self.__quick_tlb.setFloating(PluginSettings.dock_floating())
        self.__quick_tlb.resize(PluginSettings.dock_size())
        self.__quick_tlb.move(PluginSettings.dock_pos())
        self.__quick_tlb.setVisible(PluginSettings.dock_visibility())
        self.__quick_tlb.set_active_geocoder(
            PluginSettings.dock_geocoder_name())
        self.__quick_tlb.setWindowIcon(
            QIcon(path.join(_current_path, 'edit-find-project.png')))
 def init_server_panel(self):
     self.server_toolbox = QmsServiceToolbox(self.iface)
     self.iface.addDockWidget(PluginSettings.server_dock_area(), self.server_toolbox)
     self.server_toolbox.setWindowIcon(QIcon(self.plugin_dir + '/icons/mapservices.png'))
     self.server_toolbox.setVisible(PluginSettings.server_dock_visibility())
Esempio n. 35
0
import json
import os
import tempfile
import urllib2
from zipfile import ZipFile
import shutil

from PyQt4.QtCore import QUrl, QEventLoop, QFile, QIODevice
from PyQt4.QtNetwork import QNetworkRequest, QNetworkReply
from qgis.core import QgsApplication, QgsNetworkAccessManager

from plugin_settings import PluginSettings

LOCAL_SETTINGS_PATH = os.path.dirname(QgsApplication.qgisUserDbFilePath())
PLUGIN_SETTINGS_PATH = os.path.join(LOCAL_SETTINGS_PATH,
                                    PluginSettings.product_name())

CONTRIBUTE_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'Contribute')
USER_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'User')

DATA_SOURCES_DIR_NAME = 'data_sources'
GROUPS_DIR_NAME = 'groups'

CONTRIBUTE_REPO_URL = 'https://api.github.com/repos/nextgis/quickmapservices_contrib'


class ExtraSources():

    __replies = []

    @classmethod
Esempio n. 36
0
    def __init__(self, plugin, layerDef, creditVisibility=1):
        QgsPluginLayer.__init__(self, TileLayer.LAYER_TYPE, layerDef.title)
        self.plugin = plugin
        self.iface = plugin.iface
        self.layerDef = layerDef
        self.creditVisibility = 1 if creditVisibility else 0

        # set custom properties
        self.setCustomProperty("title", layerDef.title)
        self.setCustomProperty("credit", layerDef.credit)  # TODO: need to remove
        self.setCustomProperty("serviceUrl", layerDef.serviceUrl)
        self.setCustomProperty("yOriginTop", layerDef.yOriginTop)
        self.setCustomProperty("zmin", layerDef.zmin)
        self.setCustomProperty("zmax", layerDef.zmax)
        if layerDef.bbox:
            self.setCustomProperty("bbox", layerDef.bbox.toString())
        self.setCustomProperty("creditVisibility", self.creditVisibility)

        # set standard/custom crs
        self.setCrs(self.CRS_3857)
        try:
            crs = None
            if layerDef.epsg_crs_id is not None:
                crs = QgsCoordinateReferenceSystem(layerDef.epsg_crs_id, QgsCoordinateReferenceSystem.EpsgCrsId)
            if layerDef.postgis_crs_id is not None:
                crs = QgsCoordinateReferenceSystem(layerDef.postgis_crs_id, QgsCoordinateReferenceSystem.PostgisCrsId)
            if layerDef.custom_proj is not None:
                # create form proj4 str
                custom_crs = QgsCoordinateReferenceSystem()
                custom_crs.createFromProj4(layerDef.custom_proj)
                # try to search in db
                searched = custom_crs.findMatchingProj()
                if searched:
                    crs = QgsCoordinateReferenceSystem(searched, QgsCoordinateReferenceSystem.InternalCrsId)
                else:
                    # create custom and use it
                    custom_crs.saveAsUserCRS('quickmapservices %s' % layerDef.title)
                    searched = custom_crs.findMatchingProj()
                    if searched:
                        crs = QgsCoordinateReferenceSystem(searched, QgsCoordinateReferenceSystem.InternalCrsId)
                    else:
                        crs = custom_crs

            if crs:
                self.setCrs(crs)
        except:
            msg = self.tr("Custom crs can't be set for layer {0}!").format(layerDef.title)
            self.showBarMessage(msg, QgsMessageBar.WARNING, 4)

        if layerDef.bbox:
            self.setExtent(BoundingBox.degreesToMercatorMeters(layerDef.bbox).toQgsRectangle())
        else:
            self.setExtent(QgsRectangle(-layerDef.TSIZE1, -layerDef.TSIZE1, layerDef.TSIZE1, layerDef.TSIZE1))
        self.setValid(True)
        self.tiles = None
        self.useLastZoomForPrint = False
        self.canvasLastZoom = 0
        self.setTransparency(LayerDefaultSettings.TRANSPARENCY)
        self.setBlendModeByName(LayerDefaultSettings.BLEND_MODE)
        self.setSmoothRender(LayerDefaultSettings.SMOOTH_RENDER)

        # downloader
        self.downloader = Downloader(self)
        self.downloader.userAgent = QGISSettings.get_default_user_agent()
        self.downloader.default_cache_expiration = QGISSettings.get_default_tile_expiry()
        self.downloader.max_connection = PluginSettings.default_tile_layer_conn_count()  #TODO: Move to INI files
        QObject.connect(self.downloader, SIGNAL("replyFinished(QString, int, int)"), self.networkReplyFinished)

        #network
        self.downloadTimeout = QGISSettings.get_default_network_timeout()

        # multi-thread rendering
        self.eventLoop = None
        QObject.connect(self, SIGNAL("fetchRequest(QStringList)"), self.fetchRequest)
        if self.iface:
            QObject.connect(self, SIGNAL("showMessage(QString, int)"), self.showStatusMessageSlot)
            QObject.connect(self, SIGNAL("showBarMessage(QString, QString, int, int)"), self.showBarMessageSlot)
Esempio n. 37
0
 def showBarMessage(self, text, level=QgsMessageBar.INFO, duration=0, title=None):
     if PluginSettings.show_messages_in_bar():
         if title is None:
             title = PluginSettings.product_name()
         self.emit(SIGNAL("showBarMessage(QString, QString, int, int)"), title, text, level, duration)
Esempio n. 38
0
 def delete_connection(self):
     PluginSettings.remove_ngw_connection(self.cmbConnections.currentText())
     self.populate_connection_list()
Esempio n. 39
0
    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginWebMenu(self.menu_name, self.action_convert)
        self.iface.removePluginWebMenu(self.menu_name, self.action_batch_geocoding)
        self.iface.removePluginWebMenu(self.menu_name, self.action_quick_geocoding)

        self.action_convert = None
        self.action_batch_geocoding = None
        self.action_quick_geocoding = None
        self.toolbar = None

        mw = self.iface.mainWindow()
        PluginSettings.set_dock_area(mw.dockWidgetArea(self.__quick_tlb))
        PluginSettings.set_dock_floating(self.__quick_tlb.isFloating())
        PluginSettings.set_dock_pos(self.__quick_tlb.pos())
        PluginSettings.set_dock_size(self.__quick_tlb.size())
        PluginSettings.set_dock_visibility(self.__quick_tlb.isVisible())
        PluginSettings.set_dock_geocoder_name(self.__quick_tlb.get_active_geocoder_name())

        self.iface.removeDockWidget(self.__quick_tlb)
        del self.__quick_tlb
Esempio n. 40
0
 def autoOpenWebMapChanged(self, state):
     option = (state == QtCore.Qt.Checked)
     PluginSettings.set_auto_open_web_map_option(option)
Esempio n. 41
0
    def __init__(self, plugin, layerDef, creditVisibility=1):
        QgsPluginLayer.__init__(self, TileLayer.LAYER_TYPE, layerDef.title)
        self.plugin = plugin
        self.iface = plugin.iface
        self.layerDef = layerDef
        self.creditVisibility = 1 if creditVisibility else 0

        # set custom properties
        self.setCustomProperty("title", layerDef.title)
        self.setCustomProperty("credit",
                               layerDef.credit)  # TODO: need to remove
        self.setCustomProperty("serviceUrl", layerDef.serviceUrl)
        self.setCustomProperty("yOriginTop", layerDef.yOriginTop)
        self.setCustomProperty("zmin", layerDef.zmin)
        self.setCustomProperty("zmax", layerDef.zmax)
        if layerDef.bbox:
            self.setCustomProperty("bbox", layerDef.bbox.toString())
        self.setCustomProperty("creditVisibility", self.creditVisibility)

        # set standard/custom crs
        self.setCrs(self.CRS_3857)
        try:
            crs = None
            if layerDef.epsg_crs_id is not None:
                crs = QgsCoordinateReferenceSystem(
                    layerDef.epsg_crs_id,
                    QgsCoordinateReferenceSystem.EpsgCrsId)
            if layerDef.postgis_crs_id is not None:
                crs = QgsCoordinateReferenceSystem(
                    layerDef.postgis_crs_id,
                    QgsCoordinateReferenceSystem.PostgisCrsId)
            if layerDef.custom_proj is not None:
                # create form proj4 str
                custom_crs = QgsCoordinateReferenceSystem()
                custom_crs.createFromProj4(layerDef.custom_proj)
                # try to search in db
                searched = custom_crs.findMatchingProj()
                if searched:
                    crs = QgsCoordinateReferenceSystem(
                        searched, QgsCoordinateReferenceSystem.InternalCrsId)
                else:
                    # create custom and use it
                    custom_crs.saveAsUserCRS('quickmapservices %s' %
                                             layerDef.title)
                    searched = custom_crs.findMatchingProj()
                    if searched:
                        crs = QgsCoordinateReferenceSystem(
                            searched,
                            QgsCoordinateReferenceSystem.InternalCrsId)
                    else:
                        crs = custom_crs

            if crs:
                self.setCrs(crs)
        except:
            msg = self.tr("Custom crs can't be set for layer {0}!").format(
                layerDef.title)
            self.showBarMessage(msg, QgsMessageBar.WARNING, 4)

        if layerDef.bbox:
            self.setExtent(
                BoundingBox.degreesToMercatorMeters(
                    layerDef.bbox).toQgsRectangle())
        else:
            self.setExtent(
                QgsRectangle(-layerDef.TSIZE1, -layerDef.TSIZE1,
                             layerDef.TSIZE1, layerDef.TSIZE1))
        self.setValid(True)
        self.tiles = None
        self.useLastZoomForPrint = False
        self.canvasLastZoom = 0
        self.setTransparency(LayerDefaultSettings.TRANSPARENCY)
        self.setBlendModeByName(LayerDefaultSettings.BLEND_MODE)
        self.setSmoothRender(LayerDefaultSettings.SMOOTH_RENDER)

        # downloader
        self.downloader = Downloader(self)
        self.downloader.userAgent = QGISSettings.get_default_user_agent()
        self.downloader.default_cache_expiration = QGISSettings.get_default_tile_expiry(
        )
        self.downloader.max_connection = PluginSettings.default_tile_layer_conn_count(
        )  #TODO: Move to INI files
        QObject.connect(self.downloader,
                        SIGNAL("replyFinished(QString, int, int)"),
                        self.networkReplyFinished)

        #network
        self.downloadTimeout = QGISSettings.get_default_network_timeout()

        # multi-thread rendering
        self.eventLoop = None
        QObject.connect(self, SIGNAL("fetchRequest(QStringList)"),
                        self.fetchRequest)
        if self.iface:
            QObject.connect(self, SIGNAL("showMessage(QString, int)"),
                            self.showStatusMessageSlot)
            QObject.connect(
                self, SIGNAL("showBarMessage(QString, QString, int, int)"),
                self.showBarMessageSlot)
    def insert_layer(self):
        # TODO: need factory!
        layers4add = []
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias), ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            if ds.tms_y_origin_top is not None:
                service_info.yOriginTop = ds.tms_y_origin_top
            service_info.epsg_crs_id = ds.tms_epsg_crs_id
            service_info.postgis_crs_id = ds.tms_postgis_crs_id
            service_info.custom_proj = ds.tms_custom_proj
            layer = TileLayer(self, service_info, False)
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u""
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(",")
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += "&layers=" + "&layers=".join(layers) + "&styles=" * len(layers)
            qgis_wms_uri += "&url=" + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias), KNOWN_DRIVERS.WMS.lower())
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WFS:
            qgis_wfs_uri_base = ds.wfs_url
            o = urlparse.urlparse(qgis_wfs_uri_base)
            request_attrs = dict(urlparse.parse_qsl(o.query))

            layers_str = request_attrs.get("TYPENAME", "")
            layers = layers_str.split(",")
            for layer_name in layers:
                new_request_attrs = request_attrs
                new_request_attrs["TYPENAME"] == layer_name

                url_parts = list(o)
                url_parts[4] = "&".join(["%s=%s" % (k, v) for k, v in new_request_attrs.items()])

                qgis_wfs_uri = urlparse.urlunparse(url_parts)

                layer = QgsVectorLayer(qgis_wfs_uri, "%s - %s" % (self.tr(ds.alias), layer_name), "WFS")
                layers4add.append(layer)

        for layer in layers4add:
            if not layer.isValid():
                error_message = self.tr("Layer %s can't be added to the map!") % ds.alias
                self.iface.messageBar().pushMessage(self.tr("Error"), error_message, level=QgsMessageBar.CRITICAL)
                QgsMessageLog.logMessage(error_message, level=QgsMessageLog.CRITICAL)
            else:
                # Set attribs
                layer.setAttribution(ds.copyright_text)
                layer.setAttributionUrl(ds.copyright_link)
                # Insert to bottom
                QgsMapLayerRegistry.instance().addMapLayer(layer, False)
                toc_root = QgsProject.instance().layerTreeRoot()
                toc_root.insertLayer(len(toc_root.children()), layer)
                # Save link
                self.service_layers.append(layer)
                # Set OTF CRS Transform for map
                if PluginSettings.enable_otf_3857() and ds.type == KNOWN_DRIVERS.TMS:
                    self.iface.mapCanvas().setCrsTransformEnabled(True)
                    self.iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)
Esempio n. 43
0
    def add_created_wfs_service(self, index):
        if PluginSettings.auto_add_wfs_option() is False:
            return

        ngw_resource = index.data(Qt.UserRole)
        add_resource_as_wfs_layers(ngw_resource)
Esempio n. 44
0
    def unload(self):
        # Remove the plugin menu item and icon
        self.iface.removePluginWebMenu(self.menu_name, self.action_convert)
        self.iface.removePluginWebMenu(self.menu_name,
                                       self.action_batch_geocoding)
        self.iface.removePluginWebMenu(self.menu_name,
                                       self.action_quick_geocoding)

        self.action_convert = None
        self.action_batch_geocoding = None
        self.action_quick_geocoding = None
        self.toolbar = None

        mw = self.iface.mainWindow()
        PluginSettings.set_dock_area(mw.dockWidgetArea(self.__quick_tlb))
        PluginSettings.set_dock_floating(self.__quick_tlb.isFloating())
        PluginSettings.set_dock_pos(self.__quick_tlb.pos())
        PluginSettings.set_dock_size(self.__quick_tlb.size())
        PluginSettings.set_dock_visibility(self.__quick_tlb.isVisible())
        PluginSettings.set_dock_geocoder_name(
            self.__quick_tlb.get_active_geocoder_name())

        self.iface.removeDockWidget(self.__quick_tlb)
        del self.__quick_tlb
Esempio n. 45
0
 def reject(self):
     PluginSettings.set_selected_ngw_connection_name(self.cmbConnections.currentText())
     QDialog.reject(self)
Esempio n. 46
0
"""
import json
import os
import tempfile
import urllib2
from zipfile import ZipFile
import shutil

from PyQt4.QtCore import QUrl, QEventLoop, QFile, QIODevice
from PyQt4.QtNetwork import QNetworkRequest, QNetworkReply
from qgis.core import QgsApplication, QgsNetworkAccessManager

from plugin_settings import PluginSettings

LOCAL_SETTINGS_PATH = os.path.dirname(QgsApplication.qgisUserDbFilePath())
PLUGIN_SETTINGS_PATH = os.path.join(LOCAL_SETTINGS_PATH, PluginSettings.product_name())

CONTRIBUTE_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'Contribute')
USER_DIR_PATH = os.path.join(PLUGIN_SETTINGS_PATH, 'User')

DATA_SOURCES_DIR_NAME = 'data_sources'
GROUPS_DIR_NAME = 'groups'

CONTRIBUTE_REPO_URL = 'https://api.github.com/repos/nextgis/quickmapservices_contrib'


class ExtraSources():

    __replies = []

    @classmethod
Esempio n. 47
0
 def save_settings(self):
     # common
     PluginSettings.set_distance_value(self.distSpinner.value())
     PluginSettings.set_timeout_value(self.timeoutSpinner.value())
Esempio n. 48
0
 def autoAddWFSChanged(self, state):
     option = (state == QtCore.Qt.Checked)
     PluginSettings.set_auto_add_wfs_option(option)
Esempio n. 49
0
    def insert_layer(self):
        #TODO: need factory!
        layers4add = []
        action = self.menu.sender()
        ds = action.data()
        if ds.type == KNOWN_DRIVERS.TMS:
            service_info = TileServiceInfo(self.tr(ds.alias),
                                           ds.copyright_text, ds.tms_url)
            service_info.zmin = ds.tms_zmin or service_info.zmin
            service_info.zmax = ds.tms_zmax or service_info.zmax
            if ds.tms_y_origin_top is not None:
                service_info.yOriginTop = ds.tms_y_origin_top
            service_info.epsg_crs_id = ds.tms_epsg_crs_id
            service_info.postgis_crs_id = ds.tms_postgis_crs_id
            service_info.custom_proj = ds.tms_custom_proj
            layer = TileLayer(self, service_info, False)
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.GDAL:
            layer = QgsRasterLayer(ds.gdal_source_file, self.tr(ds.alias))
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WMS:
            qgis_wms_uri = u''
            if ds.wms_params:
                qgis_wms_uri += ds.wms_params
            if ds.wms_layers:
                layers = ds.wms_layers.split(',')
                if layers:
                    if ds.wms_turn_over:
                        layers.reverse()
                    qgis_wms_uri += '&layers=' + '&layers='.join(
                        layers) + '&styles=' * len(layers)
            qgis_wms_uri += '&url=' + ds.wms_url
            layer = QgsRasterLayer(qgis_wms_uri, self.tr(ds.alias),
                                   KNOWN_DRIVERS.WMS.lower())
            layers4add.append(layer)
        if ds.type == KNOWN_DRIVERS.WFS:
            qgis_wfs_uri_base = ds.wfs_url
            o = urlparse.urlparse(qgis_wfs_uri_base)
            request_attrs = dict(urlparse.parse_qsl(o.query))

            layers_str = request_attrs.get('TYPENAME', '')
            layers = layers_str.split(',')
            for layer_name in layers:
                new_request_attrs = request_attrs
                new_request_attrs['TYPENAME'] == layer_name

                url_parts = list(o)
                url_parts[4] = "&".join(
                    ["%s=%s" % (k, v) for k, v in new_request_attrs.items()])

                qgis_wfs_uri = urlparse.urlunparse(url_parts)

                layer = QgsVectorLayer(
                    qgis_wfs_uri, "%s - %s" % (self.tr(ds.alias), layer_name),
                    "WFS")
                layers4add.append(layer)

        for layer in layers4add:
            if not layer.isValid():
                error_message = self.tr(
                    'Layer %s can\'t be added to the map!') % ds.alias
                self.iface.messageBar().pushMessage(
                    self.tr('Error'),
                    error_message,
                    level=QgsMessageBar.CRITICAL)
                QgsMessageLog.logMessage(error_message,
                                         level=QgsMessageLog.CRITICAL)
            else:
                # Set attribs
                layer.setAttribution(ds.copyright_text)
                layer.setAttributionUrl(ds.copyright_link)
                # Insert to bottom
                QgsMapLayerRegistry.instance().addMapLayer(layer, False)
                toc_root = QgsProject.instance().layerTreeRoot()
                toc_root.insertLayer(len(toc_root.children()), layer)
                # Save link
                self.service_layers.append(layer)
                # Set OTF CRS Transform for map
                if PluginSettings.enable_otf_3857(
                ) and ds.type == KNOWN_DRIVERS.TMS:
                    self.iface.mapCanvas().setCrsTransformEnabled(True)
                    self.iface.mapCanvas().setDestinationCrs(
                        TileLayer.CRS_3857)
Esempio n. 50
0
    def run(self):
        xx = str(self.__xx)
        yy = str(self.__yy)

        if abs(float(xx)) > 180 or abs(float(yy)) > 90:
            QgsMessageLog.logMessage(
                self.tr('Worker: %s, %s are wrong coords!') % (xx, yy),
                self.tr('OSMInfo'),
                QgsMessageLog.INFO
            )

            self.gotError.emit(self.tr('Worker: %s, %s are wrong coords!') % (xx, yy))
            return

        url = 'http://overpass-api.de/api/interpreter'
        request = QNetworkRequest(QUrl(url))
        request.setHeader(QNetworkRequest.ContentTypeHeader, 'application/x-www-form-urlencoded');

        qnam = QgsNetworkAccessManager.instance()

        # around request
        dist = PluginSettings.distance_value()

        request_data = '[timeout:30][out:json];(node(around:%s,%s,%s);way(around:%s,%s,%s));out tags geom;relation(around:%s,%s,%s);' % (dist, yy, xx, dist, yy, xx, dist, yy, xx)
        reply1 = qnam.post(request, QByteArray(request_data))
        loop = QEventLoop()
        reply1.finished.connect(loop.quit)
        loop.exec_()
        if reply1.error() != QNetworkReply.NoError:
            reply1.deleteLater()
            self.gotError.emit(self.tr('Error getting data from the server'))
            return
        try:
            data = reply1.readAll()
            l1 = json.loads(str(data))['elements']
            reply1.deleteLater()
        except:
            self.gotError.emit(self.tr('Error parsing data'))
            return
        finally:
            reply1.deleteLater()


        request_data = '[timeout:30][out:json];is_in(%s,%s)->.a;way(pivot.a);out tags geom;relation(pivot.a);out tags bb;' % (yy, xx)
        reply2 = qnam.post(request, QByteArray(request_data))
        loop = QEventLoop()
        reply2.finished.connect(loop.quit)
        loop.exec_()
        if reply2.error() != QNetworkReply.NoError:
            reply2.deleteLater()
            self.gotError.emit(self.tr('Error getting data from the server'))
            return
        try:
            data = reply2.readAll()
            l2 = json.loads(str(data))['elements']
        except:
            self.gotError.emit(self.tr('Error parsing data'))
            return
        finally:
            reply2.deleteLater()

        self.gotData.emit(l1, l2)
Esempio n. 51
0
 def fill_pages(self):
     # common
     self.distSpinner.setValue(PluginSettings.distance_value())
     self.timeoutSpinner.setValue(PluginSettings.timeout_value())
Esempio n. 52
0
    def run(self):
        xx = str(self.__xx)
        yy = str(self.__yy)

        if abs(float(xx)) > 180 or abs(float(yy)) > 90:
            QgsMessageLog.logMessage(
                self.tr('Worker: %s, %s are wrong coords!') % (xx, yy),
                self.tr('OSMInfo'),
                QgsMessageLog.INFO
            )

            self.gotError.emit(self.tr('Worker: %s, %s are wrong coords!') % (xx, yy))
            return

        url = 'http://overpass-api.de/api/interpreter'
        request = QNetworkRequest(QUrl(url))
        request.setHeader(QNetworkRequest.ContentTypeHeader, 'application/x-www-form-urlencoded');

        qnam = QgsNetworkAccessManager.instance()

        # around request
        dist = PluginSettings.distance_value()
        timeout = PluginSettings.timeout_value()

        request_data = '[timeout:%s][out:json];(node(around:%s,%s,%s);way(around:%s,%s,%s);relation(around:%s,%s,%s););out tags geom;' % (timeout, dist, yy, xx, dist, yy, xx, dist, yy, xx)
        reply1 = qnam.post(request, QByteArray(request_data))
        loop = QEventLoop()
        reply1.finished.connect(loop.quit)
        loop.exec_()
        if reply1.error() != QNetworkReply.NoError:
            reply1.deleteLater()
            self.gotError.emit(self.tr('Error getting data from the server'))
            return
        try:
            data = reply1.readAll()
            l1 = json.loads(str(data))['elements']
            reply1.deleteLater()
        except:
            self.gotError.emit(self.tr('Error parsing data'))
            return
        finally:
            reply1.deleteLater()


        request_data = '[timeout:%s][out:json];is_in(%s,%s)->.a;way(pivot.a);out tags geom;relation(pivot.a);out geom;' % (timeout, yy, xx)
        reply2 = qnam.post(request, QByteArray(request_data))
        loop = QEventLoop()
        reply2.finished.connect(loop.quit)
        loop.exec_()
        if reply2.error() != QNetworkReply.NoError:
            reply2.deleteLater()
            self.gotError.emit(self.tr('Error getting data from the server'))
            return
        try:
            data = reply2.readAll()
            l2 = json.loads(str(data))['elements']
        except:
            self.gotError.emit(self.tr('Error parsing data'))
            return
        finally:
            reply2.deleteLater()

        self.gotData.emit(l1, l2)
Esempio n. 53
0
 def save_settings(self):
     # common
     PluginSettings.set_distance_value(self.distSpinner.value())
Esempio n. 54
0
def add_layer_to_map(ds):
    layers4add = []

    if ds.type.lower() == KNOWN_DRIVERS.TMS.lower():
        service_info = TileServiceInfo(tr(ds.alias), ds.copyright_text,
                                       ds.tms_url)
        service_info.zmin = ds.tms_zmin or service_info.zmin
        service_info.zmax = ds.tms_zmax or service_info.zmax
        if ds.tms_y_origin_top is not None:
            service_info.yOriginTop = ds.tms_y_origin_top
        service_info.epsg_crs_id = ds.tms_epsg_crs_id
        service_info.postgis_crs_id = ds.tms_postgis_crs_id
        service_info.custom_proj = ds.tms_custom_proj

        if ds.tms_tile_ranges is not None:  # needs try block & checks that keys are integers etc..
            service_info.tile_ranges = ast.literal_eval(ds.tms_tile_ranges)
        if ds.tms_tsize1 is not None:
            service_info.tsize1 = ds.tms_tsize1
        if ds.tms_origin_x is not None:
            service_info.originX = ds.tms_origin_x
        if ds.tms_origin_y is not None:
            service_info.originY = ds.tms_origin_y

        layer = TileLayer(service_info, False)
        layers4add.append(layer)
    if ds.type.lower() == KNOWN_DRIVERS.GDAL.lower():
        layer = QgsRasterLayer(ds.gdal_source_file, tr(ds.alias))
        layers4add.append(layer)
    if ds.type.lower() == KNOWN_DRIVERS.WMS.lower():
        qgis_wms_uri = u''
        if ds.wms_params:
            qgis_wms_uri += ds.wms_params
        if ds.wms_layers:
            layers = ds.wms_layers.split(',')
            if layers:
                if ds.wms_turn_over:
                    layers.reverse()
                qgis_wms_uri += '&layers=' + '&layers='.join(
                    layers) + '&styles=' * len(layers)
        qgis_wms_uri += '&url=' + ds.wms_url
        layer = QgsRasterLayer(qgis_wms_uri, tr(ds.alias),
                               KNOWN_DRIVERS.WMS.lower())
        layers4add.append(layer)
    if ds.type.lower() == KNOWN_DRIVERS.WFS.lower():
        qgis_wfs_uri_base = ds.wfs_url
        o = urlparse.urlparse(qgis_wfs_uri_base)
        request_attrs = dict(urlparse.parse_qsl(o.query))

        layers_str = request_attrs.get('TYPENAME', '')
        layers = layers_str.split(',')
        for layer_name in layers:
            new_request_attrs = request_attrs
            new_request_attrs['TYPENAME'] == layer_name

            url_parts = list(o)
            url_parts[4] = "&".join(
                ["%s=%s" % (k, v) for k, v in new_request_attrs.items()])

            qgis_wfs_uri = urlparse.urlunparse(url_parts)

            layer = QgsVectorLayer(qgis_wfs_uri,
                                   "%s - %s" % (tr(ds.alias), layer_name),
                                   "WFS")
            layers4add.append(layer)

    if ds.type.lower() == KNOWN_DRIVERS.GEOJSON.lower():
        layer = QgsVectorLayer(ds.geojson_url, tr(ds.alias), "ogr")
        layers4add.append(layer)

    for layer in layers4add:
        if not layer.isValid():
            error_message = tr(
                'Layer %s can\'t be added to the map!') % ds.alias
            iface.messageBar().pushMessage(tr('Error'),
                                           error_message,
                                           level=QgsMessageBar.CRITICAL)
            QgsMessageLog.logMessage(error_message,
                                     level=QgsMessageLog.CRITICAL)
        else:
            # Set attribs
            layer.setAttribution(ds.copyright_text)
            layer.setAttributionUrl(ds.copyright_link)
            # Insert layer
            toc_root = QgsProject.instance().layerTreeRoot()
            if ds.type.lower() in (KNOWN_DRIVERS.WMS.lower(),
                                   KNOWN_DRIVERS.TMS.lower()):
                position = len(
                    toc_root.children())  # Insert to bottom if wms\tms
            else:
                position = 0  # insert to top
            QgsMapLayerRegistry.instance().addMapLayer(layer, False)
            toc_root.insertLayer(position, layer)

            # Save link
            service_layers.append(layer)
            # Set OTF CRS Transform for map
            if PluginSettings.enable_otf_3857(
            ) and ds.type == KNOWN_DRIVERS.TMS:
                iface.mapCanvas().setCrsTransformEnabled(True)
                iface.mapCanvas().setDestinationCrs(TileLayer.CRS_3857)
Esempio n. 55
0
 def fill_pages(self):
     # common
     self.distSpinner.setValue(PluginSettings.distance_value())