예제 #1
0
    def __init__(self, iface, parent=None):

        super(PreVesperDialog, self).__init__(iface.mainWindow())

        # Set up the user interface from Designer.
        self.setupUi(self)

        # The qgis interface
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(
            PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool)
        self.DEBUG = config.get_debug_mode()

        # Catch and redirect python errors directed at the log messages python
        # error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        self.setWindowIcon(QtGui.QIcon(
            ':/plugins/pat/icons/icon_vesperKriging.svg'))

        self.validationLayout = QtGui.QFormLayout(self)
        # source: https://nathanw.net/2013/08/02/death-to-the-message-box-use-the-qgis-messagebar/
        # Add the error messages to top of form via a message bar.
        # leave this message bar for bailouts
        self.messageBar = QgsMessageBar(self)

        if isinstance(self.layout(), (QtGui.QFormLayout, QtGui.QGridLayout)):
            # create a validation layout so multiple messages can be added and
            # cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            # for use with Vertical/horizontal layout box
            self.layout().insertWidget(0, self.messageBar)

        # Set Class default variables -------------------------------------
        self.vesp_dict = None
        self.in_qgscrs = None
        self.dfCSV = None

        # this is a validation flag
        self.OverwriteCtrlFile = False
        self.cboMethod.addItems(
            ['High Density Kriging', 'Low Density Kriging (Advanced)'])

        # To allow only integers for the min number of pts.
        self.onlyInt = QIntValidator()
        self.lneMinPoint.setValidator(self.onlyInt)

        self.vesper_exe = check_vesper_dependency()
        if self.vesper_exe is None or self.vesper_exe == '':
            self.gbRunVesper.setTitle(
                'WARNING:Vesper not found please configure using the about dialog.')
            self.gbRunVesper.setChecked(False)
            self.gbRunVesper.setCheckable(False)
            self.gbRunVesper.setEnabled(False)
예제 #2
0
 def make_paging_query(self, url, json_export):
     """
     Runs an item query and returns the results
     :param url: The url to query
     :param json_export: True if exporting; False if rendering
     :return: A list of items if successful; None if not
     """
     response = None
     headers = self.get_headers().copy()
     headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON
     for i in range(0, NUM_TIMES_TO_TRY):
         try:
             request = urllib2.Request(url=url, headers=headers)
             response = self.get_opener().open(request, timeout=TIMEOUT_IN_SECONDS)
             self.is_login_successful = True
         except Exception, e:
             self.is_login_successful = False
             QgsMessageLog.instance().logMessage("Unable to run get on url: " + url + " due to: " + str(e)
                                                 + "; trying " + str(NUM_TIMES_TO_TRY - i - 1) + " times",
                                                 TAG_NAME, level=QgsMessageLog.CRITICAL)
         if response and self.is_login_successful:
             paging_id = self.process_paging_request(response.read())
             if paging_id:
                 return self.query_for_pages(paging_id, json_export)
             return None
예제 #3
0
    def __init__(self, iface, parent=None):

        super(RandomPixelSelectionDialog, self).__init__(parent)

        # Set up the user interface from Designer.
        self.setupUi(self)

        # The qgis interface
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool)

        # Catch and redirect python errors directed at the log messages python error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui --------------------------
        self.messageBar = QgsMessageBar(self)  # leave this message bar for bailouts
        self.validationLayout = QtGui.QFormLayout(self)  # new layout to gui

        if isinstance(self.layout(), QtGui.QFormLayout):
            # create a validation layout so multiple messages can be added and cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            self.layout().insertWidget(0, self.messageBar)  # for use with Vertical/horizontal layout box

        # GUI Customisation -----------------------------------------------
        self.setWindowIcon(QtGui.QIcon(':/plugins/pat/icons/icon_randomPixel.svg'))

        if read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastSize") > 0:
            self.dsbSize.setValue(read_setting(PLUGIN_NAME + "/" + self.toolKey + "/LastSize", int))
예제 #4
0
 def do_aoi_search(self, order_params, csv_element):
     """
     Performs an AOI search for strips in GBD and generates stats from them
     :param order_params: The order params for the GBD query
     :param csv_element: The entry in the CSV row to update
     :return:
     """
     data = {
         KEY_DATA_SEARCH_AREA_WKT: order_params.polygon,
         KEY_DATA_START_DATE: order_params.time_begin.isoformat() + "Z",
         KEY_DATA_END_DATE: order_params.time_end.isoformat() + "Z",
         KEY_DATA_FILTERS: VALUE_DATA_FILTERS,
         KEY_DATA_TAG_RESULTS: VALUE_DATA_TAG_RESULTS,
         KEY_DATA_TYPES: VALUE_DATA_TYPES,
     }
     json_data = json.dumps(data)
     headers = self.headers.copy()
     headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON
     try:
         request = urllib2.Request(GBD_SEARCH_AOI_AND_TIME_URL, json_data, headers)
         response = self.opener.open(request)
         response_data = response.read()
         result_data = json.loads(response_data, strict=False)
         self.update_csv_data(order_params.time_end, result_data, csv_element)
     except Exception, e:
         QgsMessageLog.instance().logMessage(
             "Exception detected during aoi search: " + str(e), TAG_NAME, level=QgsMessageLog.CRITICAL
         )
예제 #5
0
    def acquisition_search(self, order_params):
        """
        Performs a search for acquisitions.
        :param order_params: The order params for the GBD query
        :return:
        """
        self.log_in()

        # build request body json
        request_body = {
            KEY_DATA_SEARCH_AREA_WKT: order_params.polygon,
            KEY_DATA_FILTERS: order_params.filters,
            KEY_DATA_TAG_RESULTS: VALUE_DATA_TAG_RESULTS,
            KEY_DATA_TYPES: VALUE_DATA_TYPES
        }
        if order_params.time_begin:
            request_body[KEY_DATA_START_DATE] = order_params.time_begin
        if order_params.time_end:
            request_body[KEY_DATA_END_DATE] = order_params.time_end
        request_body_json = json.dumps(request_body)

        # build header
        headers = self.headers.copy()
        headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON

        try:
            request = urllib2.Request(ACQUISITION_SEARCH_URL, request_body_json, headers)
            response = self.opener.open(request)
            response_data = response.read()
            result_data = json.loads(response_data, strict=False)
            return result_data
        except Exception, e:
            QgsMessageLog.instance().logMessage("Exception during acquisition search: " + str(e), TAG_NAME, level=QgsMessageLog.CRITICAL)
