コード例 #1
0
class AuthConfigLineEdit(QWidget):
    """Simple widget composed of a QLineEdit and a QButton to start
    AuthConfigSelectDialog.
    This widget is proposed to have a simaple embeddable widget to edit and
    select a AuthCfg ID.
    """
    def __init__(self, parent=None, authcfg=None, provider=None):
        super(AuthConfigLineEdit, self).__init__(parent)

        self.authcfg = authcfg

        layout = QHBoxLayout()
        self.authCfgLineEdit = QLineEdit()
        self.authCfgLineEdit.setObjectName("authCfgLineEdit")
        self.authCfgLineEdit.setText(self.authcfg)
        self.authSelectButton = QPushButton()
        self.authSelectButton.setObjectName("authSelectButton")
        self.authSelectButton.setText("Select")
        layout.addWidget(self.authCfgLineEdit)
        layout.addWidget(self.authSelectButton)
        self.setLayout(layout)
        self.authSelectButton.clicked.connect(self.selectAuthCfg)

    def selectAuthCfg():
        dlg = AuthConfigSelectDialog(self, self.authcfg)
        if dlg.exec_():
            self.authcfg = dlg.authcfg
            self.authCfgLineEdit.setText(self.authcfg)
コード例 #2
0
    def build_gui(self):
        self.setWindowTitle(self.app_descr)
        self.setWindowIcon(QIcon(":/plugins/irmt/weights.svg"))
        self.vlayout = QVBoxLayout()
        self.setLayout(self.vlayout)
        self.vlayout.addWidget(self.message_bar)
        self.web_view = GemQWebView(self.gem_header_name,
                                    self.gem_header_value,
                                    self.gem_api,
                                    parent=self)
        self.vlayout.addWidget(self.web_view)
        initial_width = 1050
        self.resize(initial_width, self.width())
        self.setWindowFlags(Qt.Window)

        self.reload_homepage_btn = QPushButton("Reload homepage")
        # FIXME: Instead of a fixed width, we should use the natural btn size
        self.reload_homepage_btn.setFixedWidth(150)
        self.reload_homepage_btn.clicked.connect(
            self.on_reload_homepage_btn_clicked)

        self.lower_message_bar = QgsMessageBar(self)

        self.btn_hlayout = QHBoxLayout()
        self.btn_hlayout.setAlignment(Qt.AlignLeft)
        self.btn_hlayout.addWidget(self.reload_homepage_btn)
        self.btn_hlayout.addWidget(self.lower_message_bar)
        self.vlayout.addLayout(self.btn_hlayout)

        self.load_homepage()
コード例 #3
0
    def __init__(self, parent=None, authcfg=None, provider=None):
        super(AuthConfigLineEdit, self).__init__(parent)

        self.authcfg = authcfg

        layout = QHBoxLayout()
        self.authCfgLineEdit = QLineEdit()
        self.authCfgLineEdit.setObjectName("authCfgLineEdit")
        self.authCfgLineEdit.setText(self.authcfg)
        self.authSelectButton = QPushButton()
        self.authSelectButton.setObjectName("authSelectButton")
        self.authSelectButton.setText("Select")
        layout.addWidget(self.authCfgLineEdit)
        layout.addWidget(self.authSelectButton)
        self.setLayout(layout)
        self.authSelectButton.clicked.connect(self.selectAuthCfg)
コード例 #4
0
def start_worker(worker, message_bar, message):
    """
    Configure the QgsMessageBar with a :guilabel:`Cancel` button and start
    the worker in a new thread

    :param worker: the worker to be started
    :param message_bar: the message bar to be used to display progress
    :param message: a message describing the task to be performed
    """
    # configure the QgsMessageBar
    message_bar_item = message_bar.createMessage(message)
    progress_bar = QProgressBar()
    progress_bar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
    cancel_button = QPushButton()
    cancel_button.setText('Cancel')
    cancel_button.clicked.connect(worker.kill)
    message_bar_item.layout().addWidget(progress_bar)
    message_bar_item.layout().addWidget(cancel_button)
    message_bar.pushWidget(message_bar_item, message_bar.INFO)

    # start the worker in a new thread
    thread = QThread(message_bar.parent())
    worker.moveToThread(thread)

    worker.set_message.connect(
        lambda message: set_worker_message(message, message_bar_item))

    worker.toggle_show_progress.connect(
        lambda show: toggle_worker_progress(show, progress_bar))

    worker.toggle_show_cancel.connect(
        lambda show: toggle_worker_cancel(show, cancel_button))

    worker.finished.connect(lambda result: worker_finished(
        result, thread, worker, message_bar, message_bar_item))

    worker.error.connect(
        lambda e, exception_str: worker_error(e, exception_str, message_bar))

    worker.progress.connect(progress_bar.setValue)
    thread.started.connect(worker.run)
    thread.start()
    return thread, message_bar_item
コード例 #5
0
ファイル: ipt_dialog.py プロジェクト: huazhz/oq-irmt-qgis
 def build_gui(self):
     super(IptDialog, self).build_gui()
     if DEBUG:
         self.set_example_btn = QPushButton("Set example")
         self.set_example_btn.clicked.connect(
             self.on_set_example_btn_clicked)
         ipt_example = '%s/%s?tab_id=1&subtab_id=0&example_id=99' % (
             self.host, self.app_name)
         self.example_url = QLineEdit(ipt_example)
         self.hlayout = QHBoxLayout()
         self.hlayout.addWidget(self.example_url)
         self.hlayout.addWidget(self.set_example_btn)
         self.vlayout.addLayout(self.hlayout)
