Example #1
0
class web2qgisDialog(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, iface, parent=None):
        """Constructor."""
        super(web2qgisDialog, self).__init__(parent)
        # Set up the user interface from Designer.
        # After setupUI you can access any designer object by doing
        # self.<objectname>, and you can use autoconnect slots - see
        # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html
        # #widgets-and-dialogs-with-auto-connect
        self.setupUi(self)
        self.iface = iface
        self.button_box.button(QDialogButtonBox.Save).setEnabled(False)
        self.loadButton.clicked.connect(self.loadMap)
        self.button_box.accepted.connect(self.getMap)
        tplPath = "file:///C:/Users/tchadwin/Desktop/%C3%A9/"
        singleSymbol = "%sqgis2web_2018_05_17-15_08_53_455820/index.html" % tplPath
        categorized = "%sqgis2web_2018_05_18-16_25_05_270745/index.html" % tplPath
        graduated = "%sqgis2web_2018_05_19-09_36_13_550344/index.html" % tplPath
        self.urlInput.setText(
            "file:///C:/Users/tchadwin/AppData/Roaming/QGIS/QGIS3/profiles/default/python/plugins/web2qgis/HTMLrefs/leaflet_point.html"
        )

    def loadMap(self):
        self.webview = QWebView()
        self.webview.loadFinished.connect(self.mapLoaded)
        self.webview.load(QUrl(self.urlInput.text()))

    def mapLoaded(self):
        webpage = self.webview.page()
        self.mainframe = webpage.mainFrame()
        self.detectMap(self.mainframe)
        for frame in self.mainframe.childFrames():
            self.detectMap(frame)

    def detectMap(self, frame):
        leaflet = detectLeaflet(frame)
        openlayers = detectOpenlayers(frame)
        if leaflet:
            self.feedbackLabel.setText("Leaflet map detected")
            self.button_box.button(QDialogButtonBox.Save).setEnabled(True)
        elif openlayers:
            self.feedbackLabel.setText("OpenLayers map detected")
            self.button_box.button(QDialogButtonBox.Save).setEnabled(True)
        else:
            self.feedbackLabel.setText("No map detected")
            self.button_box.button(QDialogButtonBox.Save).setEnabled(False)

    def getMap(self):
        webpage = self.webview.page()
        self.mainframe = webpage.mainFrame()
        if self.feedbackLabel.text() == "Leaflet map detected":
            getLeafletMap(self.mainframe, self.iface)
            for frame in self.mainframe.childFrames():
                getLeafletMap(frame, self.iface)
        elif self.feedbackLabel.text() == "OpenLayers map detected":
            getOpenlayersMap(self.mainframe, self.iface)
            for frame in self.mainframe.childFrames():
                getOpenlayersMap(frame, self.iface)
        self.feedbackLabel.clear()
Example #2
0
class HtmlViewerWidget(QWidget):
    def __init__(self, parent):
        super(HtmlViewerWidget, self).__init__(parent)
        self.setLayout(QGridLayout())
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.view = QWebView()
        self.view.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.frame = QFrame()
        self.frame.setLayout(QGridLayout())
        self.frame.layout().setContentsMargins(0, 0, 0, 0)

        self.toolbar = QToolBar()
        self.spacer = QWidget()
        self.spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
        self.copyAction = self.toolbar.addAction(QIcon(":/icons/clipboard"),
                                                 "Copy Text")
        self.label = QLabel()
        self.closeAction = QPushButton(QIcon(":/icons/cancel"), "Close", self)
        self.spaceraction = self.toolbar.insertWidget(None, self.spacer)
        self.labelaction = self.toolbar.insertWidget(self.spaceraction,
                                                     self.label)
        self.closeAction.pressed.connect(self.close)
        self.copyAction.triggered.connect(self.copy_text)
        self.layout().addWidget(self.frame)
        self.frame.layout().addWidget(self.toolbar)
        self.frame.layout().addWidget(self.view)
        self.frame.layout().addWidget(self.closeAction)

        self.effect = QGraphicsOpacityEffect()
        self.label.setGraphicsEffect(self.effect)
        self.anim = QPropertyAnimation(self.effect, "opacity".encode("utf-8"))
        self.anim.setDuration(2000)
        self.anim.setStartValue(1.0)
        self.anim.setEndValue(0.0)
        self.anim.setEasingCurve(QEasingCurve.OutQuad)

    def copy_text(self):
        self.label.setText("Copied to clipboard")
        text = self.view.page().mainFrame().toPlainText()
        QApplication.clipboard().setText(text)
        self.anim.stop()
        self.anim.start()

    def showHTML(self, template, level, **data):
        html = templates.render_tample(template, **data)
        self.view.setHtml(html, templates.baseurl)
class QgepPlotSVGWidget(QWidget):
    webView = None
    webPage = None
    frame = None
    profile = None
    verticalExaggeration = 10
    jsTranslator = QgepJsTranslator()

    # Signals emitted triggered by javascript actions
    reachClicked = pyqtSignal([str], name='reachClicked')
    reachMouseOver = pyqtSignal([str], name='reachMouseOver')
    reachMouseOut = pyqtSignal([str], name='reachMouseOut')
    reachPointClicked = pyqtSignal([str, str], name='reachPointClicked')
    reachPointMouseOver = pyqtSignal([str, str], name='reachPointMouseOver')
    reachPointMouseOut = pyqtSignal([str, str], name='reachPointMouseOut')
    specialStructureClicked = pyqtSignal([str], name='specialStructureClicked')
    specialStructureMouseOver = pyqtSignal([str],
                                           name='specialStructureMouseOver')
    specialStructureMouseOut = pyqtSignal([str],
                                          name='specialStructureMouseOut')

    # Signals emitted for javascript
    profileChanged = pyqtSignal([str], name='profileChanged')
    verticalExaggerationChanged = pyqtSignal(
        [int], name='verticalExaggerationChanged')

    def __init__(self,
                 parent,
                 network_analyzer: QgepGraphManager,
                 url: str = None):
        QWidget.__init__(self, parent)

        self.webView = QWebView()
        self.webView.setPage(QgepWebPage(self.webView))

        self.networkAnalyzer = network_analyzer

        settings = QSettings()

        layout = QVBoxLayout(self)
        if url is None:
            # Starting with QGIS 3.4, QWebView requires paths with / even on windows.
            default_url = plugin_root_path().replace(
                '\\', '/') + '/svgprofile/index.html'
            url = settings.value("/QGEP/SvgProfilePath", default_url)
            url = 'file:///' + url

        developer_mode = settings.value("/QGEP/DeveloperMode",
                                        False,
                                        type=bool)

        if developer_mode is True:
            self.webView.page().settings().setAttribute(
                QWebSettings.DeveloperExtrasEnabled, True)
        else:
            self.webView.setContextMenuPolicy(Qt.NoContextMenu)

        self.webView.load(QUrl(url))
        self.frame = self.webView.page().mainFrame()
        self.frame.javaScriptWindowObjectCleared.connect(self.initJs)

        layout.addWidget(self.webView)

    def setProfile(self, profile):
        self.profile = profile
        # Forward to javascript
        self.profileChanged.emit(profile.asJson())

    def initJs(self):
        self.frame.addToJavaScriptWindowObject("profileProxy", self)
        self.frame.addToJavaScriptWindowObject("i18n", self.jsTranslator)

    def changeVerticalExaggeration(self, val):
        self.verticalExaggeration = val
        self.verticalExaggerationChanged.emit(val)

    def printProfile(self):
        printer = QPrinter(QPrinter.HighResolution)
        printer.setOutputFormat(QPrinter.PdfFormat)
        printer.setPaperSize(QPrinter.A4)
        printer.setOrientation(QPrinter.Landscape)

        printpreviewdlg = QPrintPreviewDialog()
        printpreviewdlg.paintRequested.connect(self.printRequested)

        printpreviewdlg.exec_()

    @pyqtSlot(QPrinter)
    def printRequested(self, printer):
        self.webView.print_(printer)

    @pyqtSlot(str)
    def onReachClicked(self, obj_id):
        self.reachClicked.emit(obj_id)

    @pyqtSlot(str)
    def onReachMouseOver(self, obj_id):
        self.reachMouseOver.emit(obj_id)

    @pyqtSlot(str)
    def onReachMouseOut(self, obj_id):
        self.reachMouseOut.emit(obj_id)

    @pyqtSlot(str, str)
    def onReachPointClicked(self, obj_id, reach_obj_id):
        self.reachPointClicked.emit(obj_id, reach_obj_id)

    @pyqtSlot(str, str)
    def onReachPointMouseOver(self, obj_id, reach_obj_id):
        self.reachPointMouseOver.emit(obj_id, reach_obj_id)

    @pyqtSlot(str, str)
    def onReachPointMouseOut(self, obj_id, reach_obj_id):
        self.reachPointMouseOut.emit(obj_id, reach_obj_id)

    @pyqtSlot(str)
    def onSpecialStructureClicked(self, obj_id):
        self.specialStructureClicked.emit(obj_id)

    @pyqtSlot(str)
    def onSpecialStructureMouseOver(self, obj_id):
        self.specialStructureMouseOver.emit(obj_id)

    @pyqtSlot(str)
    def onSpecialStructureMouseOut(self, obj_id):
        self.specialStructureMouseOut.emit(obj_id)

    # Is called from the webView when it's been reloaded and wants to have the
    # profile information resent
    @pyqtSlot()
    def updateProfile(self):
        if self.profile:
            self.profileChanged.emit(self.profile.asJson())
            self.verticalExaggerationChanged.emit(self.verticalExaggeration)
    def show_current_state(self):
        """Setup the UI for QTextEdit to show the current state."""
        right_panel_heading = QLabel(tr('Status'))
        right_panel_heading.setFont(big_font)
        right_panel_heading.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.right_layout.addWidget(right_panel_heading)

        message = m.Message()
        if self.layer_mode == layer_mode_continuous:
            title = tr('Thresholds')
        else:
            title = tr('Value maps')

        message.add(m.Heading(title, **INFO_STYLE))

        for i in range(len(self.exposures)):
            message.add(m.Text(self.exposure_labels[i]))

            classification = self.get_classification(
                self.exposure_combo_boxes[i])
            if self.layer_mode == layer_mode_continuous:
                thresholds = self.thresholds.get(self.exposures[i]['key'])
                if not thresholds or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Minimum')))
                header.add(m.Cell(tr('Maximum')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    threshold = thresholds[classification['key']]['classes'][
                        the_class['key']]
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(threshold[0]))
                    row.add(m.Cell(threshold[1]))
                    table.add(row)
            else:
                value_maps = self.value_maps.get(self.exposures[i]['key'])
                if not value_maps or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Value')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    value_map = value_maps[classification['key']][
                        'classes'].get(the_class['key'], [])
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(', '.join([str(v) for v in value_map])))
                    table.add(row)
            message.add(table)

        # status_text_edit = QTextBrowser(None)
        status_text_edit = QWebView(None)
        status_text_edit.setSizePolicy(
            QSizePolicy.Ignored,
            QSizePolicy.Ignored)

        status_text_edit.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal,
            Qt.ScrollBarAlwaysOff)
        html_string = html_header() + message.to_html() + html_footer()
        status_text_edit.setHtml(html_string)
        self.right_layout.addWidget(status_text_edit)
