Esempio n. 1
0
    def __init__(self, parent=None):
        super(DlgSettingsRegister, self).__init__(parent)
        self.setupUi(self)

        self.api = API()

        self.save.clicked.connect(self.btn_save)
        self.cancel.clicked.connect(self.btn_cancel)
Esempio n. 2
0
    def __init__(self, parent=None):
        """Constructor."""
        super(DlgSettingsUpdate, self).__init__(parent)
        self.setupUi(self)

        self.api = API()

        self.save.clicked.connect(self.btn_save)
        self.cancel.clicked.connect(self.btn_cancel)
Esempio n. 3
0
class DlgSettingsUpdate(QtGui.QDialog, Ui_DlgSettingsUpdate):
    def __init__(self, parent=None):
        """Constructor."""
        super(DlgSettingsUpdate, self).__init__(parent)
        self.setupUi(self)

        self.api = API()

        self.save.clicked.connect(self.btn_save)
        self.cancel.clicked.connect(self.btn_cancel)

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('LDMP', message)

    def btn_save(self):
        if not self.email.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your email address."),
                                       None)
        elif not self.name.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your name."), None)
        elif not self.organization.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your organization."),
                                       None)
        elif not self.country.currentText():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your country."), None)
        else:
            self.api.update_user(self.email.text(), self.name.text(),
                                 self.organization.text(),
                                 self.country.currentText())

            QtGui.QMessageBox.information(
                None, self.tr("Saved"),
                self.tr("Updated information for {}.").format(
                    self.email.text()), None)
            self.close()

    def btn_cancel(self):
        self.close()
Esempio n. 4
0
    def __init__(self, parent=None):
        super(DlgSettings, self).__init__(parent)

        self.api = API()

        self.settings = QSettings()

        self.setupUi(self)

        self.dlg_settingsregister = DlgSettingsRegister()
        self.dlg_settingsupdate = DlgSettingsUpdate()

        self.register_user.clicked.connect(self.btn_register)
        self.delete_user.clicked.connect(self.btn_delete)
        self.login.clicked.connect(self.btn_login)
        self.update_profile.clicked.connect(self.btn_update_profile)
        self.forgot_pwd.clicked.connect(self.btn_forgot_pwd)
        self.cancel.clicked.connect(self.btn_cancel)

        email = get_user_email()
        if email: self.email.setText(email)
        password = self.settings.value("LDMP/password", None)
        if password: self.password.setText(password)
Esempio n. 5
0
    def __init__(self, parent=None):
        """Constructor."""
        super(DlgJobs, self).__init__(parent)

        self.settings = QSettings()

        self.setupUi(self)

        self.api = API()

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QtGui.QSizePolicy.Minimum,
                               QtGui.QSizePolicy.Fixed)
        self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)

        self.refresh.clicked.connect(self.btn_refresh)
        self.download.clicked.connect(self.btn_download)

        # Only enable download button if a job is selected
        self.download.setEnabled(False)

        # Set a variable used to record the necessary window width to view all
        # columns
        self._full_width = None
Esempio n. 6
0
class DlgSettingsRegister(QtGui.QDialog, Ui_DlgSettingsRegister):
    def __init__(self, parent=None):
        super(DlgSettingsRegister, self).__init__(parent)
        self.setupUi(self)

        self.api = API()

        self.save.clicked.connect(self.btn_save)
        self.cancel.clicked.connect(self.btn_cancel)

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('LDMP', message)

    def btn_save(self):
        if not self.email.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your email address."),
                                       None)
        elif not self.name.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your name."), None)
        elif not self.organization.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your organization."),
                                       None)
        elif not self.country.currentText():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your country."), None)
        else:
            resp = self.api.register(self.email.text(), self.name.text(),
                                     self.organization.text(),
                                     self.country.currentText())
            if resp:
                mb.pushMessage(
                    "Success",
                    "User {} registered. Your password has been emailed to you."
                    .format(self.email.text()),
                    level=0)
                self.close()

    def btn_cancel(self):
        self.close()
