class UniumPlugin: """QGIS Plugin Implementation.""" 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 locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'UniumPlugin_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&UniumPlugin') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.pluginToolBar() #self.iface.addToolBar(u'UniumPlugin') self.toolbar.setObjectName(u'UniumPlugin') #print "** INITIALIZING UniumPlugin" self.pluginIsActive = False self.dockwidget = None # initialize dict for saving data about importing sml self.sml_data = {} # initialize layers data self.categories = {} self.layers = {} self.src_info = {} self.selected_id = u'' self.selected_files = [] self.mercator = QgsCoordinateReferenceSystem() mercatorWKT = u'PROJCS["WGS 84 / Pseudo-Mercator",GEOGCS["WGS 84",DATUM["WGS_1984",SPHEROID["WGS 84",6378137,298.257223563,AUTHORITY["EPSG","7030"]],AUTHORITY["EPSG","6326"]],PRIMEM["Greenwich",0,AUTHORITY["EPSG","8901"]],UNIT["degree",0.0174532925199433,AUTHORITY["EPSG","9122"]],AUTHORITY["EPSG","4326"]],PROJECTION["Mercator_1SP"],PARAMETER["central_meridian",0],PARAMETER["scale_factor",1],PARAMETER["false_easting",0],PARAMETER["false_northing",0],UNIT["metre",1,AUTHORITY["EPSG","9001"]],AXIS["X",EAST],AXIS["Y",NORTH],EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs"],AUTHORITY["EPSG","3857"]]' mercatorProj4 = u'+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs' #self.mercator.createFromProj4() self.mercator.createFromWkt(mercatorWKT) # default configuration self.default_config = """{"files_folder": "", "write_block": 50, "signs": {"school_2zone": {"alias": u"Школа (2 зона)", "png_src": ["blue.png"], "filename": "circle_house_blue"}, "school_3zone": {"alias": u"Школа (3 зона)", "png_src": ["green.png"], "filename": "circle_house_green"}, "school_1zone": {"alias": u"Школа (1 зона)", "png_src": ["red.png"], "filename": "circle_house_red"}, "school_repeat": {"alias": u"Школа (повтор)", "png_src": ["dopprohod.png","doprohod.png","yellow.png"], "filename": "circle_house_yellow"}, "school_center": {"alias": u"Образовательный центр", "png_src": ["stationnew.png"], "filename": "circle_house_black"}, "school_bad": {"alias": u"Не подходит", "png_src": ["neproshel.png"], "filename": "circle_cross2"}, "school_stop": {"alias": u"Не пустили", "png_src": ["nepustili.png"], "filename": "circle_minus2"}, "school_adv": {"alias": u"Объявления", "png_src": ["obyavlenie.png"], "filename": "triangle_warning2"}, "school_passed": {"alias": u"Пройдена", "png_src": ["proshel.png"], "filename": "circle_checktick2"}, "school_atwork": {"alias": u"Выдана агенту", "png_src": ["vydanaagentu.png"], "filename": "circle_helmet"}, "school_freepass": {"alias": u"Пройдена без договорённостей", "png_src": ["climbing.png"], "filename": "circle_climbing"}, "other_tools": {"alias": u"[Ремонт]", "png_src": ["carrepair.png"], "filename": "square_tools"}, "other_house": {"alias": u"[Дом]", "png_src": ["home.png"], "filename": "square_house_black"}, "other_stop": {"alias": u"[Стоп]", "png_src": ["stop.png"], "filename": "square_stop"}, "other_stoplight": {"alias": u"[Светофор]", "png_src": ["stoplight.png"], "filename": "square_trafficlights"}, "other_unknown" : {"alias" : "[без знака]", "filename" : "circle_unknown_grey"}, "promo_red": {"alias": u"Промо (срочно)", "png_src": ["promogive.png"], "filename": "circle_pushpin_red"}, "promo_yellow": {"alias": u"Промо (обычный)", "png_src": ["promoter.png"], "filename": "circle_pushpin_yellow"}, "promo_green": {"alias": u"Промо (хороший)", "png_src": ["promotergood.png"], "filename": "circle_pushpin_green"} } """ # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('UniumPlugin', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/UniumPlugin/icon.png' self.add_action( icon_path, text=self.tr(u'Unium'), callback=self.run, parent=self.iface.mainWindow()) #-------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" #print "** CLOSING UniumPlugin" self.set_project_settings() # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD UniumPlugin" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&UniumPlugin'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar #-------------------------------------------------------------------------- def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING UniumPlugin" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = UniumPluginDockWidget() self.dockwidget.catbrwsButton.clicked.connect(self.select_cat_file) self.dockwidget.marksbrwsButton.clicked.connect(self.select_marks_file) self.dockwidget.dbbrwsButton.clicked.connect(self.select_db_file) self.dockwidget.loadSASButton.clicked.connect(self.loadSASButton_clicked) self.dockwidget.layersBox.currentIndexChanged.connect(self.selected_layer_changed) self.dockwidget.ffbrwsButton.clicked.connect(self.select_filefolder_clicked) self.dockwidget.wrblkBox.valueChanged.connect(self.wrblkBox_value_changed) self.dockwidget.savesetButton.clicked.connect(self.savesetButton_clicked) self.dockwidget.loadsetButton.clicked.connect(self.loadsetButton_clicked) self.dockwidget.applyFilterButton.clicked.connect(self.applyFilterButton_clicked) self.dockwidget.resetFilterButton.clicked.connect(self.resetFilterButton_clicked) self.dockwidget.brwsxlsoutButton.clicked.connect(self.select_out_excel_file) self.dockwidget.xlsoutButton.clicked.connect(self.export_to_xls) self.dockwidget.brwsxlsinButton.clicked.connect(self.select_in_excel_file) self.dockwidget.xlsinButton.clicked.connect(self.import_from_xls) self.dockwidget.showFiles.clicked.connect(self.show_files) self.dockwidget.addFiles.clicked.connect(self.add_files) #self.dockwidget.layersBox.connect(self.dockwidget.layersBox,SIGNAL("currentIndexChanged(int)"),self.dockwidget,SLOT("self.selected_layer_changed(int)")) self.dockwidget.layersBox.currentIndex = 1 # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) self.getSettings() self.updateSettingsUI() self.get_project_settings() self.update_layers_list() for lyr in self.iface.legendInterface().layers(): if isinstance(lyr, QgsVectorLayer): self.load_subsets(lyr) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dockwidget) self.dockwidget.show() #-------------------------------------------------------------------------- def getSettings(self): config_file = os.path.join(os.path.dirname(__file__),'mcqp_unium_config.json') msg = u"Конфигурационный файл отсутствует. Будет загружена конфигурация по-умолчанию" if os.path.exists(config_file): try: conf = open(config_file,'r') self.config = json.load(conf) conf.close() i_msg = u"Конфигурация загружена" self.iface.messageBar().pushMessage("Info", i_msg, level=QgsMessageBar.INFO, duration=7) QgsMessageLog.logMessage(i_msg, level=QgsMessageLog.INFO) return except Exception,err: msg = u"Ошибка при загрузке конфигурационного файла: %s. Будет загружена конфигурация по-умолчанию" % err self.config = self.default_config self.iface.messageBar().pushMessage("Warning", msg, level=QgsMessageBar.WARNING, duration=7) QgsMessageLog.logMessage(msg, level=QgsMessageLog.WARNING) return
class UniumPlugin: """QGIS Plugin Implementation.""" 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 locale = QSettings().value('locale/userLocale')[0:2] locale_path = os.path.join( self.plugin_dir, 'i18n', 'UniumPlugin_{}.qm'.format(locale)) if os.path.exists(locale_path): self.translator = QTranslator() self.translator.load(locale_path) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Declare instance attributes self.actions = [] self.menu = self.tr(u'&UniumPlugin') # TODO: We are going to let the user set this up in a future iteration self.toolbar = self.iface.pluginToolBar() #self.iface.addToolBar(u'UniumPlugin') self.toolbar.setObjectName(u'UniumPlugin') #print "** INITIALIZING UniumPlugin" self.pluginIsActive = False self.dockwidget = None # initialize dict for saving data about importing sml self.sml_data = {} # initialize layers data self.categories = {} self.layers = {} self.selected_id = u'' # default configuration default_config = """{"files_folder": "", "write_block": 50 } """ # noinspection PyMethodMayBeStatic def tr(self, message): """Get the translation for a string using Qt translation API. We implement this ourselves since we do not inherit QObject. :param message: String for translation. :type message: str, QString :returns: Translated version of message. :rtype: QString """ # noinspection PyTypeChecker,PyArgumentList,PyCallByClass return QCoreApplication.translate('UniumPlugin', message) def add_action( self, icon_path, text, callback, enabled_flag=True, add_to_menu=True, add_to_toolbar=True, status_tip=None, whats_this=None, parent=None): """Add a toolbar icon to the toolbar. :param icon_path: Path to the icon for this action. Can be a resource path (e.g. ':/plugins/foo/bar.png') or a normal file system path. :type icon_path: str :param text: Text that should be shown in menu items for this action. :type text: str :param callback: Function to be called when the action is triggered. :type callback: function :param enabled_flag: A flag indicating if the action should be enabled by default. Defaults to True. :type enabled_flag: bool :param add_to_menu: Flag indicating whether the action should also be added to the menu. Defaults to True. :type add_to_menu: bool :param add_to_toolbar: Flag indicating whether the action should also be added to the toolbar. Defaults to True. :type add_to_toolbar: bool :param status_tip: Optional text to show in a popup when mouse pointer hovers over the action. :type status_tip: str :param parent: Parent widget for the new action. Defaults None. :type parent: QWidget :param whats_this: Optional text to show in the status bar when the mouse pointer hovers over the action. :returns: The action that was created. Note that the action is also added to self.actions list. :rtype: QAction """ icon = QIcon(icon_path) action = QAction(icon, text, parent) action.triggered.connect(callback) action.setEnabled(enabled_flag) if status_tip is not None: action.setStatusTip(status_tip) if whats_this is not None: action.setWhatsThis(whats_this) if add_to_toolbar: self.toolbar.addAction(action) if add_to_menu: self.iface.addPluginToMenu( self.menu, action) self.actions.append(action) return action def initGui(self): """Create the menu entries and toolbar icons inside the QGIS GUI.""" icon_path = ':/plugins/UniumPlugin/icon.png' self.add_action( icon_path, text=self.tr(u'Unium'), callback=self.run, parent=self.iface.mainWindow()) #-------------------------------------------------------------------------- def onClosePlugin(self): """Cleanup necessary items here when plugin dockwidget is closed""" #print "** CLOSING UniumPlugin" # disconnects self.dockwidget.closingPlugin.disconnect(self.onClosePlugin) # remove this statement if dockwidget is to remain # for reuse if plugin is reopened # Commented next statement since it causes QGIS crashe # when closing the docked window: # self.dockwidget = None self.pluginIsActive = False def unload(self): """Removes the plugin menu item and icon from QGIS GUI.""" #print "** UNLOAD UniumPlugin" for action in self.actions: self.iface.removePluginMenu( self.tr(u'&UniumPlugin'), action) self.iface.removeToolBarIcon(action) # remove the toolbar del self.toolbar #-------------------------------------------------------------------------- def run(self): """Run method that loads and starts the plugin""" if not self.pluginIsActive: self.pluginIsActive = True #print "** STARTING UniumPlugin" # dockwidget may not exist if: # first run of plugin # removed on close (see self.onClosePlugin method) if self.dockwidget == None: # Create the dockwidget (after translation) and keep reference self.dockwidget = UniumPluginDockWidget() self.dockwidget.catbrwsButton.clicked.connect(self.select_cat_file) self.dockwidget.marksbrwsButton.clicked.connect(self.select_marks_file) self.dockwidget.dbbrwsButton.clicked.connect(self.select_db_file) self.dockwidget.loadSASButton.clicked.connect(self.loadSASButton_clicked) self.dockwidget.layersBox.currentIndexChanged.connect(self.selected_layer_changed) self.dockwidget.ffbrwsButton.clicked.connect(self.select_filefolder_clicked) self.dockwidget.wrblkBox.valueChanged.connect(self.wrblkBox_value_changed) self.dockwidget.savesetButton.clicked.connect(self.savesetButton_clicked) self.dockwidget.loadsetButton.clicked.connect(self.loadsetButton_clicked) self.dockwidget.applyFilterButton.clicked.connect(self.applyFilterButton_clicked) self.dockwidget.resetFilterButton.clicked.connect(self.resetFilterButton_clicked) #self.dockwidget.layersBox.connect(self.dockwidget.layersBox,SIGNAL("currentIndexChanged(int)"),self.dockwidget,SLOT("self.selected_layer_changed(int)")) self.dockwidget.layersBox.currentIndex = 1 # connect to provide cleanup on closing of dockwidget self.dockwidget.closingPlugin.connect(self.onClosePlugin) self.getSettings() self.updateSettingsUI() self.get_project_settings() self.update_layers_list() for lyr in self.iface.legendInterface().layers(): if isinstance(lyr, QgsVectorLayer): UniumPlugin.load_subsets(lyr) # show the dockwidget # TODO: fix to allow choice of dock location self.iface.addDockWidget(Qt.BottomDockWidgetArea, self.dockwidget) self.dockwidget.show() #-------------------------------------------------------------------------- def getSettings(self): config_file = os.path.join(os.path.dirname(__file__),'mcqp_unium_config.json') msg = u"Конфигурационный файл отсутствует. Будет загружена конфигурация по-умолчанию" if os.path.exists(config_file): try: conf = open(config_file,'r') self.config = json.load(conf) conf.close() i_msg = u"Конфигурация загружена" self.iface.messageBar().pushMessage("Info", i_msg, level=QgsMessageBar.INFO, duration=7) QgsMessageLog.logMessage(i_msg, level=QgsMessageLog.INFO) return except Exception,err: msg = u"Ошибка при загрузке конфигурационного файла: %s. Будет загружена конфигурация по-умолчанию" % err else: