예제 #1
0
    def edit(self, label):
        dialog = OptionsDialog(label)
        try:
            response = dialog.run()
            if response == gtk.RESPONSE_ACCEPT:
                return dialog.check_out()
            else:
                raise error.UserCancel

        finally:
            dialog.destroy()
예제 #2
0
 def editOptions(self):
     '''Show dialog for option editing'''
     diag = OptionsDialog(self)
     logger.info('Options dialog started')
     if diag.exec_() == QDialog.Accepted:
         self.options.update(diag.getOptions())
         logger.info('Options changed')
         self.websocketServer.updatePort(self.options['websocket-port'])
         self.websocketServer.updateWhitelist(
             self.options['websocket-whitelist'])
         if self.options['websocket-enabled']:
             self.startWebsocketServer()
         else:
             self.websocketServer.close()
예제 #3
0
    def cb_column_properties(self, action):
        # column_object = treeview_column
        rownr, colnr, column_object = self.popup_info
        table = self.dataset.get_data()

        column = table.get_column(colnr)
        dialog = OptionsDialog(column.copy())
        try:
            response = dialog.run()
            if response == gtk.RESPONSE_ACCEPT:
                new_column = dialog.check_out()
                changeset = column.create_changeset(new_column)

                ul = UndoList().describe("Update Columns")
                uwrap.set(column, **changeset)
                uwrap.emit_last(table, "update-columns", undolist=ul)
                self.project.journal.append(ul)
        finally:
            dialog.destroy()
예제 #4
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
        self.canvas = self.iface.mapCanvas()

        # 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',
                                   'Auto_Polygon_{}.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)

        #Configuration
        self.config = ConfigParser.RawConfigParser()

        # Create the dialog (after translation) and keep reference
        self.dlg = AutoPolygonDialog()

        self.dlg_options = OptionsDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'Automatic Polygon')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'AutoPolygon')
        self.toolbar.setObjectName(u'AutoPolygon')
예제 #5
0
def main():
    """Main del proyecto. Aquí se inicializan los objetos principales, comienza todo el código.
    """
    client_id = 2  #ID del cliente en Laravel Passport. Por defecto es 2, y no debería cambiarse.

    #Secreto del cliente. Debe ser generado por Laravel Passport en la API.
    client_secret = ""

    try:
        main_app = QtSingleApplication(client_secret, sys.argv)
        if main_app.isRunning():
            sys.exit(0)
        QCoreApplication.setApplicationName("CAPOUNET Sync")
        QCoreApplication.setOrganizationName("CAPOUNET")
        QCoreApplication.setOrganizationDomain("capounet.unet.edu.ve")

        Settings.load_settings(client_id, client_secret)
        main_app.setStyleSheet(qdarkstyle.load_stylesheet_pyqt5())
        main_app.setWindowIcon(Settings.app_icon)

        return_code = 1
        while return_code:
            return_code = 2
            if not Settings.is_init():
                Settings.delete_settings()
                return_code = AccessDialog.obtain_configuration()
                if return_code == 1:
                    return_code = OptionsDialog.open_dialog()

            if return_code >= 1:
                main_window = MainWindow()
                sync_thread = SyncThread(main_window)
                sync_thread.start()
                if return_code == 1:
                    main_window.show()
                return_code = main_app.exec_()
                sync_thread.stop_sync()
                main_window.close()
                sync_thread.join()
                if return_code:
                    Settings.delete_settings()
                    Settings.load_settings(client_id, client_secret)

        sys.exit(0)

    except NameError:
        print("Nombre del error:", sys.exc_info()[1])
    except SystemExit:
        print("Cerrando la ventana...")