Esempio n. 7
0
class DlgJobs(QtGui.QDialog, Ui_DlgJobs):
    def __init__(self, parent=None):
        """Constructor."""
        super(DlgJobs, self).__init__(parent)

        self.settings = QSettings()

        self.setupUi(self)

        self.api = API()

        self.bar = QgsMessageBar()
        self.bar.setSizePolicy(QtGui.QSizePolicy.Minimum,
                               QtGui.QSizePolicy.Fixed)
        self.layout().addWidget(self.bar, 0, 0, Qt.AlignTop)

        self.refresh.clicked.connect(self.btn_refresh)
        self.download.clicked.connect(self.btn_download)

        # Only enable download button if a job is selected
        self.download.setEnabled(False)

        # Set a variable used to record the necessary window width to view all
        # columns
        self._full_width = None

    def resizeWindowToColumns(self):
        if not self._full_width:
            margins = self.layout().contentsMargins()
            self._full_width = margins.left() + margins.right() + \
                self.jobs_view.frameWidth() * 2 + \
                self.jobs_view.verticalHeader().width() + \
                self.jobs_view.horizontalHeader().length() + \
                self.jobs_view.style().pixelMetric(QtGui.QStyle.PM_ScrollBarExtent)
        self.resize(self._full_width, self.height())

    def selection_changed(self):
        if not self.jobs_view.selectedIndexes():
            self.download.setEnabled(False)
        else:
            rows = list(
                set(index.row() for index in self.jobs_view.selectedIndexes()))
            for row in rows:
                # Don't set button to enabled if any of the tasks aren't yet
                # finished
                if self.jobs[row]['status'] != 'FINISHED':
                    self.download.setEnabled(False)
                    return
            self.download.setEnabled(True)

    def btn_refresh(self):
        # TODO: Handle loss of internet and connection error on button refresh
        # progressMessageBar = mb.createMessage("Contacting server to update job list.")
        # progress = QtGui.QProgressBar()
        # progress.setRange(0, 0)
        # progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        # progressMessageBar.layout().addWidget(progress)
        # self.bar.pushWidget(progressMessageBar, iface.messageBar().INFO)

        self.jobs = self.api.get_execution(user=get_user_email())

        #mb.popWidget(progressMessageBar)

        if self.jobs:
            # Add script names and descriptions to jobs list
            self.scripts = get_scripts(self.api)
            for job in self.jobs:
                # self.jobs will have prettified data for usage in table, so
                # save a backup of the original data under key 'original'
                job['raw'] = job.copy()

                script = job.get('script_id', None)
                if script:
                    job['script_name'] = self.scripts[job['script_id']]['name']
                    job['script_description'] = self.scripts[
                        job['script_id']]['description']
                else:
                    # Handle case of scripts that have been removed or that are
                    # no longer supported
                    job['script_name'] = 'Script not found'
                    job['script_description'] = 'Script not found'

            # Pretty print dates and pull the metadata sent as input params
            for job in self.jobs:
                job['start_date'] = datetime.strftime(job['start_date'],
                                                      '%Y/%m/%d (%H:%M)')
                job['end_date'] = datetime.strftime(job['end_date'],
                                                    '%Y/%m/%d (%H:%M)')
                job['task_name'] = job['params'].get('task_name', '')
                job['task_notes'] = job['params'].get('task_notes', '')
                job['params'] = job['params']

            table_model = JobsTableModel(self.jobs, self)
            proxy_model = QtGui.QSortFilterProxyModel()
            proxy_model.setSourceModel(table_model)
            self.jobs_view.setModel(proxy_model)

            # Add "Notes" buttons in cell
            for row in range(0, len(self.jobs)):
                btn = QtGui.QPushButton("Details")
                btn.clicked.connect(self.btn_details)
                self.jobs_view.setIndexWidget(proxy_model.index(row, 5), btn)

            self.jobs_view.horizontalHeader().setResizeMode(
                QtGui.QHeaderView.ResizeToContents)
            self.jobs_view.setSelectionBehavior(
                QtGui.QAbstractItemView.SelectRows)
            self.jobs_view.selectionModel().selectionChanged.connect(
                self.selection_changed)

            self.resizeWindowToColumns()

            return True

        else:
            return False

    def btn_details(self):
        button = self.sender()
        index = self.jobs_view.indexAt(button.pos())

        details_dlg = DlgJobsDetails()

        job = self.jobs[index.row()]

        details_dlg.task_name.setText(job.get('task_name', ''))
        details_dlg.task_status.setText(job.get('status', ''))
        details_dlg.comments.setText(job.get('task_notes', ''))
        details_dlg.input.setText(
            json.dumps(job.get('params', ''), indent=4, sort_keys=True))
        details_dlg.output.setText(
            json.dumps(job.get('results', ''), indent=4, sort_keys=True))

        details_dlg.show()
        details_dlg.exec_()

    def btn_download(self):
        while True:
            download_dir = QtGui.QFileDialog.getExistingDirectory(
                self, self.tr("Directory to save files"),
                self.settings.value("LDMP/download_dir", None),
                QtGui.QFileDialog.ShowDirsOnly)
            if download_dir:
                if os.access(download_dir, os.W_OK):
                    self.settings.setValue("LDMP/download_dir", download_dir)
                    break
                else:
                    QtGui.QMessageBox.critical(
                        None, self.tr("Error"),
                        self.tr(
                            "Cannot write to {}. Choose a different folder.".
                            format(download_dir), None))
            else:
                return False

        log("Downloading results to {}".format(download_dir))

        rows = list(
            set(index.row() for index in self.jobs_view.selectedIndexes()))
        for row in rows:
            job = self.jobs[row]
            log("Processing job {}".format(job))
            if job['results'].get('type') == 'productivity_trajectory':
                download_prod_traj(job, download_dir)
            elif job['results'].get('type') == 'productivity_state':
                download_prod_state(job, download_dir)
            elif job['results'].get('type') == 'productivity_performance':
                download_prod_perf(job, download_dir)
            elif job['results'].get('type') == 'land_cover':
                download_land_cover(job, download_dir)
            else:
                raise ValueError(
                    "Unrecognized result type in download results: {}".format(
                        dataset['dataset']))
        self.close()