예제 #6
0
    def log_in(self):
        """
        Log in to OAuth2 using the credentials provided to the constructor
        :return: None
        """
        # prep data
        data = {
            'username': self.username,
            'password': self.password,
            'grant_type': self.grant_type
        }
        encoded_data = urllib.urlencode(data)

        # build up request with cookie jar and basic auth handler
        cookie_jar = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))
        
        headers = self.headers
        headers[HEADER_AUTHORIZATION] = 'Basic ' + b64encode(self.client_id + ':' + self.client_secret)

        try:
            request = urllib2.Request(url=LOGIN_URL, data=encoded_data, headers=headers)
            response = self.opener.open(request)
            response_data = response.read()
            json_data = json.loads(response_data, strict=False)
            self.access_token = json_data[KEY_ACCESS_TOKEN].encode(JSON_ENCODING)
            self.token_type = json_data[KEY_TOKEN_TYPE].encode(JSON_ENCODING)
            self.update_headers_with_access_info()
            self.is_login_successful = True
        except Exception, e:
            QgsMessageLog.instance().logMessage("Exception detected during log in: " + str(e), TAG_NAME,
                                                level=QgsMessageLog.CRITICAL)
            self.is_login_successful = False
    def generate_layer_definition(self):
        try:
            service = QSettings().value("/IdahoLayerPlugin/service", "", type=str).strip('/')
            image_id = self.lineEdit_ImageId.text().strip()
            bucket_name = self.lineEdit_Bucket.text().strip()

            username, password, api_key, max_items_to_return = SettingsOps.get_settings()

            query = OAuth2Query.OAuth2Query(username, password, api_key)
            query.log_in()
            if not query.is_login_successful:
                QgsMessageLog.instance().logMessage("Login unsuccessful, verify your account settings.", TAG_NAME, level=QgsMessageLog.CRITICAL)
                raise Exception("Login unsuccessful, verify your account settings.")

            token = query.headers[OAuth2Query.HEADER_AUTHORIZATION].split(' ')[-1]

            props = self.getPropsFromID(service, bucket_name, image_id, token)

            _minlevel = props["levels"][0]
            _maxlevel = props["levels"][-1]
            bbox = BoundingBox(props["extents"][0], props["extents"][1], props["extents"][2], props["extents"][3])

            self.layerdef = IdahoLayerDefinition(service, image_id, bucket_name, _minlevel, _maxlevel, bbox, 3857)
            # set parameters
            self.layerdef.parameters.colorinterpretation = props["color_interp"]
            self.layerdef.parameters.format = props["mimetype"].split('/')[-1]
            self.layerdef.parameters.token = str(token)
            self.layerdef.update()
            self.accept()

        except Exception as e:
            self.plugin.iface.messageBar().pushMessage(self.tr("IdahoLayerPlugin"),
                                                       self.tr("{0}").format(unicode(e)),
                                                       QgsMessageBar.WARNING, 5)
예제 #8
0
 def do_aoi_search(self, order_params, csv_element):
     """
     Performs an AOI search for strips in GBD and generates stats from them
     :param order_params: The order params for the GBD query
     :param csv_element: The entry in the CSV row to update
     :return:
     """
     data = {
         KEY_DATA_SEARCH_AREA_WKT: order_params.polygon,
         KEY_DATA_START_DATE: order_params.time_begin.isoformat() + 'Z',
         KEY_DATA_END_DATE: order_params.time_end.isoformat() + 'Z',
         KEY_DATA_FILTERS: VALUE_DATA_FILTERS,
         KEY_DATA_TAG_RESULTS: VALUE_DATA_TAG_RESULTS,
         KEY_DATA_TYPES: VALUE_DATA_TYPES
     }
     json_data = json.dumps(data)
     headers = self.headers.copy()
     headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON
     try:
         request = urllib2.Request(GBD_SEARCH_AOI_AND_TIME_URL, json_data,
                                   headers)
         response = self.opener.open(request)
         response_data = response.read()
         result_data = json.loads(response_data, strict=False)
         self.update_csv_data(order_params.time_end, result_data,
                              csv_element)
     except Exception, e:
         QgsMessageLog.instance().logMessage(
             "Exception detected during aoi search: " + str(e),
             TAG_NAME,
             level=QgsMessageLog.CRITICAL)
    def __init__(self, iface, parent=None):

        super(GridExtractDialog, self).__init__(parent)

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS',
                                             bool)
        self.DEBUG = config.get_debug_mode()

        # Catch and redirect python errors directed at the log messages python error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        self.messageBar = QgsMessageBar(
            self)  # leave this message bar for bailouts
        self.validationLayout = QtGui.QFormLayout(self)  # new layout to gui

        if isinstance(self.layout(), QtGui.QFormLayout):
            # create a validation layout so multiple messages can be added and cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            self.layout().insertWidget(
                0,
                self.messageBar)  # for use with Vertical/horizontal layout box

        # GUI Runtime Customisation -----------------------------------------------
        self.setWindowIcon(
            QtGui.QIcon(':/plugins/pat/icons/icon_gridExtract.svg'))

        self.chkgrpStatistics.setExclusive(False)
        self.tabList.setColumnCount(2)
        self.tabList.setHorizontalHeaderItem(0, QTableWidgetItem("ID"))
        self.tabList.setHorizontalHeaderItem(1,
                                             QTableWidgetItem("0 Raster(s)"))
        self.tabList.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)
        self.tabList.hideColumn(0)  # don't need to display the unique layer ID
        self.pixel_size = 0
        self.lblPixelFilter.setText(
            'Only process rasters with one pixel size. Adding the first raster layer will set this pixel size'
        )
        self.statsMapping = {
            'mean': np.nanmean,
            'minimum': np.nanmin,
            'maximum': np.nanmax,
            'standard deviation': np.nanstd,
            'coefficient of variation': raster_ops.nancv,
            'pixel count': raster_ops.pixelcount,
        }
 def __init__(self,iface):
     self.iface = iface
     self.alg_name = ''
     self.parameters = OrderedDict()
     self.console_output = ''
     self.execution_commands = ''
     self.error_msg = ''
     self.error = False
     self.output_files = OrderedDict()
     self.log_file = ''
     QgsMessageLog.instance().messageReceived.connect(errorCatcher)
예제 #11
0
    def log_in(self, ignore_existing_tokens=False):
        """
        Log in to OAuth2 using the credentials provided to the constructor
        :return: None
        """
        if not self.opener:
            # build up request with cookie jar and basic auth handler
            cookie_jar = cookielib.LWPCookieJar()
            self.opener = urllib2.build_opener(
                urllib2.HTTPCookieProcessor(cookie_jar))

        if not OAuth2Query.headers or ignore_existing_tokens:
            with OAuth2Query.token_lock:
                if not OAuth2Query.headers or ignore_existing_tokens:
                    # prep data
                    data = {
                        'username': self.username,
                        'password': self.password,
                        'grant_type': self.grant_type
                    }
                    encoded_data = urllib.urlencode(data)

                    basic_header = self.basic_header
                    basic_header[
                        HEADER_AUTHORIZATION] = 'Basic ' + self.api_key

                    try:
                        request = urllib2.Request(url=LOGIN_URL,
                                                  data=encoded_data,
                                                  headers=basic_header)
                        response = self.opener.open(request)
                        response_data = response.read()
                        json_data = json.loads(response_data, strict=False)

                        access_token = json_data[KEY_ACCESS_TOKEN].encode(
                            JSON_ENCODING)
                        token_type = json_data[KEY_TOKEN_TYPE].encode(
                            JSON_ENCODING)

                        OAuth2Query.headers = {}
                        OAuth2Query.headers[HEADER_AUTHORIZATION] = "%s %s" % (
                            token_type, access_token)

                        self.is_login_successful = True

                    except Exception, e:
                        self.is_login_successful = False
                        QgsMessageLog.instance().logMessage(
                            "Exception detected during log in: " + str(e),
                            TAG_NAME,
                            level=QgsMessageLog.CRITICAL)
예제 #12
0
파일: db_tree.py 프로젝트: Ariki/QGIS
 def addLayer(self):
   table = self.currentTable()
   if table is not None:
     layer = table.toMapLayer()
     layers = QgsMapLayerRegistry.instance().addMapLayers([layer])
     if len(layers) != 1:
       QgsMessageLog.instance().logMessage( self.tr( "%1 is an invalid layer - not loaded" ).replace( "%1", layer.publicSource() ) )
       msgLabel = QLabel( self.tr( "%1 is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info." ).replace( "%1", layer.publicSource() ), self.mainWindow.infoBar )
       msgLabel.setWordWrap( True )
       self.connect( msgLabel, SIGNAL("linkActivated( QString )" ),
                     self.mainWindow.iface.mainWindow().findChild( QWidget, "MessageLog" ), SLOT( "show()" ) )
       self.connect( msgLabel, SIGNAL("linkActivated( QString )" ),
                     self.mainWindow.iface.mainWindow(), SLOT( "raise()" ) )
       self.mainWindow.infoBar.pushItem( QgsMessageBarItem( msgLabel, QgsMessageBar.WARNING ) )
