def deletefile(layer):
     try:
         os.remove(filename)
     except:
         open(filename, "w").close()
         assert os.path.getsize(filename) == 0, "removal and truncation of {} failed".format(filename)
     # print "Deleted file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
 def deletefile(layer):
     try:
         os.remove(filename)
     except:
         open(filename, "w").close()
         assert os.path.getsize(filename) == 0, "removal and truncation of {} failed".format(filename)
     # print "Deleted file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
Esempio n. 3
0
    def write(self, m):

        # This manage the case when console is called from another thread
        if QThread.currentThread() != QCoreApplication.instance().thread():
            QMetaObject.invokeMethod(self, "write", Qt.QueuedConnection,
                                     Q_ARG(str, m))
            return

        if self.style == "_traceback":
            # Show errors in red
            stderrColor = QColor(
                self.sO.settings.value("pythonConsole/stderrFontColor",
                                       QColor(self.ERROR_COLOR)))
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01,
                                  stderrColor)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True)
            pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)
            self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31)
            self.sO.append(m)
            self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01)
        else:
            self.sO.append(m)

        if self.out:
            self.out.write(m)

        self.move_cursor_to_end()

        if self.style != "_traceback":
            self.sO.repaint()

        if self.fire_keyboard_interrupt:
            self.fire_keyboard_interrupt = False
            raise KeyboardInterrupt
Esempio n. 4
0
    def write(self, m):

        # This manage the case when console is called from another thread
        if QThread.currentThread() != QCoreApplication.instance().thread():
            QMetaObject.invokeMethod(self, "write", Qt.QueuedConnection, Q_ARG(str, m))
            return

        if self.style == "_traceback":
            # Show errors in red
            stderrColor = QColor(self.sO.settings.value("pythonConsole/stderrFontColor", QColor(self.ERROR_COLOR)))
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETFORE, 0o01, stderrColor)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETITALIC, 0o01, True)
            self.sO.SendScintilla(QsciScintilla.SCI_STYLESETBOLD, 0o01, True)
            pos = self.sO.SendScintilla(QsciScintilla.SCI_GETCURRENTPOS)
            self.sO.SendScintilla(QsciScintilla.SCI_STARTSTYLING, pos, 31)
            self.sO.append(m)
            self.sO.SendScintilla(QsciScintilla.SCI_SETSTYLING, len(m), 0o01)
        else:
            self.sO.append(m)

        if self.out:
            self.out.write(m)

        self.move_cursor_to_end()

        if self.style != "_traceback":
            self.sO.repaint()

        if self.fire_keyboard_interrupt:
            self.fire_keyboard_interrupt = False
            raise KeyboardInterrupt
Esempio n. 5
0
def pre_init_plugin(iface):
    app = QCoreApplication.instance()
    parent = iface.mainWindow()
    dialog = None
    log = ''
    try:
        for msg_type, msg_val in load_install_extra_deps():
            app.processEvents()
            if msg_type == 'log':
                log += msg_val
            elif msg_type == 'needs_install':
                dialog = WaitDialog(
                    parent, 'Stack Composed - installing dependencies')
            elif msg_type == 'install_done':
                dialog.accept()
    except Exception as e:
        if dialog:
            dialog.accept()
        QMessageBox.critical(
            parent, 'Stack Composed - installing dependencies',
            'An error occurred during the installation of Python packages. ' +
            'Click on "Stack Trace" in the QGIS message bar for details.')
        raise RuntimeError(
            '\nStack Composed: Error installing Python packages. Read install instruction: '
            'https://github.com/SMByC/StackComposed-Qgis-processing\nLog:\n' +
            log) from e
Esempio n. 6
0
def setup_i18n(the_preferred_locale=None):
    """
    Setup internationalisation for the plugin.

    See if QGIS wants to override the system locale
    and then see if we can get a valid translation file
    for whatever locale is effectively being used.

    @param the_preferred_locale will override any other locale setting
    """

    logger = logging.getLogger(__name__)

    my_override_flag = QSettings().value('locale/overrideFlag',
                                         False,
                                         type=bool)

    my_locale_name = None
    if the_preferred_locale is not None:
        my_locale_name = the_preferred_locale
        logger.info('Using preferred locale: ' + my_locale_name)
    elif my_override_flag:
        my_locale_name = QSettings().value('locale/userLocale', '')
        logger.info('Using QGIS override locale: ' + my_locale_name)
    else:
        my_locale_name = QLocale.system().name()
        # NOTES: we split the locale name because we need the first two
        # character i.e. 'id', 'af, etc
        my_locale_name = str(my_locale_name)
        logger.info('Using system default locale: ' + my_locale_name)

    # Insert into QT's translation system
    # As soon as translator gets deleted, the translation will stop
    # Therefore, QCoreApplication is set as parent to not delete it
    # while the application is running (but we might end up loading
    # the same translation twice)
    translator = QTranslator(QCoreApplication.instance())

    my_translator_file = 'qgepplugin_' + my_locale_name

    my_result = translator.load(my_translator_file, 'i18n')

    if my_result:
        QCoreApplication.instance().installTranslator(translator)
Esempio n. 7
0
    def __init__(self, iface):
        self.iface = iface
        self.plugin_dir = os.path.dirname(__file__)

        self.windowTitle = "3Di Modeller Interface - Powered by QGIS"

        self.app = QApplication.instance()
        self.QApp = QCoreApplication.instance()

        if self.QApp is None:
            self.QApp = QApplication(sys.argv)

        self.QApp.startingUp()
        self.QApp.processEvents()
        self.app.startDragTime()

        self.iface.initializationCompleted.connect(self.customization)
        qApp.processEvents()

        self.applyStyle()