예제 #6
0
    def on_row_activated(self, treeview, *udata):
        (model, pathlist) = self.cview.get_selection().get_selected_rows()
        if model is None:
            return
        column = model.get_value(model.get_iter(pathlist[0]), 0)

        dialog = OptionsDialog(column)
        try:
            response = dialog.run()
            if response == gtk.RESPONSE_ACCEPT:
                dialog.check_out()
        finally:
            dialog.destroy()
        self.cview.grab_focus()
    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
        self.canvas = self.iface.mapCanvas()
        
        # 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',
            'Auto_Polygon_{}.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)

        #Configuration 
        self.config = ConfigParser.RawConfigParser()
                
        # Create the dialog (after translation) and keep reference
        self.dlg = AutoPolygonDialog()
        
        self.dlg_options = OptionsDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'Automatic Polygon')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'AutoPolygon')
        self.toolbar.setObjectName(u'AutoPolygon')
    def plot_postscript(app, project, plot):

        #
        # request filename
        #
        filename = PostscriptTerminal.build_filename('ps', project, plot)
        
        chooser = gtk.FileChooserDialog(
            title="PostScript Export",
            action=gtk.FILE_CHOOSER_ACTION_SAVE,
            buttons=(gtk.STOCK_CANCEL,
                         gtk.RESPONSE_CANCEL,
                         gtk.STOCK_SAVE,
                         gtk.RESPONSE_OK))
        chooser.set_default_response(gtk.RESPONSE_OK)        
        chooser.set_select_multiple(False)
        chooser.set_current_folder(os.path.dirname(filename))
        chooser.set_current_name(os.path.basename(filename))

        filter = gtk.FileFilter()
        filter.set_name("All files")
        filter.add_pattern("*")
        chooser.add_filter(filter)
        
        filter = gtk.FileFilter()
        filter.set_name("Postscript (.ps; .eps)")
        filter.add_pattern("*.ps")
        filter.add_pattern("*.eps")
        chooser.add_filter(filter)
        chooser.set_filter(filter) # default filter                

        response = chooser.run()
        try:
            if response == gtk.RESPONSE_OK:
                filename = chooser.get_filename()                    
            else:
                raise error.UserCancel
        finally:
            chooser.destroy()               

        #
        # request export options
        #
        ##props = ['mode', 'enhanced', 'color', 'blacktext', 'solid',
        ##         'dashlength', 'linewidth', 'duplexing', 'rounded', 'fontname',
        ##         'fontsize', 'timestamp']          
        
        dialog = OptionsDialog(PostscriptTerminal(),
                               title="Options Postscript Export",
                               parent=app.window)
        #dialog.set_size_request(320,520)

        # determine requested postscript mode (ps or eps) from extension
        path, ext = os.path.splitext(filename)
        ext = ext.lower()
        if ext == '.eps':
            dialog.owner.mode = 'eps'
        elif ext == '.ps':
            dialog.owner.mode = 'landscape'
            
        try:
            result = dialog.run()
            if result == gtk.RESPONSE_ACCEPT:            
                dialog.check_out()
            else:
                return
            terminal = dialog.owner
        finally:
            dialog.destroy()


        #
        # now check if mode and filename extension match
        #

        def fix_filename(filename, mode):
            msg = "The postscript mode you selected (%s) does not match the given filename extension (%s).  Do you want to adjust the filename to match the mode? " % (mode, os.path.splitext(filename)[1])
            dialog = gtk.MessageDialog(type = gtk.MESSAGE_QUESTION, message_format = msg)
            dialog.add_button("Keep Filename", gtk.RESPONSE_NO)
            btn_default = dialog.add_button(gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL)
            dialog.add_button("Adjust Filename", gtk.RESPONSE_YES)

            btn_default.grab_focus()

            response = dialog.run()
            dialog.destroy()

            if response == gtk.RESPONSE_YES:
                # yes = yes, adjust filename
                if mode == '.eps':  new_ext = '.eps'
                else: new_ext = '.ps'
                path, ext = os.path.splitext(filename)
                return path + new_ext
            elif response == gtk.RESPONSE_NO:
                # no = no, keep filename
                return filename
            else:
                # everything else -> abort action
                raise error.UserCancel

        if (terminal.mode == 'eps' and ext != '.eps') or \
               (terminal.mode != 'eps' and ext != '.ps'):
            filename = fix_filename(filename, terminal.mode)
        
        #
        # construct backend for output
        #
        backend = BackendRegistry['gnuplot'](project=project,
                                             plot=plot,
                                             filename=filename,
                                             terminal=terminal)
        try:
            backend.draw()
        finally:
            backend.disconnect()
    def _cb_import_dataset(self, action):
        pj = self._check_project()
        
        # allow user to choose files for import
        chooser = gtk.FileChooserDialog(
            title="Import Dataset from file",
            action=gtk.FILE_CHOOSER_ACTION_OPEN,
            buttons=(gtk.STOCK_CANCEL,
                     gtk.RESPONSE_CANCEL,
                     gtk.STOCK_OPEN,
                     gtk.RESPONSE_OK))
        chooser.set_default_response(gtk.RESPONSE_OK)
        chooser.set_current_folder(const.internal_path(const.PATH_DATA))
        chooser.set_select_multiple(True)

        filter_keys = {} # used for reference later on
        
        # add 'All Files' filter
        blurb_all_files = "All Files"
        filter = gtk.FileFilter()
        filter.set_name(blurb_all_files)
        filter.add_pattern("*")
        chooser.add_filter(filter)
        chooser.set_filter(filter)
        filter_keys[blurb_all_files] = 'auto' # default if nothing else specified
        
        # create file filters
        for (key, importer) in ImporterRegistry.iteritems():
            extensions = ';'.join(map(lambda ext: '*.'+ext, importer.extensions))
            blurb = "%s (%s)" % (importer.blurb, extensions)

            filter = gtk.FileFilter()
            filter.set_name(blurb)
            for ext in importer.extensions:
                filter.add_pattern("*."+ext.lower())
                filter.add_pattern("*."+ext.upper())
            chooser.add_filter(filter)

            filter_keys[blurb] = key

        # add shortcut folder to example path, if such exists
        shortcut_folder = const.internal_path(const.PATH_EXAMPLE)
        if os.path.exists(shortcut_folder):
            chooser.add_shortcut_folder(shortcut_folder)

        #
        # prepare extra widget
        #
        
        # The custom widget `combobox` lets the user choose,
        # which Importer is to be used.
        
        # model: key, blurb
        model = gtk.ListStore(str, str)
        # add 'Same as Filter' as first choice, then add all importers
        model.append( (None, "Auto") )
        for key, importer in ImporterRegistry.iteritems():
            model.append( (key, importer.blurb) )

        combobox = gtk.ComboBox(model)
        cell = gtk.CellRendererText()
        combobox.pack_start(cell, True)
        combobox.add_attribute(cell, 'text', 1)
        combobox.set_active(0)
        combobox.show()

        label = gtk.Label("Importer")
        label.show()
            
        hbox = gtk.HBox()       
        hbox.pack_end(combobox,False)
        hbox.pack_end(label,False)
        hbox.show()        

        # The progress bar display which file is currently being imported.
        pbar = gtk.ProgressBar()
        
        vbox = gtk.VBox()
        vbox.pack_start(hbox,False)
        vbox.pack_start(pbar,False)
        vbox.show()
        
        chooser.set_extra_widget(vbox)


        #
        # run dialog
        #
        
        try:
            response = chooser.run()
            if response == gtk.RESPONSE_OK:
                filenames = chooser.get_filenames()
                if len(filenames) == 0:
                    return
                
                importer_key = model[combobox.get_active()][0]
                if importer_key is None: # auto
                    f = chooser.get_filter()
                    importer_key = filter_keys[f.get_name()]
                    if importer_key is 'auto':
                        matches = importer_from_filename(filenames[0])
                        if len(matches) > 0:
                            importer_key = matches[0]
                        else:
                            importer_key = 'ASCII'
            else:
                return

            # TODO
            #chooser.set_active(False)
            pbar.show()
            
            # request import options
            importer = ImporterRegistry[importer_key]()

            try:
                dialog = OptionsDialog(importer, parent=self.window)
            except NoOptionsError:
                pass
            else:
                # If there are any options, construct a
                # preview widget to help the user.
                view = gtk.TextView()
                buffer = view.get_buffer()
                view.set_editable(False)
                view.show()

                tag_main = buffer.create_tag(family="Courier")
                tag_linenr = buffer.create_tag(family="Courier", weight=pango.WEIGHT_HEAVY)

                # fill preview buffer with at most 100 lines
                preview_file = filenames[0]
                try:
                    fd = open(preview_file, 'r')
                except IOError:
                    raise RuntimeError("Could not open file %s for preview!" % preview_file)

                iter = buffer.get_start_iter()        
                try:
                    for j in range(100):
                        line = fd.readline()
                        if len(line) == 0:
                            break
                        buffer.insert_with_tags(iter, u"%3d\t" % j, tag_linenr)
                        try:
                            buffer.insert_with_tags(iter, unicode(line), tag_main)
                        except UnicodeDecodeError:
                            buffer.insert_with_tags(iter, u"<unreadable line>\n", tag_main)
                finally:
                    fd.close()

                preview_widget = uihelper.add_scrollbars(view)
                preview_widget.show()

                dialog.vbox.add(preview_widget)
                dialog.set_size_request(480,320)

                try:
                    result = dialog.run()
                    if result == gtk.RESPONSE_ACCEPT:
                        dialog.check_out
                    else:
                        return
                finally:
                    dialog.destroy()


            def set_text(queue):
                while True:
                    try:
                        text, fraction = queue.get()
                        if text == -1:
                            pbar.hide()
                        elif text is not None:
                            pbar.set_text(text)                                        
                        if fraction is not None:
                            pbar.set_fraction(fraction)
                    except QueueEmpty:
                        pass
                    yield None

            queue = Queue()
            thread_progress = GIdleThread(set_text(queue))
            thread_progress.start()

            thread_import = GIdleThread(self.import_datasets(pj, filenames, importer), queue)
            thread_import.start()
            thread_import.wait()

        finally:
            chooser.destroy()