예제 #13
0
    def enable_qgis_log(filename='C:\Temp\gqis_jupiter.log', haltApp = False, haltMsg = 'stop'):
        """ Very useful when QGIS crashes on PGSQL error
        :param filename: Filename and path for log file
        :param haltApp: Halts the application with a modal dialog
        :param haltMsg: Message to user when showing model stopping dialog
        :rtype: None
        """
        def write_log_message(message, tag, level):
            with open(filename, 'a') as logfile:
                logfile.write('{tag}({level}): {message}'.format(tag=tag, level=level, message=message))

        QgsMessageLog.instance().messageReceived.connect(write_log_message)

        if haltApp:
            QtGui.QMessageBox.information(None, JupiterAux.JUPITER, "{}".format(haltMsg.encode('cp1252')), QtGui.QMessageBox.Ok)
예제 #14
0
    def __init__(self, iface, parent=None):

        super(CalculateImageIndicesDialog, self).__init__(parent)

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS',
                                             bool)
        self.DEBUG = config.get_debug_mode()

        # Catch and redirect python errors directed at the log messages python error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        self.messageBar = QgsMessageBar(
            self)  # leave this message bar for bailouts
        self.validationLayout = QtGui.QFormLayout(self)  # new layout to gui

        if isinstance(self.layout(), (QtGui.QFormLayout, QtGui.QGridLayout)):
            # create a validation layout so multiple messages can be added and cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            self.layout().insertWidget(
                0,
                self.messageBar)  # for use with Vertical/horizontal layout box

        self.band_mapping = BandMapping()
        self.outQgsCRS = None

        self.chkgrpIndices.setExclusive(False)  # allow for multi selection
        self.exclude_map_layers()
        self.updateRaster()
        self.updateUseSelected()
        self.autoSetCoordinateSystem()

        # GUI Runtime Customisation -----------------------------------------------
        self.chkAddToDisplay.setChecked(False)
        # self.chkAddToDisplay.hide()

        self.add_blank_field_to_cbo()

        self.setWindowIcon(
            QtGui.QIcon(':/plugins/pat/icons/icon_calcImgIndices.svg'))
예제 #15
0
 def randomize(self, inLayer, outPath, minimum, design, value):
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     if design == self.tr("unstratified"):
         ext = inLayer.extent()
         if inLayer.type() == QgsMapLayer.RasterLayer:
             points = self.simpleRandom(int(value), ext, ext.xMinimum(),
                                        ext.xMaximum(), ext.yMinimum(),
                                        ext.yMaximum())
         else:
             points = self.vectorRandom(int(value), inLayer, ext.xMinimum(),
                                        ext.xMaximum(), ext.yMinimum(),
                                        ext.yMaximum())
     else:
         points, featErrors = self.loopThruPolygons(inLayer, value, design)
         if featErrors:
             if len(featErrors) >= 10:
                 err_msg = "Too many features couldn't be calculated due to conversion error. "
                 err_msg += "Please check out message log for more info."
                 msgLogInstance = QgsMessageLog.instance()
                 msgLogInstance.logMessage("WARNING - fTools: " +
                                           self.tr("Random Points"))
                 msgLogInstance.logMessage(
                     "The following feature ids should be checked.")
                 for feat in featErrors:
                     msgLogInstance.logMessage("Feature id: %d" % feat.id())
                 msgLogInstance.logMessage("End of features to be checked.")
             else:
                 features_ids = []
                 for feat in featErrors:
                     features_ids.append(unicode(feat.id()))
                 erroneous_ids = ', '.join(features_ids)
                 err_msg = "The following features IDs couldn't be calculated due to conversion error: %s" % erroneous_ids
             self.iface.messageBar().pushMessage("Errors", err_msg)
     if len(points):
         crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
         if not crs.isValid():
             crs = None
         fields = QgsFields()
         fields.append(QgsField("ID", QVariant.Int))
         outFeat.setFields(fields)
         check = QFile(self.shapefileName)
         if check.exists():
             if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                 return
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding,
                                      fields, QGis.WKBPoint, crs)
         idVar = 0
         count = 70.00
         add = (100.00 - 70.00) / len(points)
         for i in points:
             outFeat.setGeometry(i)
             outFeat.setAttribute(0, idVar)
             writer.addFeature(outFeat)
             idVar = idVar + 1
             count = count + add
             self.progressBar.setValue(count)
         del writer
         return True
     return False
예제 #16
0
    def run_wholeOfBlockAnalysis(self):
        """Run method for the fit to block grid dialog"""
        # https://gis.stackexchange.com/a/160146

        result = check_R_dependency()
        if result is not True:
            self.iface.messageBar().pushMessage("R configuration", result,
                                                level=QgsMessageBar.WARNING, duration=15)
            return

        proc_alg_mess = ProcessingAlgMessages(self.iface)
        QgsMessageLog.instance().messageReceived.connect(proc_alg_mess.processingCatcher)

        # Then get the algorithm you're interested in (for instance, Join Attributes):
        alg = Processing.getAlgorithm("r:wholeofblockanalysis")
        if alg is None:
            self.iface.messageBar().pushMessage("Whole-of-block analysis algorithm could not"
                                                " be found", level=QgsMessageBar.CRITICAL)
            return
        # Instantiate the commander window and open the algorithm's interface
        cw = CommanderWindow(self.iface.mainWindow(), self.iface.mapCanvas())
        if alg is not None:
            cw.runAlgorithm(alg)

        # if proc_alg_mess.alg_name == '' then cancel was clicked

        if proc_alg_mess.error:
            self.iface.messageBar().pushMessage("Whole-of-block analysis", proc_alg_mess.error_msg,
                                                level=QgsMessageBar.CRITICAL, duration=0)
        elif proc_alg_mess.alg_name != '':
            data_column = proc_alg_mess.parameters['Data_Column']

            # load rasters into qgis as grouped layers.
            for key, val in proc_alg_mess.output_files.items():

                grplyr = os.path.join('Whole-of-block {}'.format(data_column),  val['title'])

                for ea_file in val['files']:
                    removeFileFromQGIS(ea_file)
                    raster_layer = addRasterFileToQGIS(ea_file, group_layer_name=grplyr, atTop=False)
                    if key in ['p_val']:
                        raster_apply_unique_value_renderer(raster_layer)

            self.iface.messageBar().pushMessage("Whole-of-block analysis Completed Successfully!",
                                                level=QgsMessageBar.INFO, duration=15)

        del proc_alg_mess
예제 #17
0
 def addLayer(self):
     table = self.currentTable()
     if table is not None:
         layer = table.toMapLayer()
         layers = QgsMapLayerRegistry.instance().addMapLayers([layer])
         if len(layers) != 1:
             QgsMessageLog.instance().logMessage(
                 self.tr("%1 is an invalid layer - not loaded").replace("%1", layer.publicSource()))
             msgLabel = QLabel(self.tr(
                 "%1 is an invalid layer and cannot be loaded. Please check the <a href=\"#messageLog\">message log</a> for further info.").replace(
                 "%1", layer.publicSource()), self.mainWindow.infoBar)
             msgLabel.setWordWrap(True)
             self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
                          self.mainWindow.iface.mainWindow().findChild(QWidget, "MessageLog"), SLOT("show()"))
             self.connect(msgLabel, SIGNAL("linkActivated( QString )"),
                          self.mainWindow.iface.mainWindow(), SLOT("raise()"))
             self.mainWindow.infoBar.pushItem(QgsMessageBarItem(msgLabel, QgsMessageBar.WARNING))