Esempio n. 8
0
class DlgSettings(QtGui.QDialog, UiDialog):
    def __init__(self, parent=None):
        super(DlgSettings, self).__init__(parent)

        self.api = API()

        self.settings = QSettings()

        self.setupUi(self)

        self.dlg_settingsregister = DlgSettingsRegister()
        self.dlg_settingsupdate = DlgSettingsUpdate()

        self.register_user.clicked.connect(self.btn_register)
        self.delete_user.clicked.connect(self.btn_delete)
        self.login.clicked.connect(self.btn_login)
        self.update_profile.clicked.connect(self.btn_update_profile)
        self.forgot_pwd.clicked.connect(self.btn_forgot_pwd)
        self.cancel.clicked.connect(self.btn_cancel)

        email = get_user_email()
        if email: self.email.setText(email)
        password = self.settings.value("LDMP/password", None)
        if password: self.password.setText(password)

    # noinspection PyMethodMayBeStatic
    def tr(self, message):
        # noinspection PyTypeChecker,PyArgumentList,PyCallByClass
        return QCoreApplication.translate('LDMP', message)

    def btn_update_profile(self):
        if not self.email.text():
            QtGui.QMessageBox.critical(
                None, self.tr("Error"),
                self.tr("Enter an email address to update."), None)
        elif not self.password.text():
            QtGui.QMessageBox.critical(
                None, self.tr("Error"),
                self.tr("Enter your password to update your user details."),
                None)
        else:
            user = self.api.get_user(self.email.text())

            if not user:
                return

            self.dlg_settingsupdate.email.setText(user['email'])
            self.dlg_settingsupdate.password.setText(
                self.settings.value("LDMP/password"))
            self.dlg_settingsupdate.name.setText(user['name'])
            self.dlg_settingsupdate.organization.setText(user['institution'])

            # Add countries, and set index to currently chosen country
            admin_0 = json.loads(QSettings().value('LDMP/admin_0', None))
            self.dlg_settingsupdate.country.addItems(sorted(admin_0.keys()))
            index = self.dlg_settingsupdate.country.findText(user['country'])
            if index != -1:
                self.dlg_settingsupdate.country.setCurrentIndex(index)

            result = self.dlg_settingsupdate.exec_()

            if result:
                self.close()

    def btn_register(self):
        admin_0 = json.loads(QSettings().value('LDMP/admin_0', None))
        self.dlg_settingsregister.country.addItems(sorted(admin_0.keys()))
        result = self.dlg_settingsregister.exec_()
        # See if OK was pressed
        if result:
            pass

    def btn_delete(self):
        QtGui.QMessageBox.critical(
            None, self.tr("Error"),
            self.tr("Delete user functionality coming soon!"), None)
        pass

    def btn_cancel(self):
        self.close()

    def btn_forgot_pwd(self):
        # Verify there is input for email
        if not self.email.text():
            QtGui.QMessageBox.critical(
                None, self.tr("Error"),
                self.tr("Enter your email address to reset your password."),
                None)
        resp = self.api.recover_pwd(self.email.text())
        if resp != None:
            mb.pushMessage(
                "Success",
                self.
                tr("The password has been reset for {}. Check your email for the new password."
                   ).format(self.email.text()),
                level=0)
            self.close()

    def btn_login(self):
        if not self.email.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your email address."),
                                       None)
            self.close()
        elif not self.email.text():
            QtGui.QMessageBox.critical(None, self.tr("Error"),
                                       self.tr("Enter your password."), None)
            self.close()
        resp = login(self.email.text(), self.password.text())
        if resp:
            mb.pushMessage("Success",
                           "Logged in to the LDMP server as {}.".format(
                               self.email.text()),
                           level=0)
            self.close()