コード例 #6
0
    def show_results(self,
                     api_results,
                     tbl_result=None,
                     pg_connections=dict(),
                     progress_bar=QProgressBar):
        """Display the results in a table ."""
        logger.info("Results manager called. Displaying the results")
        # check parameters
        if not tbl_result:
            tbl_result = self.isogeo_widget.tbl_result
        else:
            pass
        # Get the name (and other informations) of all databases whose
        # connection is set up in QGIS
        if pg_connections == {}:
            pg_connections = self.pg_connections
        else:
            pass
        # Set table rows
        if api_results.get("total") >= 10:
            tbl_result.setRowCount(10)
        else:
            tbl_result.setRowCount(api_results.get("total"))

        # Looping inside the table lines. For each of them, showing the title,
        # abstract, geometry type, and a button that allow to add the data
        # to the canvas.
        count = 0
        for i in api_results.get("results"):
            # get useful metadata
            md_id = i.get("_id")
            md_keywords = [
                i.get("tags").get(k) for k in i.get("tags", [
                    "NR",
                ]) if k.startswith("keyword:isogeo")
            ]
            md_title = i.get("title", "NR")
            ds_geometry = i.get("geometry")

            # COLUMN 1 - Title and abstract
            # Displaying the metadata title inside a button
            btn_md_title = QPushButton(
                custom_tools.format_button_title(md_title))
            # Connecting the button to the full metadata popup
            btn_md_title.pressed.connect(
                partial(self.send_details_request, md_id=md_id))
            # Putting the abstract as a tooltip on this button
            btn_md_title.setToolTip(i.get("abstract", "")[:300])
            # Insert it in column 1
            tbl_result.setCellWidget(count, 0, btn_md_title)

            # COLUMN 2 - Data last update
            tbl_result.setItem(
                count, 1,
                QTableWidgetItem(custom_tools.handle_date(i.get("_modified"))))

            # COLUMN 3 - Geometry type
            lbl_geom = QLabel(tbl_result)
            if ds_geometry:
                if ds_geometry in point_list:
                    lbl_geom.setPixmap(pix_point)
                    lbl_geom.setToolTip(self.tr("Point", "ResultsManager"))
                elif ds_geometry in polygon_list:
                    lbl_geom.setPixmap(pix_polyg)
                    lbl_geom.setToolTip(self.tr("Polygon", "ResultsManager"))
                elif ds_geometry in line_list:
                    lbl_geom.setPixmap(pix_line)
                    lbl_geom.setToolTip(self.tr("Line", "ResultsManager"))
                elif ds_geometry in multi_list:
                    lbl_geom.setPixmap(pix_multi)
                    lbl_geom.setToolTip(
                        self.tr("MultiPolygon", "ResultsManager"))
                elif ds_geometry == "TIN":
                    tbl_result.setItem(count, 2, QTableWidgetItem(u"TIN"))
                else:
                    tbl_result.setItem(
                        count, 2,
                        QTableWidgetItem(
                            self.tr("Unknown geometry", "ResultsManager")))
            else:
                if "rasterDataset" in i.get("type"):
                    lbl_geom.setPixmap(pix_rastr)
                    lbl_geom.setToolTip(self.tr("Raster", "ResultsManager"))
                elif "service" in i.get("type"):
                    lbl_geom.setPixmap(pix_serv)
                    lbl_geom.setToolTip(self.tr("Service", "ResultsManager"))
                else:
                    lbl_geom.setPixmap(pix_nogeo)
                    lbl_geom.setToolTip(
                        self.tr("Unknown geometry", "ResultsManager"))

            tbl_result.setCellWidget(count, 2, lbl_geom)

            # COLUMN 4 - Add options
            dico_add_options = {}

            # Files and PostGIS direct access
            if "format" in i.keys():
                # If the data is a vector and the path is available, store
                # useful information in the dict
                if i.get("format", "NR") in li_formats_vect and "path" in i:
                    filepath = custom_tools.format_path(i.get("path"))
                    dir_file = os.path.dirname(filepath)
                    if dir_file not in self.cached_unreach_paths:
                        try:
                            open(filepath)
                            params = [
                                "vector", filepath,
                                i.get("title", "NR"),
                                i.get("abstract", "NR"), md_keywords
                            ]
                            dico_add_options[self.tr(
                                "Data file", "ResultsManager")] = params
                        except IOError:
                            self.cached_unreach_paths.append(dir_file)
                            self.cached_unreach_paths = list(
                                set(self.cached_unreach_paths))
                    else:
                        logger.debug(
                            "Path has been ignored because it's cached.")
                        pass
                # Same if the data is a raster
                elif i.get("format", "NR") in li_formats_rastr and "path" in i:
                    filepath = custom_tools.format_path(i.get("path"))
                    dir_file = os.path.dirname(filepath)
                    if dir_file not in self.cached_unreach_paths:
                        try:
                            open(filepath)
                            params = [
                                "raster", filepath,
                                i.get("title", "NR"),
                                i.get("abstract", "NR"), md_keywords
                            ]
                            dico_add_options[self.tr(
                                "Data file", "ResultsManager")] = params
                        except IOError:
                            self.cached_unreach_paths.append(dir_file)
                            pass
                    else:
                        logger.debug(
                            "Path has been ignored because it's cached.")
                        pass
                # If the data is a postGIS table and the connexion has
                # been saved in QGIS.
                elif i.get("format") == "postgis":
                    # Récupère le nom de la base de données
                    base_name = i.get("path")
                    if base_name in pg_connections.keys():
                        params = {}
                        params["base_name"] = base_name
                        schema_table = i.get("name")
                        if schema_table is not None and "." in schema_table:
                            params["schema"] = schema_table.split(".")[0]
                            params["table"] = schema_table.split(".")[1]
                            params["abstract"] = i.get("abstract", None)
                            params["title"] = i.get("title", None)
                            params["keywords"] = md_keywords
                            dico_add_options[self.tr(
                                "PostGIS table", "ResultsManager")] = params
                        else:
                            pass
                    else:
                        pass
                else:
                    pass
            # Associated service layers
            d_type = i.get("type")
            if d_type == "vectorDataset" or d_type == "rasterDataset":
                for layer in i.get("serviceLayers"):
                    service = layer.get("service")
                    if service is not None:
                        srv_details = {
                            "path": service.get("path", "NR"),
                            "formatVersion": service.get("formatVersion")
                        }
                        # EFS
                        if service.get("format") == "efs":
                            name_url = srv_url_bld.build_efs_url(
                                layer,
                                srv_details,
                                rsc_type="ds_dyn_lyr_srv",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # EMS
                        if service.get("format") == "ems":
                            name_url = srv_url_bld.build_ems_url(
                                layer,
                                srv_details,
                                rsc_type="ds_dyn_lyr_srv",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WFS
                        if service.get("format") == "wfs":
                            name_url = srv_url_bld.build_wfs_url(
                                layer,
                                srv_details,
                                rsc_type="ds_dyn_lyr_srv",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WMS
                        elif service.get("format") == "wms":
                            name_url = srv_url_bld.build_wms_url(
                                layer,
                                srv_details,
                                rsc_type="ds_dyn_lyr_srv",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WMTS
                        elif service.get("format") == "wmts":
                            name_url = srv_url_bld.build_wmts_url(
                                layer, srv_details, rsc_type="ds_dyn_lyr_srv")
                            if name_url[0] != 0:
                                dico_add_options[u"WMTS : " +
                                                 name_url[1]] = name_url
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
            # New association mode. For services metadata sheet, the layers
            # are stored in the purposely named include: "layers".
            elif i.get("type") == "service":
                if i.get("layers") is not None:
                    srv_details = {
                        "path": i.get("path", "NR"),
                        "formatVersion": i.get("formatVersion")
                    }
                    # WFS
                    if i.get("format") == "wfs":
                        for layer in i.get("layers"):
                            name_url = srv_url_bld.build_wfs_url(
                                layer,
                                srv_details,
                                rsc_type="service",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                                pass
                    # WMS
                    elif i.get("format") == "wms":
                        for layer in i.get("layers"):
                            name_url = srv_url_bld.build_wms_url(
                                layer,
                                srv_details,
                                rsc_type="service",
                                mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                                pass
                    # WMTS
                    elif i.get("format") == "wmts":
                        for layer in i.get("layers"):
                            name_url = srv_url_bld.build_wmts_url(
                                layer, srv_details, rsc_type="service")
                            if name_url[0] != 0:
                                btn_label = "WMTS : {}".format(name_url[1])
                                dico_add_options[btn_label] = name_url
                            else:
                                continue
                                pass
                    else:
                        pass
            else:
                pass

            # Now the plugin has tested every possibility for the layer to be
            # added. The "Add" column has to be filled accordingly.

            # If the data can't be added, just insert "can't" text.
            if dico_add_options == {}:
                text = self.tr("Can't be added", "ResultsManager")
                fake_button = QPushButton(text)
                fake_button.setStyleSheet("text-align: left")
                fake_button.setEnabled(False)
                tbl_result.setCellWidget(count, 3, fake_button)
            # If there is only one way for the data to be added, insert a
            # button.
            elif len(dico_add_options) == 1:
                text = dico_add_options.keys()[0]
                params = dico_add_options.get(text)
                if text.startswith("WFS"):
                    icon = ico_wfs
                elif text.startswith("WMS"):
                    icon = ico_wms
                elif text.startswith("WMTS"):
                    icon = ico_wmts
                elif text.startswith("EFS"):
                    icon = ico_efs
                elif text.startswith("EMS"):
                    icon = ico_ems
                elif text.startswith(self.tr("PostGIS table",
                                             "ResultsManager")):
                    icon = ico_pgis
                elif text.startswith(self.tr("Data file", "ResultsManager")):
                    icon = ico_file
                add_button = QPushButton(icon, text)
                add_button.setStyleSheet("text-align: left")
                add_button.pressed.connect(
                    partial(self.add_layer, layer_info=["info", params]))
                tbl_result.setCellWidget(count, 3, add_button)
            # Else, add a combobox, storing all possibilities.
            else:
                combo = QComboBox()
                for i in dico_add_options:
                    if i.startswith("WFS"):
                        icon = ico_wfs
                    elif i.startswith("WMS"):
                        icon = ico_wms
                    elif i.startswith("WMTS"):
                        icon = ico_wmts
                    elif i.startswith("EFS"):
                        icon = ico_efs
                    elif i.startswith("EMS"):
                        icon = ico_ems
                    elif i.startswith(
                            self.tr("PostGIS table", "ResultsManager")):
                        icon = ico_pgis
                    elif i.startswith(self.tr("Data file", "ResultsManager")):
                        icon = ico_file
                    combo.addItem(icon, i, dico_add_options.get(i))
                combo.activated.connect(
                    partial(self.add_layer, layer_info=["index", count]))
                tbl_result.setCellWidget(count, 3, combo)

            count += 1
        # dimensions
        header = tbl_result.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.ResizeToContents)
        header.setResizeMode(2, QHeaderView.ResizeToContents)
        # Remove the "loading" bar
        iface.mainWindow().statusBar().removeWidget(progress_bar)
        # method ending
        return None
コード例 #7
0
    def show_output_list(self, output_list, calculation_mode):
        if not output_list:
            self.clear_output_list()
            self.download_datastore_btn.setEnabled(False)
            self.download_datastore_btn.setText('Download HDF5 datastore')
            return
        exclude = ['url', 'outtypes', 'type']
        selected_keys = [key for key in sorted(output_list[0].keys())
                         if key not in exclude]
        max_actions = 0
        for row in output_list:
            num_actions = len(row['outtypes'])
            if row['type'] in (OQ_TO_LAYER_TYPES |
                               OQ_RST_TYPES |
                               OQ_EXTRACT_TO_VIEW_TYPES):
                # TODO: remove check when gmf_data will be loadable also for
                #       event_based
                if not (row['type'] == 'gmf_data'
                        and 'event_based' in calculation_mode):
                    num_actions += 1  # needs additional column for loader btn
            if "%s_aggr" % row['type'] in OQ_EXTRACT_TO_VIEW_TYPES:
                num_actions += 1
            max_actions = max(max_actions, num_actions)

        self.output_list_tbl.setRowCount(len(output_list))
        self.output_list_tbl.setColumnCount(
            len(selected_keys) + max_actions)
        for row, output in enumerate(output_list):
            for col, key in enumerate(selected_keys):
                item = QTableWidgetItem()
                value = output_list[row][key]
                item.setData(Qt.DisplayRole, value)
                self.output_list_tbl.setItem(row, col, item)
            outtypes = output_list[row]['outtypes']
            for col, outtype in enumerate(outtypes, len(selected_keys)):
                action = 'Download'
                button = QPushButton()
                self.connect_button_to_action(button, action, output, outtype)
                self.output_list_tbl.setCellWidget(row, col, button)
                self.calc_list_tbl.setColumnWidth(col, BUTTON_WIDTH)
                if output['type'] in (OQ_TO_LAYER_TYPES |
                                      OQ_RST_TYPES |
                                      OQ_EXTRACT_TO_VIEW_TYPES):
                    if output['type'] in (OQ_RST_TYPES |
                                          OQ_EXTRACT_TO_VIEW_TYPES):
                        action = 'Show'
                    else:
                        action = 'Load as layer'
                    # TODO: remove check when gmf_data will be loadable also
                    #       for event_based
                    if (output['type'] == 'gmf_data'
                            and calculation_mode == 'event_based'):
                        continue
                    button = QPushButton()
                    self.connect_button_to_action(
                        button, action, output, outtype)
                    self.output_list_tbl.setCellWidget(row, col + 1, button)
                if "%s_aggr" % output['type'] in OQ_EXTRACT_TO_VIEW_TYPES:
                    mod_output = copy.deepcopy(output)
                    mod_output['type'] = "%s_aggr" % output['type']
                    button = QPushButton()
                    self.connect_button_to_action(
                        button, 'Aggregate', mod_output, outtype)
                    self.output_list_tbl.setCellWidget(row, col + 2, button)
        col_names = [key.capitalize() for key in selected_keys]
        empty_col_names = ['' for outtype in range(max_actions)]
        headers = col_names + empty_col_names
        self.output_list_tbl.setHorizontalHeaderLabels(headers)
        self.output_list_tbl.horizontalHeader().setStyleSheet(
            "font-weight: bold;")
        self.output_list_tbl.resizeColumnsToContents()
        self.output_list_tbl.resizeRowsToContents()
コード例 #8
0
 def refresh_calc_list(self):
     # returns True if the list is correctly retrieved
     calc_list_url = "%s/v1/calc/list?relevant=true" % self.hostname
     with WaitCursorManager():
         try:
             # FIXME: enable the user to set verify=True
             resp = self.session.get(
                 calc_list_url, timeout=10, verify=False,
                 allow_redirects=False)
             if resp.status_code == 302:
                 raise RedirectionError(
                     "Error %s loading %s: please check the url" % (
                         resp.status_code, resp.url))
             if not resp.ok:
                 raise ServerError(
                     "Error %s loading %s: %s" % (
                         resp.status_code, resp.url, resp.reason))
         except HANDLED_EXCEPTIONS as exc:
             self._handle_exception(exc)
             return False
         calc_list = json.loads(resp.text)
     selected_keys = [
         'description', 'id', 'calculation_mode', 'owner', 'status']
     col_names = [
         'Description', 'Job ID', 'Calculation Mode', 'Owner', 'Status']
     col_widths = [340, 60, 135, 70, 80]
     if not calc_list:
         if self.calc_list_tbl.rowCount() > 0:
             self.calc_list_tbl.clearContents()
             self.calc_list_tbl.setRowCount(0)
         else:
             self.calc_list_tbl.setRowCount(0)
             self.calc_list_tbl.setColumnCount(len(col_names))
             self.calc_list_tbl.setHorizontalHeaderLabels(col_names)
             self.calc_list_tbl.horizontalHeader().setStyleSheet(
                 "font-weight: bold;")
             self.set_calc_list_widths(col_widths)
         return False
     actions = [
         {'label': 'Console', 'bg_color': '#3cb3c5', 'txt_color': 'white'},
         {'label': 'Remove', 'bg_color': '#d9534f', 'txt_color': 'white'},
         {'label': 'Outputs', 'bg_color': '#3cb3c5', 'txt_color': 'white'},
         {'label': 'Continue', 'bg_color': 'white', 'txt_color': 'black'}
     ]
     self.calc_list_tbl.clearContents()
     self.calc_list_tbl.setRowCount(len(calc_list))
     self.calc_list_tbl.setColumnCount(len(selected_keys) + len(actions))
     for row, calc in enumerate(calc_list):
         for col, key in enumerate(selected_keys):
             item = QTableWidgetItem()
             try:
                 value = calc_list[row][key]
             except KeyError:
                 # from engine2.5 to engine2.6, job_type was changed into
                 # calculation_mode. This check prevents the plugin to break
                 # wnen using an old version of the engine.
                 if key == 'calculation_mode':
                     value = 'unknown'
                 else:
                     # if any other unexpected keys are used, it is safer to
                     # raise a KeyError
                     raise
             item.setData(Qt.DisplayRole, value)
             # set default colors
             row_bg_color = Qt.white
             row_txt_color = Qt.black
             if calc['status'] == 'failed':
                 row_bg_color = QColor('#f2dede')
             elif calc['status'] == 'complete':
                 row_bg_color = QColor('#dff0d8')
             item.setBackgroundColor(row_bg_color)
             item.setTextColor(row_txt_color)
             self.calc_list_tbl.setItem(row, col, item)
         for col, action in enumerate(actions, len(selected_keys)):
             # display the Continue and Output buttons only if the
             # computation is completed
             if (calc['status'] != 'complete' and
                     action['label'] in ('Continue', 'Outputs')):
                 continue
             button = QPushButton()
             button.setText(action['label'])
             style = 'background-color: %s; color: %s' % (
                 action['bg_color'], action['txt_color'])
             button.setStyleSheet(style)
             QObject.connect(
                 button, SIGNAL("clicked()"),
                 lambda calc_id=calc['id'], action=action['label']: (
                     self.on_calc_action_btn_clicked(calc_id, action)))
             self.calc_list_tbl.setCellWidget(row, col, button)
             self.calc_list_tbl.setColumnWidth(col, BUTTON_WIDTH)
     empty_col_names = [''] * len(actions)
     headers = col_names + empty_col_names
     self.calc_list_tbl.setHorizontalHeaderLabels(headers)
     self.calc_list_tbl.horizontalHeader().setStyleSheet(
         "font-weight: bold;")
     self.set_calc_list_widths(col_widths)
     if self.pointed_calc_id:
         self.highlight_and_scroll_to_calc_id(self.pointed_calc_id)
     # if a running calculation is selected, the corresponding outputs will
     # be displayed (once) automatically at completion
     if (self.pointed_calc_id and
             self.output_list_tbl.rowCount() == 0):
         self.update_output_list(self.pointed_calc_id)
     return True
コード例 #9
0
class StandaloneAppDialog(QDialog):
    """
    Dialog to be inherited by OpenQuake standalone applications

    :param app_name: short name of the app as it appears in the url
    :param app_descr: longer name to be used as the window title
    :param gem_header_name: header that identifies that the application is
        being driven from QGIS
    :param gem_header_value: version of the interface between the plugin and
        the embedded application
    :param parent: the parent object (optional)
    """
    def __init__(self,
                 app_name,
                 app_descr,
                 gem_header_name,
                 gem_header_value,
                 parent=None):
        super(StandaloneAppDialog, self).__init__(parent)

        self.message_bar = QgsMessageBar(self)
        self.app_name = app_name
        self.app_descr = app_descr
        self.gem_header_name = gem_header_name
        self.gem_header_value = gem_header_value
        self.web_view = None
        self.set_host()

    def set_host(self):
        engine_profiles = json.loads(QSettings().value(
            'irmt/engine_profiles', DEFAULT_ENGINE_PROFILES))
        cur_eng_profile = QSettings().value('irmt/current_engine_profile')
        if cur_eng_profile is None:
            cur_eng_profile = engine_profiles.keys()[0]
        engine_profile = engine_profiles[cur_eng_profile]
        engine_hostname = engine_profile['hostname']
        self.host = QSettings().value('irmt/engine_hostname', engine_hostname)

    def load_homepage(self):
        if self.web_view is not None:
            qurl = QUrl('%s/%s' % (self.host, self.app_name))
            # # Uncomment to use the dummy example instead
            # if self.app_name == 'taxtweb':
            #     qurl = QUrl('http://localhost:8000')
            self.web_view.load(qurl)

    def build_gui(self):
        self.setWindowTitle(self.app_descr)
        self.setWindowIcon(QIcon(":/plugins/irmt/weights.svg"))
        self.vlayout = QVBoxLayout()
        self.setLayout(self.vlayout)
        self.vlayout.addWidget(self.message_bar)
        self.web_view = GemQWebView(self.gem_header_name,
                                    self.gem_header_value,
                                    self.gem_api,
                                    parent=self)
        self.vlayout.addWidget(self.web_view)
        initial_width = 1050
        self.resize(initial_width, self.width())
        self.setWindowFlags(Qt.Window)

        self.reload_homepage_btn = QPushButton("Reload homepage")
        # FIXME: Instead of a fixed width, we should use the natural btn size
        self.reload_homepage_btn.setFixedWidth(150)
        self.reload_homepage_btn.clicked.connect(
            self.on_reload_homepage_btn_clicked)

        self.lower_message_bar = QgsMessageBar(self)

        self.btn_hlayout = QHBoxLayout()
        self.btn_hlayout.setAlignment(Qt.AlignLeft)
        self.btn_hlayout.addWidget(self.reload_homepage_btn)
        self.btn_hlayout.addWidget(self.lower_message_bar)
        self.vlayout.addLayout(self.btn_hlayout)

        self.load_homepage()

    def on_reload_homepage_btn_clicked(self):
        msg = ("Reloading the homepage, all current changes will be discarded."
               " Are you sure?")
        reply = QMessageBox.question(self, 'Warning', msg, QMessageBox.Yes,
                                     QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.set_host()
            self.load_homepage()

    def on_set_example_btn_clicked(self):
        qurl = QUrl(self.example_url.text())
        self.web_view.load(qurl)
コード例 #10
0
    def fillTreeUsingProviders(self):
        self.items = {}
        self.model.clear()
        self.model.setHorizontalHeaderLabels(
            [self.tr('Setting'), self.tr('Value')])

        settings = ProcessingConfig.getSettings()

        rootItem = self.model.invisibleRootItem()
        """
        Filter 'General', 'Models' and 'Scripts' items
        """
        priorityKeys = [
            self.tr('General'),
            self.tr('Models'),
            self.tr('Scripts')
        ]
        for group in priorityKeys:
            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)
            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            rootItem.insertRow(0, [groupItem, emptyItem])
            # add menu item only if it has any search matches
            for setting in settings[group]:
                if setting.hidden or setting.name.startswith("MENU_"):
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])
        """
        Filter 'Providers' items
        """
        providersItem = QStandardItem(self.tr('Providers'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'alg.png'))
        providersItem.setIcon(icon)
        providersItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [providersItem, emptyItem])
        for group in settings.keys():
            if group in priorityKeys or group == menusSettingsGroup:
                continue

            groupItem = QStandardItem(group)
            icon = ProcessingConfig.getGroupIcon(group)
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for setting in settings[group]:
                if setting.hidden:
                    continue

                labelItem = QStandardItem(setting.description)
                labelItem.setIcon(icon)
                labelItem.setEditable(False)
                self.items[setting] = SettingItem(setting)
                groupItem.insertRow(0, [labelItem, self.items[setting]])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)
            providersItem.appendRow([groupItem, emptyItem])
        """
        Filter 'Menus' items
        """
        self.menusItem = QStandardItem(self.tr('Menus (requires restart)'))
        icon = QIcon(os.path.join(pluginPath, 'images', 'menu.png'))
        self.menusItem.setIcon(icon)
        self.menusItem.setEditable(False)
        emptyItem = QStandardItem()
        emptyItem.setEditable(False)

        rootItem.insertRow(0, [self.menusItem, emptyItem])

        button = QPushButton(self.tr('Reset to defaults'))
        button.clicked.connect(self.resetMenusToDefaults)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        layout.addWidget(button)
        layout.addStretch()
        widget = QWidget()
        widget.setLayout(layout)
        self.tree.setIndexWidget(emptyItem.index(), widget)

        providers = Processing.providers
        for provider in providers:
            providerDescription = provider.getDescription()
            groupItem = QStandardItem(providerDescription)
            icon = provider.getIcon()
            groupItem.setIcon(icon)
            groupItem.setEditable(False)

            for alg in provider.algs:
                algItem = QStandardItem(alg.i18n_name or alg.name)
                algItem.setIcon(icon)
                algItem.setEditable(False)
                try:
                    settingMenu = ProcessingConfig.settings[
                        "MENU_" + alg.commandLineName()]
                    settingButton = ProcessingConfig.settings[
                        "BUTTON_" + alg.commandLineName()]
                    settingIcon = ProcessingConfig.settings[
                        "ICON_" + alg.commandLineName()]
                except:
                    continue
                self.items[settingMenu] = SettingItem(settingMenu)
                self.items[settingButton] = SettingItem(settingButton)
                self.items[settingIcon] = SettingItem(settingIcon)
                menuLabelItem = QStandardItem("Menu path")
                menuLabelItem.setEditable(False)
                buttonLabelItem = QStandardItem("Add button in toolbar")
                buttonLabelItem.setEditable(False)
                iconLabelItem = QStandardItem("Icon")
                iconLabelItem.setEditable(False)
                emptyItem = QStandardItem()
                emptyItem.setEditable(False)
                algItem.insertRow(0, [menuLabelItem, self.items[settingMenu]])
                algItem.insertRow(0,
                                  [buttonLabelItem, self.items[settingButton]])
                algItem.insertRow(0, [iconLabelItem, self.items[settingIcon]])
                groupItem.insertRow(0, [algItem, emptyItem])

            emptyItem = QStandardItem()
            emptyItem.setEditable(False)

            self.menusItem.appendRow([groupItem, emptyItem])

        self.tree.sortByColumn(0, Qt.AscendingOrder)
        self.adjustColumns()
コード例 #11
0
ファイル: results.py プロジェクト: isogeo/isogeo-plugin-qgis
    def show_results(self, api_results, tbl_result=None, pg_connections=dict(), progress_bar=QProgressBar):
        """Display the results in a table ."""
        logger.info("Results manager called. Displaying the results")
        # check parameters
        if not tbl_result:
            tbl_result = self.isogeo_widget.tbl_result
        else:
            pass
        # Get the name (and other informations) of all databases whose
        # connection is set up in QGIS
        if pg_connections == {}:
            pg_connections = self.pg_connections
        else:
            pass
        # Set table rows
        if api_results.get("total") >= 10:
            tbl_result.setRowCount(10)
        else:
            tbl_result.setRowCount(api_results.get("total"))

        # Looping inside the table lines. For each of them, showing the title,
        # abstract, geometry type, and a button that allow to add the data
        # to the canvas.
        count = 0
        for i in api_results.get("results"):
            # get useful metadata
            md_id = i.get("_id")
            md_keywords = [i.get("tags").get(k)
                           for k in i.get("tags", ["NR", ])
                           if k.startswith("keyword:isogeo")]
            md_title = i.get("title", "NR")
            ds_geometry = i.get("geometry")

            # COLUMN 1 - Title and abstract
            # Displaying the metadata title inside a button
            btn_md_title = QPushButton(plg_tools.format_button_title(md_title))
            # Connecting the button to the full metadata popup
            btn_md_title.pressed.connect(partial(
                self.send_details_request, md_id=md_id))
            # Putting the abstract as a tooltip on this button
            btn_md_title.setToolTip(i.get("abstract", "")[:300])
            # Insert it in column 1
            tbl_result.setCellWidget(count, 0, btn_md_title)

            # COLUMN 2 - Data last update
            tbl_result.setItem(
                count, 1, QTableWidgetItem(
                    plg_tools.handle_date(i.get("_modified"))))

            # COLUMN 3 - Geometry type
            lbl_geom = QLabel(tbl_result)
            if ds_geometry:
                if ds_geometry in point_list:
                    lbl_geom.setPixmap(pix_point)
                    lbl_geom.setToolTip(self.tr("Point", "ResultsManager"))
                elif ds_geometry in polygon_list:
                    lbl_geom.setPixmap(pix_polyg)
                    lbl_geom.setToolTip(self.tr("Polygon", "ResultsManager"))
                elif ds_geometry in line_list:
                    lbl_geom.setPixmap(pix_line)
                    lbl_geom.setToolTip(self.tr("Line", "ResultsManager"))
                elif ds_geometry in multi_list:
                    lbl_geom.setPixmap(pix_multi)
                    lbl_geom.setToolTip(self.tr("MultiPolygon", "ResultsManager"))
                elif ds_geometry == "TIN":
                    tbl_result.setItem(
                        count, 2, QTableWidgetItem(u"TIN"))
                else:
                    tbl_result.setItem(
                        count, 2, QTableWidgetItem(
                            self.tr("Unknown geometry", "ResultsManager")))
            else:
                if "rasterDataset" in i.get("type"):
                    lbl_geom.setPixmap(pix_rastr)
                    lbl_geom.setToolTip(self.tr("Raster", "ResultsManager"))
                elif "service" in i.get("type"):
                    lbl_geom.setPixmap(pix_serv)
                    lbl_geom.setToolTip(self.tr("Service", "ResultsManager"))
                else:
                    lbl_geom.setPixmap(pix_nogeo)
                    lbl_geom.setToolTip(self.tr("Unknown geometry", "ResultsManager"))

            tbl_result.setCellWidget(count, 2, lbl_geom)

            # COLUMN 4 - Add options
            dico_add_options = {}

            # Files and PostGIS direct access
            if "format" in i.keys():
                # If the data is a vector and the path is available, store
                # useful information in the dict
                if i.get("format", "NR") in li_formats_vect and "path" in i:
                    add_path = self._filepath_builder(i.get("path"))
                    if add_path:
                        params = ["vector", add_path,
                                  i.get("title", "NR"),
                                  i.get("abstract", "NR"),
                                  md_keywords]
                        dico_add_options[self.tr("Data file", "ResultsManager")] = params
                    else:
                        pass
                # Same if the data is a raster
                elif i.get("format", "NR") in li_formats_rastr and "path" in i:
                    add_path = self._filepath_builder(i.get("path"))
                    if add_path:
                        params = ["raster", add_path,
                                  i.get("title", "NR"),
                                  i.get("abstract", "NR"),
                                  md_keywords]
                        dico_add_options[self.tr("Data file", "ResultsManager")] = params
                    else:
                        pass
                # If the data is a postGIS table and the connexion has
                # been saved in QGIS.
                elif i.get("format") == "postgis":
                    base_name = i.get("path", "No path")
                    if base_name in pg_connections.keys():
                        params = {}
                        params["base_name"] = base_name
                        schema_table = i.get("name")
                        if schema_table is not None and "." in schema_table:
                            params["schema"] = schema_table.split(".")[0]
                            params["table"] = schema_table.split(".")[1]
                            params["abstract"] = i.get("abstract", None)
                            params["title"] = i.get("title", None)
                            params["keywords"] = md_keywords
                            dico_add_options[self.tr("PostGIS table", "ResultsManager")] = params
                        else:
                            pass
                    else:
                        pass
                else:
                    logger.debug("Metadata {} has a format but it's not recognized or path is missing".format(md_id))
                    pass
            # Associated service layers
            d_type = i.get("type")
            if d_type == "vectorDataset" or d_type == "rasterDataset":
                for layer in i.get("serviceLayers"):
                    service = layer.get("service")
                    if service is not None:
                        srv_details = {"path": service.get("path", "NR"),
                                       "formatVersion": service.get("formatVersion")}
                        # EFS
                        if service.get("format") == "efs":
                            name_url = plg_url_bldr.build_efs_url(layer, srv_details,
                                                                 rsc_type="ds_dyn_lyr_srv",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # EMS
                        if service.get("format") == "ems":
                            name_url = plg_url_bldr.build_ems_url(layer, srv_details,
                                                                 rsc_type="ds_dyn_lyr_srv",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WFS
                        if service.get("format") == "wfs":
                            name_url = plg_url_bldr.build_wfs_url(layer, srv_details,
                                                                 rsc_type="ds_dyn_lyr_srv",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WMS
                        elif service.get("format") == "wms":
                            name_url = plg_url_bldr.build_wms_url(layer, srv_details,
                                                                 rsc_type="ds_dyn_lyr_srv",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                pass
                        # WMTS
                        elif service.get("format") == "wmts":
                            name_url = plg_url_bldr.build_wmts_url(layer, srv_details,
                                                                  rsc_type="ds_dyn_lyr_srv")
                            if name_url[0] != 0:
                                dico_add_options[u"WMTS : " + name_url[1]] = name_url
                            else:
                                pass
                        else:
                            pass
                    else:
                        pass
            # New association mode. For services metadata sheet, the layers
            # are stored in the purposely named include: "layers".
            elif i.get("type") == "service":
                if i.get("layers") is not None:
                    srv_details = {"path": i.get("path", "NR"),
                                   "formatVersion": i.get("formatVersion")}
                    # EFS
                    if i.get("format") == "efs":
                        for layer in i.get("layers"):
                            name_url = plg_url_bldr.build_efs_url(layer, srv_details,
                                                                  rsc_type="service",
                                                                  mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                    # EMS
                    if i.get("format") == "ems":
                        for layer in i.get("layers"):
                            name_url = plg_url_bldr.build_ems_url(layer, srv_details,
                                                                  rsc_type="service",
                                                                  mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                    # WFS
                    if i.get("format") == "wfs":
                        for layer in i.get("layers"):
                            name_url = plg_url_bldr.build_wfs_url(layer, srv_details,
                                                                 rsc_type="service",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                    # WMS
                    elif i.get("format") == "wms":
                        for layer in i.get("layers"):
                            name_url = plg_url_bldr.build_wms_url(layer, srv_details,
                                                                 rsc_type="service",
                                                                 mode="quicky")
                            if name_url[0] != 0:
                                dico_add_options[name_url[5]] = name_url
                            else:
                                continue
                    # WMTS
                    elif i.get("format") == "wmts":
                        for layer in i.get("layers"):
                            name_url = plg_url_bldr.build_wmts_url(layer, srv_details,
                                                                  rsc_type="service")
                            if name_url[0] != 0:
                                btn_label = "WMTS : {}".format(name_url[1])
                                dico_add_options[btn_label] = name_url
                            else:
                                continue
                    else:
                        pass
            else:
                pass

            # Now the plugin has tested every possibility for the layer to be
            # added. The "Add" column has to be filled accordingly.

            # If the data can't be added, just insert "can't" text.
            if dico_add_options == {}:
                text = self.tr("Can't be added", "ResultsManager")
                fake_button = QPushButton(text)
                fake_button.setStyleSheet("text-align: left")
                fake_button.setEnabled(False)
                tbl_result.setCellWidget(count, 3, fake_button)
            # If there is only one way for the data to be added, insert a
            # button.
            elif len(dico_add_options) == 1:
                text = dico_add_options.keys()[0]
                params = dico_add_options.get(text)
                if text.startswith("WFS"):
                    icon = ico_wfs
                elif text.startswith("WMS"):
                    icon = ico_wms
                elif text.startswith("WMTS"):
                    icon = ico_wmts
                elif text.startswith("EFS"):
                    icon = ico_efs
                elif text.startswith("EMS"):
                    icon = ico_ems
                elif text.startswith(self.tr("PostGIS table", "ResultsManager")):
                    icon = ico_pgis
                elif text.startswith(self.tr("Data file", "ResultsManager")):
                    icon = ico_file
                add_button = QPushButton(icon, text)
                add_button.setStyleSheet("text-align: left")
                add_button.pressed.connect(partial(self.add_layer,
                                                   layer_info=["info", params])
                                           )
                tbl_result.setCellWidget(count, 3, add_button)
            # Else, add a combobox, storing all possibilities.
            else:
                combo = QComboBox()
                for i in dico_add_options:
                    if i.startswith("WFS"):
                        icon = ico_wfs
                    elif i.startswith("WMS"):
                        icon = ico_wms
                    elif i.startswith("WMTS"):
                        icon = ico_wmts
                    elif i.startswith("EFS"):
                        icon = ico_efs
                    elif i.startswith("EMS"):
                        icon = ico_ems
                    elif i.startswith(self.tr("PostGIS table", "ResultsManager")):
                        icon = ico_pgis
                    elif i.startswith(self.tr("Data file", "ResultsManager")):
                        icon = ico_file
                    combo.addItem(icon, i, dico_add_options.get(i))
                combo.activated.connect(partial(self.add_layer,
                                                layer_info=["index", count]))
                combo.model().sort(0)   # sort alphabetically on option prefix. see: #113
                tbl_result.setCellWidget(count, 3, combo)

            count += 1
        # dimensions
        header = tbl_result.horizontalHeader()
        header.setResizeMode(0, QHeaderView.Stretch)
        header.setResizeMode(1, QHeaderView.ResizeToContents)
        header.setResizeMode(2, QHeaderView.ResizeToContents)
        # Remove the "loading" bar
        iface.mainWindow().statusBar().removeWidget(progress_bar)
        # method ending
        return None