예제 #18
0
    def query_for_pages(self, paging_id, json_export):
        """
        Runs paging queries until there is nothing left to find
        :param paging_id: The pagingId for the intial page
        :param json_export: True if exporting to JSON; False if rendering
        :return: A list of returned items if successful; None if not
        """
        response = None
        headers = self.get_headers().copy()
        total_data = {
            KEY_POINT: [],
            KEY_POLYGON: [],
            KEY_LINE: [],
            KEY_MULTIPOINT: [],
        }
        continue_querying = True
        while continue_querying:
            data = {'pagingId': paging_id}
            for i in range(0, NUM_TIMES_TO_TRY):
                try:
                    request = urllib2.Request(ITEMS_POST_PAGING_ID, urllib.urlencode(data), headers)
                    response = self.get_opener().open(request)
                    self.is_login_successful = True
                    response_body = response.read()

                    paging_id = self.process_paging_request(response_body)
                    new_data = self.process_paging_json_data(response_body, json_export)
                    total_data[KEY_LINE] += new_data[KEY_LINE]
                    total_data[KEY_POLYGON] += new_data[KEY_POLYGON]
                    total_data[KEY_POINT] += new_data[KEY_POINT]

                    continue_querying = len(new_data) >= ITEMS_TO_RETURN
                    break;

                except Exception, e:
                    self.is_login_successful = False
                    QgsMessageLog.instance().logMessage("Unable to post to url: " + ITEMS_POST_PAGING_ID +
                                                        " due to: " + str(e) + "; trying "
                                                        + str(NUM_TIMES_TO_TRY - i - 1) + " times", TAG_NAME,
                                                        level=QgsMessageLog.CRITICAL)
                    if (NUM_TIMES_TO_TRY - i - 1) <= 0:
                        raise e

            if not self.is_login_successful:
                continue_querying = False
예제 #19
0
 def randomize(self, inLayer, outPath, minimum, design, value):
     outFeat = QgsFeature()
     outFeat.initAttributes(1)
     if design == self.tr("unstratified"):
         ext = inLayer.extent()
         if inLayer.type() == QgsMapLayer.RasterLayer:
             points = self.simpleRandom(
                 int(value), ext, ext.xMinimum(),
                 ext.xMaximum(), ext.yMinimum(), ext.yMaximum())
         else:
             points = self.vectorRandom(
                 int(value), inLayer,
                 ext.xMinimum(), ext.xMaximum(), ext.yMinimum(), ext.yMaximum())
     else:
         points, featErrors = self.loopThruPolygons(inLayer, value, design)
         if featErrors:
             if len(featErrors) >= 10:
                 err_msg = "Too many features couldn't be calculated due to conversion error. "
                 err_msg += "Please check out message log for more info."
                 msgLogInstance = QgsMessageLog.instance()
                 msgLogInstance.logMessage("WARNING - fTools: " + self.tr("Random Points"))
                 msgLogInstance.logMessage("The following feature ids should be checked.")
                 for feat in featErrors:
                     msgLogInstance.logMessage("Feature id: %d" % feat.id())
                 msgLogInstance.logMessage("End of features to be checked.")
             else:
                 features_ids = []
                 for feat in featErrors:
                     features_ids.append(unicode(feat.id()))
                 erroneous_ids = ', '.join(features_ids)
                 err_msg = "The following features IDs couldn't be calculated due to conversion error: %s" % erroneous_ids
             self.iface.messageBar().pushMessage("Errors", err_msg)
     if len(points):
         crs = self.iface.mapCanvas().mapRenderer().destinationCrs()
         if not crs.isValid():
             crs = None
         fields = QgsFields()
         fields.append(QgsField("ID", QVariant.Int))
         outFeat.setFields(fields)
         check = QFile(self.shapefileName)
         if check.exists():
             if not QgsVectorFileWriter.deleteShapeFile(self.shapefileName):
                 return
         writer = QgsVectorFileWriter(self.shapefileName, self.encoding, fields, QGis.WKBPoint, crs)
         idVar = 0
         count = 70.00
         add = (100.00 - 70.00) / len(points)
         for i in points:
             outFeat.setGeometry(i)
             outFeat.setAttribute(0, idVar)
             writer.addFeature(outFeat)
             idVar = idVar + 1
             count = count + add
             self.progressBar.setValue(count)
         del writer
         return True
     return False
예제 #20
0
    def __init__(self, addLegendLayer):

        super(WorkerPopulateGroup, self).__init__()
        self.addLegendLayer = addLegendLayer

        self.sortedImages = SortedListByThread()
        self.killed = False
        self.canvas = qgis.utils.iface.mapCanvas()
        self.logMessage = QgsMessageLog.instance().logMessage
        self.nameFieldSource = self.layer = self.ltgCatalog = None
예제 #21
0
    def build_qgis_feature(self, vector_item):
        """
        Constructs a QGIS feature for rendering
        :param vector_item: The item returned
        :return a VectorFeature that can be rendered by QGIS
        """

        feature = VectorFeature()
        geometry = vector_item[KEY_JSON_GEOMETRY]
        coordinates = geometry[KEY_JSON_GEOMETRY_COORDINATES]
        geometry_type = geometry[KEY_JSON_GEOMETRY_TYPE]
        if geometry_type == u'Point':
            feature.setGeometry(QgsGeometry.fromPoint(self.get_point_from_json(coordinates)))
        elif geometry_type == u'LineString':
            feature.setGeometry(QgsGeometry.fromPolyline(self.get_linestring_from_json(coordinates)))
        elif geometry_type == u'MultiPoint':
            feature.setGeometry(QgsGeometry.fromMultiPoint(self.get_linestring_from_json(coordinates)))
        elif geometry_type == u'Polygon':
            feature.setGeometry(QgsGeometry.fromPolygon(self.get_polygon_from_json(coordinates)))
        elif geometry_type == u'MultiLineString':
            feature.setGeometry(QgsGeometry.fromMultiPolyline(self.get_polygon_from_json(coordinates)))
        elif geometry_type == u'MultiPolygon':
            feature.setGeometry(QgsGeometry.fromMultiPolygon(self.get_multipolygon_from_json(coordinates)))
        else:
            QgsMessageLog.instance().logMessage(u"Encountered odd geometry type: " + geometry_type, TAG_NAME,
                                                level=QgsMessageLog.CRITICAL)
        feature.geometry_type = geometry_type
        attributes = self.get_attributes_from_json(vector_item[KEY_JSON_PROPERTIES])
        fields = QgsFields()
        values = []
        for key, value in attributes.iteritems():
            type_value = None
            if key.endswith(u'int'):
                type_value = QVariant.Int
            elif key.endswith(u'dbl'):
                type_value = QVariant.Double
            else:
                type_value = QVariant.String
            fields.append(QgsField(key, type_value))
            values.append(value)
        feature.setFields(fields)
        feature.setAttributes(values)
        return feature
def CreateVritualDebLayer(self):
    # Vraag naar map met Deborah bestanden
    folder = str(
        QFileDialog.getExistingDirectory(
            None, "Selecteer Deborah Projectmap",
            "D:\\Google Drive\\Dev\\QGis Probeersels\\TZD78"))
    if not folder: return

    # Controleer of bestanden bestaan
    project = folder.split('\\')[-1]
    kop_path = os.path.join(folder, project + "_kop.dbf")
    laag_path = os.path.join(folder, project + "_laag.dbf")

    if not (os.path.isfile(kop_path) and os.path.isfile(laag_path)):
        iface.messageBar().pushMessage(
            "Fout",
            "Kan geen kop en/of laaggegevens vinden in de opgegeven map",
            level=QgsMessageBar.CRITICAL)
        return

    # Maak virtuele laag aan
    filecontent = getVRTText(self, project)
    filepath = os.path.join(folder, project + "_boringen.vrt")

    outputfile = open(filepath, "w")
    outputfile.write(filecontent)
    outputfile.close()

    # Voeg de virtuele laag toe aan de legenda
    layer = iface.addVectorLayer(filepath, project + "_boringen", "ogr")
    if not layer:
        QgsMessageLog.instance().logMessage('Kon virtuele laag niet laden!',
                                            level=QgsMessageLog.WARNING)

    # Voeg ook de laaggegevens toe aan de legenda voor evt. queries
    filepath = os.path.join(folder, project + "_laag.dbf")
    layer = iface.addVectorLayer(filepath, project + "_lagen", "ogr")
    if not layer:
        QgsMessageLog.instance().logMessage('Kon laaggegevens niet laden!',
                                            level=QgsMessageLog.WARNING)

    iface.mapCanvas().setExtent(layer.extent())