class SearchDialog(QDialog):

    def __init__(self):
        super(SearchDialog, self).__init__(iface.mainWindow())
        self.initGui()
        self.mapstory = None

    def initGui(self):
        hlayout = QHBoxLayout()
        layout = QVBoxLayout()
        self.searchBox = QLineEdit()
        self.searchBox.returnPressed.connect(self.search)
        self.searchBox.setPlaceholderText("[Enter search string and press enter to search for maps]")
        hlayout.addWidget(self.searchBox)

        self.button = QToolButton()
        self.button.setText("Search")
        self.button.clicked.connect(self.search)
        self.button.adjustSize()
        self.searchBox.setFixedHeight(self.button.height())
        hlayout.addWidget(self.button)
        layout.addLayout(hlayout)

        w = QFrame()
        self.browser = QWebView()
        w.setStyleSheet("QFrame{border:1px solid rgb(0, 0, 0);}")
        innerlayout = QHBoxLayout()
        innerlayout.setSpacing(0)
        innerlayout.setMargin(0)
        innerlayout.addWidget(self.browser)
        w.setLayout(innerlayout)
        layout.addWidget(w)
        self.setLayout(layout)

        self.browser.page().setLinkDelegationPolicy(QWebPage.DelegateAllLinks)
        self.browser.settings().setUserStyleSheetUrl(QUrl("file://" + resourceFile("search.css").replace("\\", "/")))
        self.browser.linkClicked.connect(self.linkClicked)
        self.resize(600, 500)
        self.setWindowTitle("Search stories")

    def linkClicked(self, url):
        self.mapstory = url.path()
        self.close()

    def search(self):
        text = self.searchBox.text().strip()
        if text:
            try:
                r = execute(lambda: requests.get("http://mapstory.org/api/base/search", params={"type__in":"map", "limit":50, "q": text}))
                r.raise_for_status()
                mapstories = r.json()["objects"]
                if mapstories:
                    s = "<div><ul>"
                    for mapstory in mapstories:
                        link = "<a href='%s' class='button'>Open</a>" % (mapstory["id"])
                        s += "<li>%s <h3>%s</h3> %s <br> </li>" % (link, mapstory["title"], mapstory["abstract"])
                    s += "</ul></div>"
                else:
                    s = "<h2>No maps matching your search criteria were found.</h2>"
                self.browser.setHtml(s)
            except RequestException as e:
                    QMessageBox.warning(self, "Search",
                        u"There has been a problem performing the search:\n" + str(e.args[0]),
                        QMessageBox.Ok)
    def show_current_state(self):
        """Setup the UI for QTextEdit to show the current state."""
        right_panel_heading = QLabel(tr('Status'))
        right_panel_heading.setFont(big_font)
        right_panel_heading.setSizePolicy(
            QSizePolicy.Maximum, QSizePolicy.Maximum)
        self.right_layout.addWidget(right_panel_heading)

        message = m.Message()
        if self.layer_mode == layer_mode_continuous:
            title = tr('Thresholds')
        else:
            title = tr('Value maps')

        message.add(m.Heading(title, **INFO_STYLE))

        for i in range(len(self.exposures)):
            message.add(m.Text(self.exposure_labels[i]))

            classification = self.get_classification(
                self.exposure_combo_boxes[i])
            if self.layer_mode == layer_mode_continuous:
                thresholds = self.thresholds.get(self.exposures[i]['key'])
                if not thresholds or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Minimum')))
                header.add(m.Cell(tr('Maximum')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    threshold = thresholds[classification['key']]['classes'][
                        the_class['key']]
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(threshold[0]))
                    row.add(m.Cell(threshold[1]))
                    table.add(row)
            else:
                value_maps = self.value_maps.get(self.exposures[i]['key'])
                if not value_maps or not classification:
                    message.add(m.Paragraph(tr('No classifications set.')))
                    continue
                table = m.Table(
                    style_class='table table-condensed table-striped')
                header = m.Row()
                header.add(m.Cell(tr('Class name')))
                header.add(m.Cell(tr('Value')))
                table.add(header)
                classes = classification.get('classes')
                # Sort by value, put the lowest first
                classes = sorted(classes, key=lambda k: k['value'])
                for the_class in classes:
                    value_map = value_maps[classification['key']][
                        'classes'].get(the_class['key'], [])
                    row = m.Row()
                    row.add(m.Cell(the_class['name']))
                    row.add(m.Cell(', '.join([str(v) for v in value_map])))
                    table.add(row)
            message.add(table)

        # status_text_edit = QTextBrowser(None)
        status_text_edit = QWebView(None)
        status_text_edit.setSizePolicy(
            QSizePolicy.Ignored,
            QSizePolicy.Ignored)

        status_text_edit.page().mainFrame().setScrollBarPolicy(
            Qt.Horizontal,
            Qt.ScrollBarAlwaysOff)
        html_string = html_header() + message.to_html() + html_footer()
        status_text_edit.setHtml(html_string)
        self.right_layout.addWidget(status_text_edit)