Esempio n. 8
0
    def get_valid_mime_uri(layer_name, uri, wkb_type):
        """
        Gross method to force a valid layer path, only used for very old QGIS versions
        """
        if QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.NullGeometry:
            layer_type = QgsMapLayer.RasterLayer
        else:
            layer_type = QgsMapLayer.VectorLayer

        if QThread.currentThread() == QCoreApplication.instance().thread():
            from .datasourceselectdialog import DataSourceSelectDialog  # pylint: disable=import-outside-toplevel

            dlg = DataSourceSelectDialog(layer_name=layer_name,
                                         original_uri=uri,
                                         layer_type=layer_type)
            if dlg.exec_():
                return dlg.uri

        # use default dummy path - QGIS 3.4 will crash on invalid layer sources otherwise
        uri = QgsMimeDataUtils.Uri()
        if QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.PointGeometry:
            file = 'dummy_points.shp'
        elif QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.LineGeometry:
            file = 'dummy_lines.shp'
        elif QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.PolygonGeometry:
            file = 'dummy_polygon.shp'
        elif QgsWkbTypes.geometryType(wkb_type) == QgsWkbTypes.NullGeometry:
            file = 'dummy_raster.tif'
        else:
            # ???
            file = 'dummy_points.shp'

        path = os.path.dirname(os.path.abspath(__file__))
        uri.uri = os.path.realpath(os.path.join(path, '..', '..',
                                                file)).replace('\\', '/')
        uri.providerKey = 'ogr'
        return uri
Esempio n. 9
0
 def rewritefile(layer):
     with open(filename, 'w') as f:
         f.write("name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n")
     # print "Rewritten file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
Esempio n. 10
0
 def appendfile(layer):
     with open(filename, 'a') as f:
         f.write('3,tiger\n')
     # print "Appended to file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
Esempio n. 11
0
def qgis_excepthook(type, value, tb):
    # detect if running in the main thread
    in_main_thread = QCoreApplication.instance() is None or QThread.currentThread() == QCoreApplication.instance().thread()

    # only use messagebar if running in main thread - otherwise it will crash!
    showException(type, value, tb, None, messagebar=in_main_thread)
 def rewritefile(layer):
     with open(filename, 'w') as f:
         f.write("name,size,id\ntoad,small,5\nmole,medium,6\nbadger,big,7\n")
     # print "Rewritten file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
 def appendfile(layer):
     with open(filename, 'a') as f:
         f.write('3,tiger\n')
     # print "Appended to file - sleeping"
     time.sleep(1)
     QCoreApplication.instance().processEvents()
Esempio n. 14
0
def qgis_excepthook(type, value, tb):
    # detect if running in the main thread
    in_main_thread = QCoreApplication.instance() is None or QThread.currentThread() == QCoreApplication.instance().thread()

    # only use messagebar if running in main thread - otherwise it will crash!
    showException(type, value, tb, None, messagebar=in_main_thread)
Esempio n. 15
0
def get_pixel_count_by_pixel_values(layer, band, pixel_values=None, nodata=-1):
    app = QCoreApplication.instance()

    nodata = nodata if nodata != -1 else None
    if pixel_values is None:
        pixel_values = get_pixel_values(layer, band)

    # put nodata at the beginning, with the idea to include it for stopping
    # the counting when reaching the total pixels, delete it at the end
    if nodata is not None:
        if nodata in pixel_values: pixel_values.remove(nodata)
        pixel_values.insert(0, nodata)

    try:
        import xarray as xr
        import dask.array as da
        dataset = xr.open_rasterio(get_file_path_of_layer(layer),
                                   chunks={
                                       'band': 1,
                                       'x': 2000,
                                       'y': 2000
                                   })
        parallel = True
    except:
        dataset = gdal_array.LoadFile(get_file_path_of_layer(layer))
        parallel = False

    if len(dataset.shape) == 3:
        if parallel:
            dataset = dataset.sel(band=band)
        else:
            dataset = dataset[band - 1]

    max_pixels = dataset.shape[-1] * dataset.shape[-2]

    progress = QProgressDialog(
        'AcATaMa is counting the number of pixels for each thematic value.\n'
        'Depending on the size of the image, it would take a few minutes.',
        None, 0, 100, iface.mainWindow())
    progress.setWindowTitle("AcATaMa - Counting pixels by values... " +
                            ("[parallel]" if parallel else "[not parallel!]"))
    progress.setWindowModality(Qt.WindowModal)
    progress.setValue(0)
    progress.show()
    app.processEvents()

    global total_count
    total_count = 0

    def count_value(pixel_value):
        global total_count
        if total_count >= max_pixels:
            return 0
        if parallel:
            count = da.count_nonzero(dataset == pixel_value).compute()
        else:
            count = np.count_nonzero(dataset == pixel_value)
        total_count += count
        progress.setValue(int(total_count * 100 / max_pixels))
        return count

    pixel_counts = [count_value(pixel_value) for pixel_value in pixel_values]

    if nodata is not None:
        pixel_values.pop(0)
        pixel_counts.pop(0)

    progress.accept()
    return dict(zip(pixel_values, pixel_counts))