예제 #23
0
    def log_in(self, ignore_existing_tokens=False):
        """
        Log in to OAuth2 using the credentials provided to the constructor
        :return: None
        """
        if not self.opener:
            # build up request with cookie jar and basic auth handler
            cookie_jar = cookielib.LWPCookieJar()
            self.opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookie_jar))

        if not OAuth2Query.headers or ignore_existing_tokens:
            with OAuth2Query.token_lock:
                if not OAuth2Query.headers or ignore_existing_tokens:
                    # prep data
                    data = {
                        'username': self.username,
                        'password': self.password,
                        'grant_type': self.grant_type
                    }
                    encoded_data = urllib.urlencode(data)
                    
                    basic_header = self.basic_header
                    basic_header[HEADER_AUTHORIZATION] = 'Basic ' + self.api_key
            
                    try:
                        request = urllib2.Request(url=LOGIN_URL, data=encoded_data, headers=basic_header)
                        response = self.opener.open(request)
                        response_data = response.read()
                        json_data = json.loads(response_data, strict=False)
                        
                        access_token = json_data[KEY_ACCESS_TOKEN].encode(JSON_ENCODING)                    
                        token_type = json_data[KEY_TOKEN_TYPE].encode(JSON_ENCODING)
                        
                        OAuth2Query.headers = {}
                        OAuth2Query.headers[HEADER_AUTHORIZATION] = "%s %s" % (token_type, access_token)
                        
                        self.is_login_successful = True
                        
                    except Exception, e:
                        self.is_login_successful = False
                        QgsMessageLog.instance().logMessage("Exception detected during log in: " + str(e), TAG_NAME, level=QgsMessageLog.CRITICAL)
예제 #24
0
    def log_in(self):
        """
        Log in to OAuth2 using the credentials provided to the constructor
        :return: None
        """
        # prep data
        data = {
            'username': self.username,
            'password': self.password,
            'grant_type': self.grant_type
        }
        encoded_data = urllib.urlencode(data)

        # build up request with cookie jar and basic auth handler
        cookie_jar = cookielib.LWPCookieJar()
        self.opener = urllib2.build_opener(
            urllib2.HTTPCookieProcessor(cookie_jar))

        headers = self.headers
        headers[HEADER_AUTHORIZATION] = 'Basic ' + b64encode(
            self.client_id + ':' + self.client_secret)

        try:
            request = urllib2.Request(url=LOGIN_URL,
                                      data=encoded_data,
                                      headers=headers)
            response = self.opener.open(request)
            response_data = response.read()
            json_data = json.loads(response_data, strict=False)
            self.access_token = json_data[KEY_ACCESS_TOKEN].encode(
                JSON_ENCODING)
            self.token_type = json_data[KEY_TOKEN_TYPE].encode(JSON_ENCODING)
            self.update_headers_with_access_info()
            self.is_login_successful = True
        except Exception, e:
            QgsMessageLog.instance().logMessage(
                "Exception detected during log in: " + str(e),
                TAG_NAME,
                level=QgsMessageLog.CRITICAL)
            self.is_login_successful = False
예제 #25
0
    def __init__(self, iface, parent=None):

        super(PostVesperDialog, self).__init__(iface.mainWindow())

        # Set up the user interface from Designer.
        self.setupUi(self)

        # The qgis interface
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool)
        self.DEBUG = config.get_debug_mode()

        # Catch and redirect python errors directed at the log messages python error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        self.setWindowIcon(QtGui.QIcon(':/plugins/pat/icons/icon_importVesperKriging.svg'))

        self.validationLayout = QtGui.QFormLayout(self)

        # source: https://nathanw.net/2013/08/02/death-to-the-message-box-use-the-qgis-messagebar/
        # Add the error messages to top of form via a message bar.
        self.messageBar = QgsMessageBar(self)  # leave this message bar for bailouts

        if isinstance(self.layout(), (QtGui.QFormLayout, QtGui.QGridLayout)):
            # create a validation layout so multiple messages can be added and cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            self.layout().insertWidget(0, self.messageBar)  # for use with Vertical/horizontal layout box

        # Set Class default variables -------------------------------------
        self.vesper_qgscrs = None
        self.vesp_dict = None
        self.dfCSV = None
        self.chkRunVesper.hide()
    def __init__(self, iface, parent=None):

        super(KMeansClusterDialog, self).__init__(parent)

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS', bool)
        self.DEBUG = config.get_debug_mode()

        # Catch and redirect python errors directed at the log messages python error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        self.messageBar = QgsMessageBar(self)  # leave this message bar for bailouts
        self.validationLayout = QtGui.QFormLayout(self)  # new layout to gui

        if isinstance(self.layout(), QtGui.QFormLayout):
            # create a validation layout so multiple messages can be added and cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            self.layout().insertWidget(0, self.messageBar)  # for use with Vertical/horizontal layout box

        # GUI Runtime Customisation -----------------------------------------------
        self.setWindowIcon(QtGui.QIcon(':/plugins/pat/icons/icon_kMeansCluster.svg'))

        self.tabList.setColumnCount(2)
        self.tabList.setHorizontalHeaderItem(0, QTableWidgetItem("ID"))
        self.tabList.setHorizontalHeaderItem(1, QTableWidgetItem("0 Raster(s)"))

        self.tabList.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
        self.tabList.hideColumn(0)  # don't need to display the unique layer ID
        self.pixel_size = 0
        self.pixel_size_message = ''
        self.setMapLayers()
예제 #27
0
 def make_query(self, url):
     """
     Runs a source/geometry/type query and returns the results
     :param url: The url to query
     :return: A dictionary of name => count if successful; None if not
     """
     response = None
     headers = self.get_headers().copy()
     headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON
             
     for i in range(0, NUM_TIMES_TO_TRY):
         try:
             request = urllib2.Request(url=url, headers=headers)
             response = self.get_opener().open(request, timeout=TIMEOUT_IN_SECONDS)
             self.is_login_successful = True
         except Exception, e:
             self.is_login_successful = False
             QgsMessageLog.instance().logMessage("Unable to hit url: " + url + " due to: " + str(e) + "; trying " +
                                                 str(NUM_TIMES_TO_TRY - i - 1) + " more times.", TAG_NAME,
                                                 level=QgsMessageLog.CRITICAL)
         
         if response and self.is_login_successful:
             return self.process_json_data(response.read())