예제 #10
0
class AutoPolygon:
    """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
        self.canvas = self.iface.mapCanvas()

        # 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',
                                   'Auto_Polygon_{}.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)

        #Configuration
        self.config = ConfigParser.RawConfigParser()

        # Create the dialog (after translation) and keep reference
        self.dlg = AutoPolygonDialog()

        self.dlg_options = OptionsDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'Automatic Polygon')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'AutoPolygon')
        self.toolbar.setObjectName(u'AutoPolygon')

    # 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('Auto_Polygon', 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."""

        # Add actions

        #Automatic creation of a polygon with a point
        icon_path = ':/plugins/AutoPolygon/icons/rectangle_point.png'
        self.rectdigitpoint = self.add_action(
            icon_path,
            text=self.tr(u'Automatic creation of a polygon with a point'),
            callback=self.rectcreate_point,
            add_to_menu=True,
            add_to_toolbar=False,
            parent=self.iface.mainWindow())

        #Automatic creation of a polygon with a line
        icon_path = ':/plugins/AutoPolygon/icons/rectangle_line.png'
        self.rectdigitline = self.add_action(
            icon_path,
            text=self.tr(u'Automatic creation of a polygon with a line'),
            callback=self.rectcreate_line,
            add_to_menu=True,
            add_to_toolbar=False,
            parent=self.iface.mainWindow())

        # Get the tool to digitize a rectangle
        self.rectdigittool = RectDigitTool(self.canvas)

        #Configuring the rectangle tool
        self.RectMaj()

        #Polygon creation tools
        self.rectdigittools = QToolButton(self.toolbar)
        self.rectdigittools.setPopupMode(QToolButton.MenuButtonPopup)

        self.rectdigittools.addActions(
            [self.rectdigitpoint, self.rectdigitline])
        self.rectdigittools.setDefaultAction(self.rectdigitpoint)
        self.toolbar.addWidget(self.rectdigittools)

        #Creating the option button
        icon_path = ':/plugins/AutoPolygon/icons/option.png'
        self.options_conf = self.add_action(icon_path,
                                            text=self.tr(u'Options'),
                                            callback=self.options,
                                            add_to_menu=True,
                                            add_to_toolbar=True,
                                            parent=self.iface.mainWindow())

        #Connect to the event change layer
        QObject.connect(self.iface,
                        SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                        self.toggle)

        # At the end of the feature creation, call the function createFeature
        QObject.connect(self.rectdigittool,
                        SIGNAL("rbFinished(PyQt_PyObject)"),
                        self.createFeature)

        # By default, put the enabled button to False
        self.rectdigitpoint.setEnabled(False)
        self.rectdigitline.setEnabled(False)

        #If a layer is already selected, you are asked to perform toggle if the user requests editing
        self.toggle()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(self.tr(u'&Automatic Polygon'), action)
            self.iface.removeToolBarIcon(action)

        #Disconnecting events
        QObject.disconnect(self.rectdigittool,
                           SIGNAL("rbFinished(PyQt_PyObject)"),
                           self.createFeature)
        QObject.disconnect(self.iface,
                           SIGNAL("currentLayerChanged(QgsMapLayer*)"),
                           self.toggle)

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass

    #Function changing a layer
    def toggle(self):
        mc = self.canvas
        layer = mc.currentLayer()
        #Decide whether the plugin button/menu is enabled or disabled
        if layer <> None:

            if layer.type() == QgsMapLayer.VectorLayer:
                #If the layer is editable and the geometry is a type polygon
                if (layer.isEditable() and layer.geometryType() == 2):

                    #It makes clickable button
                    self.rectdigitpoint.setEnabled(True)
                    self.rectdigitline.setEnabled(True)

                    #Connect to the event editing stopped
                    QObject.connect(layer, SIGNAL("editingStopped()"),
                                    self.toggle)

                    #Disconnect to the event editing started
                    QObject.disconnect(layer, SIGNAL("editingStarted()"),
                                       self.toggle)

                else:
                    #It makes unclickable button
                    self.rectdigitpoint.setEnabled(False)
                    self.rectdigitline.setEnabled(False)

                    if layer.geometryType() == 2:
                        #Connect to the event editing started
                        QObject.connect(layer, SIGNAL("editingStarted()"),
                                        self.toggle)
                    else:
                        #Disconnect to the event editing started
                        QObject.disconnect(layer, SIGNAL("editingStarted()"),
                                           self.toggle)

                    #Disconnect to the event editing stopped
                    QObject.disconnect(layer, SIGNAL("editingStopped()"),
                                       self.toggle)
            else:
                #Disconnect to the event editing started
                QObject.disconnect(layer, SIGNAL("editingStarted()"),
                                   self.toggle)

    def rectcreate_point(self):
        self.canvas.setMapTool(self.rectdigittool)
        self.rectdigittools.setDefaultAction(self.rectdigitpoint)

        result = self.rectdigittool.SetPositionTypeSaisie("Point")

        if result is not None:
            self.iface.messageBar().pushMessage(self.tr(u'Warning'),
                                                self.tr(result),
                                                level=QgsMessageBar.WARNING,
                                                duration=3)

    def rectcreate_line(self):
        self.canvas.setMapTool(self.rectdigittool)
        self.rectdigittools.setDefaultAction(self.rectdigitline)

        result = self.rectdigittool.SetPositionTypeSaisie("Line")

        if result is not None:
            self.iface.messageBar().pushMessage(self.tr(u'Warning'),
                                                self.tr(result),
                                                level=QgsMessageBar.WARNING,
                                                duration=3)

    #Function when create feature
    def createFeature(self, geom):
        settings = QSettings()
        mc = self.canvas

        #Get the current layer
        layer = mc.currentLayer()
        if layer <> None:
            renderer = mc.mapRenderer()

            #Get the layer SRID
            layerCRSSrsid = layer.crs().srsid()
            projectCRSSrsid = renderer.destinationCrs().srsid()

            provider = layer.dataProvider()
            f = QgsFeature()

            #On the Fly reprojection.
            if layerCRSSrsid != projectCRSSrsid:
                geom.transform(
                    QgsCoordinateTransform(projectCRSSrsid, layerCRSSrsid))

            f.setGeometry(geom)

            # add attribute fields to feature
            fields = layer.pendingFields()

            # vector api change update
            f.initAttributes(fields.count())
            for i in range(fields.count()):
                f.setAttribute(i, provider.defaultValue(i))

            layer.beginEditCommand("Create a feature")
            layer.addFeature(f)
            layer.endEditCommand()

        else:
            QObject.disconnect(self.rectdigittool,
                               SIGNAL("rbFinished(PyQt_PyObject)"),
                               self.createFeature)

    # Showing the option dialog box
    def options(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg_options.show()
        # Run the dialog event loop
        result = self.dlg_options.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.

            #Configuring the rectangle tool
            self.RectMaj()

            pass

    def RectMaj(self):
        #Configuring the rectangle tool
        try:
            self.config.read(self.plugin_dir + '/AutoPolygon.cfg')
        except:
            return
        try:
            width = self.config.getfloat('RECTANGLE', 'width')
            height = self.config.getfloat('RECTANGLE', 'height')
            position = self.config.get('RECTANGLE', 'position')
        except:
            #If there were errors, the default values are put
            width = 2
            height = 1
            position = self.tr(u'Bottom Left').encode('utf-8').strip()

        self.rectdigittool.SetWidth(width)
        self.rectdigittool.SetHeight(height)
        result = self.rectdigittool.SetPositionPoint(position)

        #If the position doesn't existSi la position n'existe pas
        if result is not None:
            self.iface.messageBar().pushMessage(self.tr(u'Warning'),
                                                self.tr(result),
                                                level=QgsMessageBar.WARNING,
                                                duration=3)
예제 #11
0
class AutoPolygon:
    """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
        self.canvas = self.iface.mapCanvas()
        
        # 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',
            'Auto_Polygon_{}.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)

        #Configuration 
        self.config = ConfigParser.RawConfigParser()
                
        # Create the dialog (after translation) and keep reference
        self.dlg = AutoPolygonDialog()
        
        self.dlg_options = OptionsDialog()

        # Declare instance attributes
        self.actions = []
        self.menu = self.tr(u'Automatic Polygon')
        # TODO: We are going to let the user set this up in a future iteration
        self.toolbar = self.iface.addToolBar(u'AutoPolygon')
        self.toolbar.setObjectName(u'AutoPolygon')

    # 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('Auto_Polygon', 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."""

        # Add actions
        
        #Automatic creation of a polygon with a point
        icon_path = ':/plugins/AutoPolygon/icons/rectangle_point.png'
        self.rectdigitpoint = self.add_action(
            icon_path,
            text=self.tr(u'Automatic creation of a polygon with a point'),
            callback=self.rectcreate_point,
             add_to_menu=True,
             add_to_toolbar=False,
            parent=self.iface.mainWindow())
            
        #Automatic creation of a polygon with a line
        icon_path = ':/plugins/AutoPolygon/icons/rectangle_line.png'
        self.rectdigitline = self.add_action(
            icon_path,
            text=self.tr(u'Automatic creation of a polygon with a line'),
            callback=self.rectcreate_line,
             add_to_menu=True,
             add_to_toolbar=False,
            parent=self.iface.mainWindow())
                
        # Get the tool to digitize a rectangle
        self.rectdigittool = RectDigitTool( self.canvas )
                
        #Configuring the rectangle tool
        self.RectMaj()
        
        #Polygon creation tools
        self.rectdigittools = QToolButton(self.toolbar)
        self.rectdigittools.setPopupMode(QToolButton.MenuButtonPopup)
        
        self.rectdigittools.addActions( [ self.rectdigitpoint, self.rectdigitline ] )
        self.rectdigittools.setDefaultAction(self.rectdigitpoint)        
        self.toolbar.addWidget(self.rectdigittools)  

        #Creating the option button
        icon_path = ':/plugins/AutoPolygon/icons/option.png'
        self.options_conf = self.add_action(
            icon_path,
            text=self.tr(u'Options'),
            callback=self.options,
             add_to_menu=True,
             add_to_toolbar=True,
            parent=self.iface.mainWindow())        
                           
        #Connect to the event change layer
        QObject.connect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.toggle)
        
        # At the end of the feature creation, call the function createFeature
        QObject.connect(self.rectdigittool, SIGNAL("rbFinished(PyQt_PyObject)"), self.createFeature)
        
        # By default, put the enabled button to False
        self.rectdigitpoint.setEnabled(False)
        self.rectdigitline.setEnabled(False)
        
        #If a layer is already selected, you are asked to perform toggle if the user requests editing
        self.toggle()

    def unload(self):
        """Removes the plugin menu item and icon from QGIS GUI."""
        for action in self.actions:
            self.iface.removePluginMenu(
                self.tr(u'&Automatic Polygon'),
                action)
            self.iface.removeToolBarIcon(action)
        
        #Disconnecting events
        QObject.disconnect(self.rectdigittool, SIGNAL("rbFinished(PyQt_PyObject)"), self.createFeature)
        QObject.disconnect(self.iface, SIGNAL("currentLayerChanged(QgsMapLayer*)"), self.toggle)
    

    def run(self):
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg.show()
        # Run the dialog event loop
        result = self.dlg.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            pass
         
    #Function changing a layer
    def toggle(self):
        mc = self.canvas
        layer = mc.currentLayer()
        #Decide whether the plugin button/menu is enabled or disabled
        if layer <> None:
            
            if layer.type() == QgsMapLayer.VectorLayer:
                #If the layer is editable and the geometry is a type polygon
                if (layer.isEditable() and layer.geometryType() == 2):
                                                                       
                    #It makes clickable button
                    self.rectdigitpoint.setEnabled(True)
                    self.rectdigitline.setEnabled(True)

                    #Connect to the event editing stopped
                    QObject.connect(layer,SIGNAL("editingStopped()"),self.toggle)

                    #Disconnect to the event editing started
                    QObject.disconnect(layer,SIGNAL("editingStarted()"),self.toggle) 
                
                else:                                
                    #It makes unclickable button
                    self.rectdigitpoint.setEnabled(False)
                    self.rectdigitline.setEnabled(False)
                    
                    if layer.geometryType() == 2:
                        #Connect to the event editing started
                        QObject.connect(layer,SIGNAL("editingStarted()"),self.toggle)
                    else:
                        #Disconnect to the event editing started
                        QObject.disconnect(layer,SIGNAL("editingStarted()"),self.toggle) 
                    
                    #Disconnect to the event editing stopped
                    QObject.disconnect(layer,SIGNAL("editingStopped()"),self.toggle)
            else:
                #Disconnect to the event editing started
                QObject.disconnect(layer,SIGNAL("editingStarted()"),self.toggle) 
                
                
    def rectcreate_point(self):
        self.canvas.setMapTool(self.rectdigittool)
        self.rectdigittools.setDefaultAction(self.rectdigitpoint)    
        
        result = self.rectdigittool.SetPositionTypeSaisie("Point")
        
        if result is not None :
            self.iface.messageBar().pushMessage(
                        self.tr(u'Warning'),
                        self.tr(result),
                        level=QgsMessageBar.WARNING,
                        duration=3
                    )
                
    def rectcreate_line(self):
        self.canvas.setMapTool(self.rectdigittool)
        self.rectdigittools.setDefaultAction(self.rectdigitline)
        
        result = self.rectdigittool.SetPositionTypeSaisie("Line")
        
        if result is not None :
            self.iface.messageBar().pushMessage(
                        self.tr(u'Warning'),
                        self.tr(result),
                        level=QgsMessageBar.WARNING,
                        duration=3
                    )        

    #Function when create feature
    def createFeature(self, geom):
        settings = QSettings()
        mc = self.canvas
        
        #Get the current layer
        layer = mc.currentLayer()
        if layer <> None:
            renderer = mc.mapRenderer()
            
            #Get the layer SRID
            layerCRSSrsid = layer.crs().srsid()
            projectCRSSrsid = renderer.destinationCrs().srsid()
            
            provider = layer.dataProvider()   
            f = QgsFeature()
                        
            #On the Fly reprojection.
            if layerCRSSrsid != projectCRSSrsid:
                geom.transform(QgsCoordinateTransform(projectCRSSrsid, layerCRSSrsid))
                                        
            f.setGeometry(geom)
            
            # add attribute fields to feature
            fields = layer.pendingFields()

            # vector api change update
            f.initAttributes(fields.count())
            for i in range(fields.count()):
                f.setAttribute(i,provider.defaultValue(i))

            layer.beginEditCommand("Create a feature")       
            layer.addFeature(f)
            layer.endEditCommand()
            
        else:
            QObject.disconnect(self.rectdigittool, SIGNAL("rbFinished(PyQt_PyObject)"), self.createFeature)
         
    # Showing the option dialog box         
    def options(self):
    
        """Run method that performs all the real work"""
        # show the dialog
        self.dlg_options.show()
        # Run the dialog event loop
        result = self.dlg_options.exec_()
        # See if OK was pressed
        if result:
            # Do something useful here - delete the line containing pass and
            # substitute with your code.
            
            #Configuring the rectangle tool
            self.RectMaj()
            
            pass
     
    def RectMaj(self):
        #Configuring the rectangle tool
        try: self.config.read( self.plugin_dir+'/AutoPolygon.cfg' )
        except: return
        try: 
            width=self.config.getfloat('RECTANGLE','width')
            height=self.config.getfloat('RECTANGLE','height')
            position=self.config.get('RECTANGLE','position')
        except: 
            #If there were errors, the default values are put
            width=2
            height=1
            position= self.tr(u'Bottom Left').encode('utf-8').strip()
            
        self.rectdigittool.SetWidth (width)
        self.rectdigittool.SetHeight (height)
        result = self.rectdigittool.SetPositionPoint(position)
        
        #If the position doesn't existSi la position n'existe pas
        if result is not None :
            self.iface.messageBar().pushMessage(
                        self.tr(u'Warning'),
                        self.tr(result),
                        level=QgsMessageBar.WARNING,
                        duration=3
                    )
예제 #12
0
 def open_options(self):
     """Abre el Dialog de opciones.
     """
     self.show()
     OptionsDialog.open_dialog(self)