예제 #28
0
    def acquisition_search(self, order_params):
        """
        Performs a search for acquisitions.
        :param order_params: The order params for the GBD query
        :return:
        """
        self.log_in()

        # build request body json
        request_body = {
            KEY_DATA_SEARCH_AREA_WKT: order_params.polygon,
            KEY_DATA_FILTERS: order_params.filters,
            KEY_DATA_TAG_RESULTS: VALUE_DATA_TAG_RESULTS,
            KEY_DATA_TYPES: VALUE_DATA_TYPES
        }
        if order_params.time_begin:
            request_body[KEY_DATA_START_DATE] = order_params.time_begin
        if order_params.time_end:
            request_body[KEY_DATA_END_DATE] = order_params.time_end
        request_body_json = json.dumps(request_body)

        # build header
        headers = self.headers.copy()
        headers[HEADER_CONTENT_TYPE] = CONTENT_TYPE_JSON

        try:
            request = urllib2.Request(ACQUISITION_SEARCH_URL,
                                      request_body_json, headers)
            response = self.opener.open(request)
            response_data = response.read()
            result_data = json.loads(response_data, strict=False)
            return result_data
        except Exception, e:
            QgsMessageLog.instance().logMessage(
                "Exception during acquisition search: " + str(e),
                TAG_NAME,
                level=QgsMessageLog.CRITICAL)
예제 #29
0
class QgepQgsLogHandler(logging.Handler):
    """
    A class acting as a translator between pythons log system and the QGIS log
    system.
    """
    qgsMessageLog = QgsMessageLog.instance()

    def emit(self, record):
        '''
        Will be called by pythons logging and is the actual bridge
        @param record: The record to be logged
        '''

        # Should be adjusted to translate the levelno to QGIS debug levels once
        # QGIS agreed on standards.
        # See http://hub.qgis.org/issues/6965
        QgsMessageLog.logMessage(record.name + ':' + record.msg, 'qgep', record.levelno)
예제 #30
0
 def __enter__(self):
     QgsMessageLog.instance().messageReceived.connect(self.logMessage)
     return self
예제 #31
0
    def test_makeKeyTokens_(self):
        # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters

        invalidTokens = []
        validTokens = []

        # all test tokens will be generated by prepending or inserting characters to this token
        validBase = "valid"

        # some invalid characters, not allowed anywhere in a token
        # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_()
        invalidChars = "+*,;<>|!$%()=?#\x01"

        # generate the characters that are allowed at the start of a token (and at every other position)
        validStartChars = ":_"
        charRanges = [
            (ord('a'), ord('z')),
            (ord('A'), ord('Z')),
            (0x00F8, 0x02FF),
            (0x0370, 0x037D),
            (0x037F, 0x1FFF),
            (0x200C, 0x200D),
            (0x2070, 0x218F),
            (0x2C00, 0x2FEF),
            (0x3001, 0xD7FF),
            (0xF900, 0xFDCF),
            (0xFDF0, 0xFFFD),
            #(0x10000, 0xEFFFF),   while actually valid, these are not yet accepted by makeKeyTokens_()
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validStartChars += chr(c)

        # generate the characters that are only allowed inside a token, not at the start
        validInlineChars = "-.\xB7"
        charRanges = [
            (ord('0'), ord('9')),
            (0x0300, 0x036F),
            (0x203F, 0x2040),
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validInlineChars += chr(c)

        # test forbidden start characters
        for c in invalidChars + validInlineChars:
            invalidTokens.append(c + validBase)

        # test forbidden inline characters
        for c in invalidChars:
            invalidTokens.append(validBase[:4] + c + validBase[4:])

        # test each allowed start character
        for c in validStartChars:
            validTokens.append(c + validBase)

        # test each allowed inline character
        for c in validInlineChars:
            validTokens.append(validBase[:4] + c + validBase[4:])

        logger = QgsMessageLog.instance()
        logger.messageReceived.connect(self.catchMessage)
        prj = QgsProject.instance()

        for token in validTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "valid token '%s' not accepted" % (token)
            assert not self.messageCaught, myMessage

        for token in invalidTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "invalid token '%s' accepted" % (token)
            assert self.messageCaught, myMessage

        logger.messageReceived.disconnect(self.catchMessage)
예제 #32
0
    def layers_changed(self):
        layerstates = self.layers_with_states()
        for layer, visible in layerstates:
            layerid = layer.id()
            viewerloaded = self.viewer.layer_loaded(layerid)
            QgsMessageLog.instance().logMessage(layerid, "Earthmine")
            QgsMessageLog.instance().logMessage(
                "Viewer State:" + str(viewerloaded), "Earthmine")
            QgsMessageLog.instance().logMessage("QGIS State:" + str(visible),
                                                "Earthmine")
            if (viewerloaded and visible) or (not viewerloaded
                                              and not visible):
                QgsMessageLog.instance().logMessage("Ignoring as states match",
                                                    "Earthmine")
                continue

            if viewerloaded and not visible:
                QgsMessageLog.instance().logMessage(
                    "Clearing layer because viewer loaded and disabled in QGIS",
                    "Earthmine")
                self.viewer.clear_layer_features(layerid)
                continue

            if not viewerloaded and visible:
                QgsMessageLog.instance().logMessage("Loading layer",
                                                    "Earthmine")
                self.load_layer_features(layers=[layer])
                continue
예제 #33
0
# coding: utf-8
from qgis.core import QgsMessageLog

filename = '/tmp/qgis.log'


def writelogmessage(message, tag, level):
    with open(filename, 'a') as logfile:
        logfile.write('{}({}): {}'.format(tag, level, message))


QgsMessageLog.instance().messageReceived.connect(writelogmessage)

# Use QgsMessageLog to log all the information that you want to save about
# the execution of your code.
QgsMessageLog.logMessage("Your plugin code has been executed correctly",
                         'MyPlugin', QgsMessageLog.INFO)
QgsMessageLog.logMessage("Your plugin code might have some problems",
                         level=QgsMessageLog.WARNING)
QgsMessageLog.logMessage("Your plugin code has crashed!",
                         level=QgsMessageLog.CRITICAL)
예제 #34
0
    def test_makeKeyTokens_(self):
        # see http://www.w3.org/TR/REC-xml/#d0e804 for a list of valid characters

        invalidTokens = []
        validTokens = []

        # all test tokens will be generated by prepending or inserting characters to this token
        validBase = u"valid"

        # some invalid characters, not allowed anywhere in a token
        # note that '/' must not be added here because it is taken as a separator by makeKeyTokens_()
        invalidChars = u"+*,;<>|!$%()=?#\x01"

        # generate the characters that are allowed at the start of a token (and at every other position)
        validStartChars = u":_"
        charRanges = [
            (ord(u'a'), ord(u'z')),
            (ord(u'A'), ord(u'Z')),
            (0x00F8, 0x02FF),
            (0x0370, 0x037D),
            (0x037F, 0x1FFF),
            (0x200C, 0x200D),
            (0x2070, 0x218F),
            (0x2C00, 0x2FEF),
            (0x3001, 0xD7FF),
            (0xF900, 0xFDCF),
            (0xFDF0, 0xFFFD),
            #(0x10000, 0xEFFFF),   while actually valid, these are not yet accepted by makeKeyTokens_()
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validStartChars += unichr(c)

        # generate the characters that are only allowed inside a token, not at the start
        validInlineChars = u"-.\xB7"
        charRanges = [
            (ord(u'0'), ord(u'9')),
            (0x0300, 0x036F),
            (0x203F, 0x2040),
        ]
        for r in charRanges:
            for c in range(r[0], r[1]):
                validInlineChars += unichr(c)

        # test forbidden start characters
        for c in invalidChars + validInlineChars:
            invalidTokens.append(c + validBase)

        # test forbidden inline characters
        for c in invalidChars:
            invalidTokens.append(validBase[:4] + c + validBase[4:])

        # test each allowed start character
        for c in validStartChars:
            validTokens.append(c + validBase)

        # test each allowed inline character
        for c in validInlineChars:
            validTokens.append(validBase[:4] + c + validBase[4:])

        logger = QgsMessageLog.instance()
        logger.messageReceived.connect(self.catchMessage)
        prj = QgsProject.instance()

        for token in validTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "valid token '%s' not accepted" % (token)
            assert not self.messageCaught, myMessage

        for token in invalidTokens:
            self.messageCaught = False
            prj.readEntry("test", token)
            myMessage = "invalid token '%s' accepted" % (token)
            assert self.messageCaught, myMessage

        logger.messageReceived.disconnect(self.catchMessage)
예제 #35
0
파일: utils.py 프로젝트: giohappy/infotools
def log(msg):
    logger = QgsMessageLog.instance()
    logger.logMessage(msg,'InfoTools')
예제 #36
0
 def __exit__(self, type, value, traceback):
     QgsMessageLog.instance().messageReceived.disconnect(self.logMessage)
# coding: utf-8
from qgis.core import QgsMessageLog

filename = '/tmp/qgis.log'


def writelogmessage(message, tag, level):
    with open(filename, 'a') as logfile:
        logfile.write('{}({}): {}'.format(tag, level, message))

QgsMessageLog.instance().messageReceived.connect(writelogmessage)

# Use QgsMessageLog to log all the information that you want to save about
# the execution of your code.
QgsMessageLog.logMessage("Your plugin code has been executed correctly",
                         'MyPlugin', QgsMessageLog.INFO)
QgsMessageLog.logMessage("Your plugin code might have some problems",
                         level=QgsMessageLog.WARNING)
QgsMessageLog.logMessage("Your plugin code has crashed!",
                         level=QgsMessageLog.CRITICAL)
예제 #38
0
    def layers_changed(self):
        layerstates = self.layers_with_states()
        for layer, visible in layerstates:
            layerid = layer.id()
            viewerloaded = self.viewer.layer_loaded(layerid)
            QgsMessageLog.instance().logMessage(layerid, "Earthmine")
            QgsMessageLog.instance().logMessage("Viewer State:" + str(viewerloaded), "Earthmine")
            QgsMessageLog.instance().logMessage("QGIS State:" + str(visible), "Earthmine")
            if (viewerloaded and visible) or (not viewerloaded and not visible):
                QgsMessageLog.instance().logMessage("Ignoring as states match", "Earthmine")
                continue

            if viewerloaded and not visible:
                QgsMessageLog.instance().logMessage(
                    "Clearing layer because viewer loaded and disabled in QGIS", "Earthmine"
                )
                self.viewer.clear_layer_features(layerid)
                continue

            if not viewerloaded and visible:
                QgsMessageLog.instance().logMessage("Loading layer", "Earthmine")
                self.load_layer_features(layers=[layer])
                continue
예제 #39
0
    def __init__(self, iface, parent=None):

        super(PersistorDialog, self).__init__(parent)

        # Set up the user interface from Designer.
        self.setupUi(self)
        self.iface = iface
        self.DISP_TEMP_LAYERS = read_setting(PLUGIN_NAME + '/DISP_TEMP_LAYERS',
                                             bool)
        self.DEBUG = config.get_debug_mode()
        self.pixel_size = 0
        # Catch and redirect python errors directed at the log messages python
        # error tab.
        QgsMessageLog.instance().messageReceived.connect(errorCatcher)

        if not os.path.exists(TEMPDIR):
            os.mkdir(TEMPDIR)

        # Setup for validation messagebar on gui-----------------------------
        # leave this message bar for bailouts
        self.messageBar = QgsMessageBar(self)
        self.validationLayout = QtGui.QFormLayout(self)  # new layout to gui

        if isinstance(self.layout(), QtGui.QFormLayout):
            # create a validation layout so multiple messages can be added and
            # cleaned up.
            self.layout().insertRow(0, self.validationLayout)
            self.layout().insertRow(0, self.messageBar)
        else:
            # for use with Vertical/horizontal layout box
            self.layout().insertWidget(0, self.messageBar)

        # GUI Runtime Customisation -------------------------------------------
        self.setWindowIcon(
            QtGui.QIcon(':/plugins/pat/icons/icon_persistor.svg'))

        self.cboMethod.addItems(
            ['Target Probability', 'Target Over All Years'])
        self.cboMethod.setCurrentIndex(1)
        for ea_cbo in [
                self.cboAllYearTargetPerc, self.cboUpperPerc, self.cboLowerPerc
        ]:
            ea_cbo.addItems(['{}%'.format(ea) for ea in range(50, -55, -5)])

            ea_cbo.setCurrentIndex(
                ea_cbo.findText('10%', QtCore.Qt.MatchFixedString))

        self.cboLowerPerc.setCurrentIndex(
            self.cboLowerPerc.findText('-10%', QtCore.Qt.MatchFixedString))

        for ea_tab in [self.tabUpper, self.tabLower]:
            ea_tab.setColumnCount(2)
            ea_tab.hideColumn(0)  # don't need to display the unique layer ID
            ea_tab.setHorizontalHeaderItem(0, QTableWidgetItem("ID"))
            ea_tab.setHorizontalHeaderItem(1, QTableWidgetItem("0 Raster(s)"))
            ea_tab.horizontalHeader().setResizeMode(QtGui.QHeaderView.Stretch)
            ea_tab.hideColumn(0)  # don't need to display the unique layer ID

        self.lblPixelFilter.setText(
            'Only process rasters with one pixel size. '
            'Adding the first raster layer will set this pixel size')
예제 #40
0
파일: plugin.py 프로젝트: vpicavet/Roam
    def initGui(self):
        """
        Create all the icons and setup the tool bars.  Called by QGIS when
        loading. This is called before setupUI.
        """
        QApplication.setWindowIcon(QIcon(":/branding/logo"))
        self.mainwindow.findChildren(QMenuBar)[0].setVisible(False)
        self.mainwindow.setContextMenuPolicy(Qt.PreventContextMenu)
        self.mainwindow.setWindowTitle("IntraMaps Roam: Mobile Data Collection")
        
        # Disable QGIS logging window popups. We do our own logging
        QgsMessageLog.instance().messageReceived.disconnect()
        
        s = """
        QToolButton { 
            padding: 6px;
            color: #4f4f4f;
         }
        
        QToolButton:hover { 
            padding: 6px;
            background-color: rgb(211, 228, 255);
         }
         
        QToolBar {
         background: white;
        }
        
        QCheckBox::indicator {
             width: 40px;
             height: 40px;
         }
        
        QLabel {
            color: #4f4f4f;
        }
        
        QDialog { background-color: rgb(255, 255, 255); }
        
        QPushButton { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            color: #4f4f4f;
         }
        
        QPushButton:hover { 
            border: 1px solid #e1e1e1;
             padding: 6px;
            background-color: rgb(211, 228, 255);
         }
        
        QCheckBox {
            color: #4f4f4f;
        }
        
        QComboBox::drop-down {
            width: 30px;
        }
        
        QComboBox {
            border: 1px solid #d3d3d3;
        }

        QStackedWidget {
             background-color: rgb(255, 255, 255);
        }
        """
        self.mainwindow.setStyleSheet(s)
        
        mainwidget = self.mainwindow.centralWidget()
        mainwidget.setLayout(QGridLayout())
        mainwidget.layout().setContentsMargins(0,0,0,0)
        
        newlayout = QGridLayout()
        newlayout.setContentsMargins(0,0,0,0)
        newlayout.addWidget(self.iface.mapCanvas(), 0,0,2,1)
        newlayout.addWidget(self.iface.messageBar(), 0,0,1,1)
        
        wid = QWidget()
        wid.setLayout(newlayout)
        
        self.stack = QStackedWidget(self.mainwindow)
        self.messageBar = QgsMessageBar(wid)
        self.messageBar.setSizePolicy( QSizePolicy.Minimum, QSizePolicy.Fixed )
        self.errorreport = PopDownReport(self.messageBar)

        mainwidget.layout().addWidget(self.stack, 0,0,2,1)
        mainwidget.layout().addWidget(self.messageBar, 0,0,1,1)

        self.helppage = HelpPage()
        helppath = os.path.join(os.path.dirname(__file__) , 'help',"help.html")
        self.helppage.setHelpPage(helppath)
        
        self.settingswidget = SettingsWidget(self.stack)
        
        self.projectwidget = ProjectsWidget()   
        self.projectwidget.requestOpenProject.connect(self.loadProject)
        self.stack.addWidget(wid)
        self.stack.addWidget(self.projectwidget)
        self.stack.addWidget(self.helppage)
        self.stack.addWidget(self.settingswidget)
                
        sys.excepthook = self.excepthook

        def createSpacer(width=30):
            widget = QWidget()
            widget.setMinimumWidth(width)
            return widget

        self.createToolBars()
        self.createActions()

        spacewidget = createSpacer(60)
        gpsspacewidget = createSpacer()
        gpsspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)

        self.moveaction.toggled.connect(functools.partial(self.setMapTool, self.movetool))
        self.infoaction.toggled.connect(functools.partial(self.setMapTool, self.infotool))
        
        showediting = (functools.partial(self.editingtoolbar.showToolbar, 
                                         self.editingmodeaction,
                                         self.moveaction))
        self.editingmodeaction.toggled.connect(showediting)

        self.addatgpsaction.triggered.connect(self.addAtGPS)
        self.addatgpsaction.setEnabled(self.gpsAction.isConnected)
        self.gpsAction.gpsfixed.connect(self.addatgpsaction.setEnabled)

        self.editingtoolbar.addToActionGroup(self.moveaction)

        self.actionGroup.addAction(self.editingmodeaction)
        self.actionGroup.addAction(self.editattributesaction)
        self.actionGroup.addAction(self.infoaction)

        self.homeAction.triggered.connect(self.zoomToDefaultView)
        
        self.openProjectAction.triggered.connect(self.showOpenProjectDialog)
        self.openProjectAction.triggered.connect(functools.partial(self.stack.setCurrentIndex, 1))
        
        self.configAction.triggered.connect(functools.partial(self.stack.setCurrentIndex, 3))
        self.configAction.triggered.connect(self.settingswidget.populateControls)
        self.configAction.triggered.connect(self.settingswidget.readSettings)
        
        self.toggleRasterAction.triggered.connect(self.toggleRasterLayers)

        self.navtoolbar.insertAction(self.iface.actionZoomIn(), self.iface.actionTouch())
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.homeAction)
        self.navtoolbar.insertAction(self.iface.actionTouch(), self.iface.actionZoomFullExtent())
        self.navtoolbar.insertAction(self.homeAction, self.iface.actionZoomFullExtent())

        self.navtoolbar.addAction(self.toggleRasterAction)
        self.navtoolbar.insertWidget(self.iface.actionZoomFullExtent(), spacewidget)
        self.toolbar.addAction(self.infoaction)
        self.toolbar.addAction(self.editingmodeaction)
        self.toolbar.addAction(self.editattributesaction)
        self.toolbar.addAction(self.syncAction)
        self.toolbar.addAction(self.gpsAction)
        self.toolbar.insertWidget(self.syncAction, gpsspacewidget)
        self.toolbar.insertSeparator(self.gpsAction)

        self.extraaddtoolbar.addAction(self.addatgpsaction)

        self.editingtoolbar.addAction(self.moveaction)
        
        self.mapview = QAction(QIcon(":/icons/map"), "Map", self.menutoolbar)
        self.mapview.setCheckable(True)
        self.mapview.triggered.connect(functools.partial(self.stack.setCurrentIndex, 0))
        
        self.help = QAction(QIcon(":/icons/help"), "Help", self.menutoolbar)
        self.help.setCheckable(True)
        self.help.triggered.connect(functools.partial(self.stack.setCurrentIndex, 2))
        self.help.setVisible(False)
        
        self.projectlabel = QLabel("Project: <br> None")
        self.projectlabel.setAlignment(Qt.AlignCenter)
        self.projectlabel.setStyleSheet("""
            QLabel {
                    color: #8c8c8c;
                    font: 10px "Calibri" ;
                    }""")

        self.userlabel = QLabel("User: <br> {user}".format(user=getpass.getuser()))
        self.userlabel.setAlignment(Qt.AlignCenter)
        self.userlabel.setStyleSheet("""
            QLabel {
                    color: #8c8c8c;
                    font: 10px "Calibri" ;
                    }""")
        
        self.quit = QAction(QIcon(":/icons/quit"), "Quit", self.menutoolbar)
        self.quit.triggered.connect(self.iface.actionExit().trigger)

        self.menuGroup.addAction(self.mapview)
        self.menuGroup.addAction(self.openProjectAction)
        self.menuGroup.addAction(self.help)
        self.menuGroup.addAction(self.configAction)
        
        self.menutoolbar.addAction(self.mapview)
        self.menutoolbar.addAction(self.openProjectAction)
        self.menutoolbar.addAction(self.help)
        self.menutoolbar.addAction(self.configAction)
        self.menutoolbar.addAction(self.quit)
        
        quitspacewidget = createSpacer()
        quitspacewidget.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        
        labelaction = self.menutoolbar.insertWidget(self.configAction, self.userlabel)
        
        self.menutoolbar.insertWidget(labelaction, quitspacewidget)
        self.menutoolbar.insertWidget(labelaction, self.projectlabel)
        self.setupIcons()
        self.stack.currentChanged.connect(self.updateUIState)
예제 #41
0
from functools import partial

from PyQt4.QtCore import Qt, QObject, SIGNAL

from qgis.core import QgsMessageLog

from .ElevationReader import ElevationReader
from .ElevationScene import ElevationScene, PT1, PT2
from .PluginDialogs import EleViewDialogDisp


log = QgsMessageLog.instance()


def log_points(the_points):
    x, y = [p.x() for p in the_points], [p.y() for p in the_points]
    log.logMessage(
        "Elevations span over {} units horizontally, with a maximum "
        "elevation of {} and minimum of {}, comprised of {} distinct "
        "points".format(
            max(x) - min(x), max(y), min(y), len(the_points)
        ),
        level=QgsMessageLog.INFO
    )


class ElevationDisplay(object):
    """
    This class is responsible for drawing the "Elevation View" display, where 
    the user can see a line representing line-of-sight between the two points
    selected on the map, overlaid on a simulated side-view of the terrain (
예제 #42
0
 def __exit__(self, type, value, traceback):
     QgsMessageLog.instance().messageReceived.disconnect(self.logMessage)
예제 #43
0
from functools import partial

from PyQt4.QtCore import Qt, QObject, SIGNAL

from qgis.core import QgsMessageLog

from .ElevationReader import ElevationReader
from .ElevationScene import ElevationScene, PT1, PT2
from .PluginDialogs import EleViewDialogDisp

log = QgsMessageLog.instance()


def log_points(the_points):
    x, y = [p.x() for p in the_points], [p.y() for p in the_points]
    log.logMessage(
        "Elevations span over {} units horizontally, with a maximum "
        "elevation of {} and minimum of {}, comprised of {} distinct "
        "points".format(max(x) - min(x), max(y), min(y), len(the_points)),
        level=QgsMessageLog.INFO)


class ElevationDisplay(object):
    """
    This class is responsible for drawing the "Elevation View" display, where 
    the user can see a line representing line-of-sight between the two points
    selected on the map, overlaid on a simulated side-view of the terrain (
    based on interpolation over the elevation of each vector encountered along
    the path between the start & end point).
    """
    def __init__(self, pt1, pt2, elev_layer, elev_attr, layer_crs,
예제 #44
0
def log(msg):
    logger = QgsMessageLog.instance()
    logger.logMessage(msg, 'InfoTools')
예제 #45
0
 def __enter__(self):
     QgsMessageLog.instance().messageReceived.connect(self.logMessage)
     return self