Exemple #1
0
    def downloadBtnClicked(self):
        # TODO: disable search button till the downloads finish or stopped manually
        self.ui.downloadBtn.setText("Please wait...")
        self.ui.downloadBtn.setEnabled(False)
        QtGui.QApplication.processEvents()
        selected_range = self.ui.chapterTable.selectedRanges()
        selected_range = [i for r in selected_range
                          for i in range(r.topRow(), r.bottomRow() + 1)]
        # "selected_range" is a list of positions in table
        print "{} items selected".format(len(selected_range))
        for i in selected_range:
            try:
                index = i
                file = DownloadFile(self.course.getMp4UrlMirror(index),
                                    self.get_file_path(index),
                                    index,
                                    lambda index, size, tot, i=index:
                                        self.updateProgress.emit(
                                            index, size, tot, i))
                pg = QProgressBar()
                pg.setRange(0, 100)
                pg.setValue(0)
                self.ui.chapterTable.setCellWidget(i, 1, pg)
                self.downloadQueue.addToQueue(file)
                print file.fileName + " Added to download queue"
            except Exception as e:
                pass

        self.ui.downloadBtn.setText("Start Download")
        self.ui.downloadBtn.setEnabled(True)
        QtGui.QApplication.processEvents()
Exemple #2
0
 def synccomplete(self):
     try:
         self.iface.messageBar().popWidget(self.syncwidget)
     except RuntimeError:
         pass
     
     stylesheet = ("QgsMessageBar { background-color: rgba(239, 255, 233); border: 0px solid #b9cfe4; } "
                  "QLabel,QTextEdit { color: #057f35; } ")
     
     closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
     closebutton.setVisible(True)
     closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
     self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Complete", QIcon(":/icons/syncdone"))
     button = QPushButton(self.syncwidget)
     button.setCheckable(True)
     button.setChecked(self.report.isVisible())
     button.setText("Sync Report")
     button.setIcon(QIcon(":/icons/syncinfo"))
     button.toggled.connect(functools.partial(self.report.setVisible))      
     pro = QProgressBar()
     pro.setMaximum(100)
     pro.setValue(100)
     self.syncwidget.layout().addWidget(pro)      
     self.syncwidget.layout().addWidget(button)
     self.iface.messageBar().pushWidget(self.syncwidget)
     self.iface.messageBar().setStyleSheet(stylesheet)
     self.iface.mapCanvas().refresh()
Exemple #3
0
class ProgressDialog(QDialog):
    def __init__(self, parent):
        QDialog.__init__(self, parent)
        self.resize(300, 75)
        self.setWindowTitle("Updating")
        self.vw = QWidget(self)
        self.vl = QVBoxLayout(self.vw)
        self.vl.setMargin(10)
        self.label = QLabel(self.vw)
        self.label.setText("<b>Downloading:</b> library.zip")
        self.vl.addWidget(self.label)
        self.horizontalLayoutWidget = QWidget()
        self.horizontalLayout = QHBoxLayout(self.horizontalLayoutWidget)
        self.horizontalLayout.setMargin(0)
        self.progressbar = QProgressBar(self.horizontalLayoutWidget)
        self.progressbar.setFixedWidth(260)
        self.progressbar.setMinimum(0)
        self.progressbar.setMaximum(100)
        self.stopButton = QPushButton(self.horizontalLayoutWidget)
        self.stopButton.setFlat(True)
        self.stopButton.setIcon(Icons.stop)
        self.stopButton.setFixedSize(16,16)
        self.horizontalLayout.addWidget(self.progressbar)
        self.horizontalLayout.addWidget(self.stopButton)
        self.vl.addWidget(self.horizontalLayoutWidget)
        self.stopButton.clicked.connect(self.forceStop)
        
    def setValue(self,val):
        self.progressbar.setValue(val)
    def forceStop(self):
        self.emit(SIGNAL("forceStop"))
Exemple #4
0
class progressBar:
    def __init__(self, parent, msg='', steps=0):
        '''
        progressBar class instatiation method. It creates a QgsMessageBar with provided msg and a working QProgressBar
        :param parent:
        :param msg: string
        '''
        self.iface = parent.iface
        widget = self.iface.messageBar().createMessage("fdtm plugin:", msg)
        self.progressBar = QProgressBar()
        self.progressBar.setRange(0, steps)  #(1,steps)
        self.progressBar.setValue(0)
        self.progressBar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        widget.layout().addWidget(self.progressBar)
        qApp.processEvents()
        self.iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, 50)
        qApp.processEvents()

    def setStep(self, step):
        self.progressBar.setValue(step)
        qApp.processEvents()

    def stop(self, msg=''):
        '''
        the progressbar is stopped with a succes message
        :param msg: string
        :return:
        '''
        self.iface.messageBar().clearWidgets()
        message = self.iface.messageBar().createMessage("fdtm plugin:", msg)
        self.iface.messageBar().pushWidget(message, QgsMessageBar.SUCCESS, 3)
Exemple #5
0
class WideSpanVNAWidget(VNAWidget):
    def __init__(self):
        super(WideSpanVNAWidget, self).__init__()
        self.start_spin = SpinBox(value=3e9)
        self.form_layout.addRow("Start Frequency", self.start_spin)
        self.stop_spin = SpinBox(value=9e9)
        self.form_layout.addRow("Stop Frequency", self.stop_spin)
        self.step_spin = SpinBox(value=1e6)
        self.form_layout.addRow("Delta Frequency", self.step_spin)
        self.progress_bar = QProgressBar()
        self.form_layout.addRow(self.progress_bar)

    def grab_trace(self):
        vna = self.get_vna()
        n_points_per_trace = vna.get_points()
        start = self.start_spin.value()
        stop = self.stop_spin.value()
        step = self.step_spin.value()
        span = stop - start
        n_traces = int(ceil(span / (step * n_points_per_trace)))
        trace_size = span / n_traces
        trace_starts = [start + i * trace_size for i in range(n_traces)]
        trace_ends = [start + (i + 1) * trace_size for i in range(n_traces)]
        self.freqs = []
        self.mags = []
        for i, (start_f, stop_f) in enumerate(zip(trace_starts, trace_ends)):
            self.progress_bar.setValue(int((100.0 * (1 + i)) / n_traces))
            vna.set_start_freq(start_f)
            vna.set_stop_freq(stop_f)
            self.freqs.extend(vna.do_get_xaxis())
            m, _ = vna.do_get_data(opc=True)
            self.mags.extend(m)
            self.replot()
            QApplication.instance().processEvents()
        self.progress_bar.setValue(0)
Exemple #6
0
    def on_downloaded(self):

        widget = self.iface.messageBar().createMessage(
            u"Géofoncier", u"Téléchargement du RFU.")

        progress_bar = QProgressBar()
        progress_bar.setMinimum(0)
        progress_bar.setMaximum(2)
        widget.layout().addWidget(progress_bar)

        self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING)
        progress_bar.setValue(1)

        # https://pro.geofoncier.fr/index.php?&centre=-196406,5983255&context=metropole
        url = self.permalinkLineEdit.text()
        if not url:
            return self.abort_action(msg=u"Veuillez renseigner le permalien.")
        self.url = url

        try:
            self.download(self.url)
        except Exception as e:
            return self.abort_action(msg=e.message)

        progress_bar.setValue(2)
        self.iface.messageBar().clearWidgets()

        return
Exemple #7
0
class ProgressView(QWidget):
    def __init__(self, parent=None):
        super(ProgressView, self).__init__(parent)

        self._progressBar = QProgressBar()

        layout = QVBoxLayout(self)
        layout.addWidget(self._progressBar)

    def setRunner(self, runner):
        self.show()
        self._progressBar.setMaximum(0)
        runner.progress.connect(self._showProgress)
        runner.done.connect(self.hide)

    def _showProgress(self, dct):
        step = dct['step']
        if step in ('install', 'remove'):
            self._progressBar.setMaximum(100)
            self._progressBar.setValue(dct['percent'])
            if step == 'install':
                self._progressBar.setFormat(i18n('Installing... %p%'))
            else:
                self._progressBar.setFormat(i18n('Removing... %p%'))
        elif step == 'acquire':
            fetched = dct['fetched_bytes']
            total = dct['total_bytes']
            self._progressBar.setMaximum(total)
            self._progressBar.setValue(fetched)
            locale = KGlobal.locale()
            self._progressBar.setFormat(i18n('Downloading... %1 / %2',
                                             locale.formatByteSize(fetched),
                                             locale.formatByteSize(total)
                                             ))
    def on_downloaded(self):

        widget = self.iface.messageBar().createMessage(u"Géofoncier", u"Téléchargement du RFU.")

        progress_bar = QProgressBar()
        progress_bar.setMinimum(0)
        progress_bar.setMaximum(2)
        widget.layout().addWidget(progress_bar)

        self.iface.messageBar().pushWidget(widget, QgsMessageBar.WARNING)
        progress_bar.setValue(1)

        # https://pro.geofoncier.fr/index.php?&centre=-196406,5983255&context=metropole
        url = self.permalinkLineEdit.text()
        if not url:
            return self.abort_action(msg=u"Veuillez renseigner le permalien.")
        self.url = url

        try:
            self.download(self.url)
        except Exception as e:
            return self.abort_action(msg=e.message)

        progress_bar.setValue(2)
        self.iface.messageBar().clearWidgets()

        return
Exemple #9
0
class ProgressWidget(QgsMessageBar):
    def __init__(self, min, max, message, parent=None, timeout = 1.5):
        """
        Constructs a progress widget
        """
        super(self.__class__, self).__init__(parent)
        self.min = min
        self.max = max
        sizePolicy = QSizePolicy(QSizePolicy.MinimumExpanding, QSizePolicy.Fixed)
        if parent:
            self.setMinimumSize(parent.width(),40)
        else:
            self.setMinimumSize(766,40)
        self.setSizePolicy(sizePolicy)
        self.progressBar = QProgressBar()
        self.progressBar.setMinimum(min)
        self.progressBar.setMaximum(max)
        self.msgBarItem = QgsMessageBarItem(self.tr("INFO: "), message, self.progressBar, level=QgsMessageBar.INFO, duration=timeout)
        self.pushWidget(self.msgBarItem)
    
    def initBar(self):
        """
        Initializes the progress bar
        """
        self.progressBar.setValue(0)
    
    def step(self):
        """
        Increments the progress bar
        """
        value = self.progressBar.value() + 1
        self.progressBar.setValue(value)
        if value == self.max:
            time.sleep(1)
            self.close()
Exemple #10
0
class Popup(QDialog):
    def __init__(self, widget, parent = None):
        QDialog.__init__(self, parent)
        self.setModal(True)
        self.setWindowTitle("Plot save progress")

        layout = QVBoxLayout()
        layout.addWidget(widget)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(1)
        self.progress_bar.setValue(0)
        layout.addWidget(self.progress_bar)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self)
        layout.addWidget(buttons)
        
        self.setLayout(layout)

        self.connect(buttons, SIGNAL('accepted()'), self.accept)

        self.ok_button = buttons.button(QDialogButtonBox.Ok)
        self.ok_button.setEnabled(False)

    def closeEvent(self, event):
        """Ignore clicking of the x in the top right corner"""
        event.ignore()

    def keyPressEvent(self, event):
        """Ignore ESC keystrokes"""
        if not event.key() == Qt.Key_Escape:
            QDialog.keyPressEvent(self, event)
Exemple #11
0
class ReportExportProgressItems(QObject):
    def __init__(self):
        QObject.__init__(self)
        self.eventCount = ReportManager.EventExportItems
        self.eventFinish = [
            ReportManager.EventExportCategoryFinish,
            ReportPage.EventExportFinish, ReportPageFragment.EventWriteFinish,
            ReportPageFragment.EventWriteElementFinish
        ]
        self.label = QLabel(self.tr("Extracting report"))
        self.bar = QProgressBar()
        self.bar.setFormat(" %v/%m (%p%)")
        self.reset()

    def reset(self):
        self.count = 0
        self.current = 0

    def event(self, event):
        if event.type == self.eventCount:
            self.count = event.value.value()
            self.bar.setValue(0)
            self.bar.setMaximum(self.count)
        if event.type in self.eventFinish:
            self.current += 1
            self.bar.setValue(self.current)
Exemple #12
0
 def synccomplete(self):
     try:
         self.iface.messageBar().popWidget(self.syncwidget)
     except RuntimeError:
         pass
     
     stylesheet = ("QgsMessageBar { background-color: rgba(239, 255, 233); border: 0px solid #b9cfe4; } "
                  "QLabel,QTextEdit { color: #057f35; } ")
     
     closebutton = self.iface.messageBar().findChildren(QToolButton)[0]
     closebutton.setVisible(True)
     closebutton.clicked.connect(functools.partial(self.report.setVisible, False))
     self.syncwidget = self.iface.messageBar().createMessage("Syncing", "Sync Complete", QIcon(":/icons/syncdone"))
     button = QPushButton(self.syncwidget)
     button.setCheckable(True)
     button.setChecked(self.report.isVisible())
     button.setText("Sync Report")
     button.setIcon(QIcon(":/icons/syncinfo"))
     button.toggled.connect(functools.partial(self.report.setVisible))      
     pro = QProgressBar()
     pro.setMaximum(100)
     pro.setValue(100)
     self.syncwidget.layout().addWidget(pro)      
     self.syncwidget.layout().addWidget(button)
     self.iface.messageBar().pushWidget(self.syncwidget)
     self.iface.messageBar().setStyleSheet(stylesheet)
     self.iface.mapCanvas().refresh()
    def _createTrackProgress(self, parent, track):

        w = QWidget(parent)
        l = QVBoxLayout(w)


        p = QProgressBar(w)
        p.setRange(0, 100)
        p.setValue(track['progress'])
        w.progress = p

        label = QLabel(w)
        label.setContentsMargins(5, 2, 5, 2)
        label.setOpenExternalLinks(True)
        label.setWordWrap(True)

        if track['name'] is not None:
            label.setText(track['name'])
        elif track['error']:
            label.setText('<font color="red">%s</font>' % track['error'])
            p.setValue(100)

        w.label = label


        l.addWidget(label)
        l.addWidget(p)

        w.setLayout(l)

        return w
Exemple #14
0
class ReportExportProgress(QObject):
    def __init__(self, name, eventCount, eventStart, eventFinish, child=None):
        QObject.__init__(self)
        self.name = name
        self.eventCount = eventCount
        self.eventStart = eventStart
        self.eventFinish = eventFinish
        self.child = child
        self.label = QLabel()
        self.label.setWordWrap(True)
        self.bar = QProgressBar()
        self.bar.setFormat(" %v/%m (%p%)")
        self.reset()

    def reset(self):
        self.title = ""
        self.current = 0
        self.count = 0

    def event(self, event):
        if event.type == self.eventStart:
            self.title = event.value.value()
            if self.child:
                self.child.reset()
        if event.type == self.eventFinish:
            self.current += 1
            self.bar.setValue(self.current)
        if event.type == self.eventCount:
            self.count = event.value.value()
            self.bar.setValue(0)
            self.bar.setMaximum(self.count)
        self.label.setText(
            self.tr("Extraction ") + self.name + " : " + str(self.title))
class ExerciseUI(QGroupBox):

  def __init__(self, exercise):
    super(ExerciseUI, self).__init__()
    self.exercise = exercise
    self.initUI()

  def initUI(self):
    self.setTitle(self.exercise.label)
    
    self.level = QLabel(QString('Lvl. %d' % self.exercise.level))

    self.progressbar = QProgressBar()
    self.progressbar.setMinimum(0)
    self.progressbar.setMaximum(100)
    self.progressbar.setValue(self.exercise.progress)

    grid = QGridLayout()
    grid.addWidget(self.level, 0, 0)
    grid.addWidget(self.progressbar, 0, 1, 1, 9)
    for (index, step) in enumerate(self.exercise.steps):
      btn = QPushButton(QString('+') + QString.number(step))
      grid.addWidget(btn, 1, index)
      btn.clicked.connect(self.buttonClicked)

    self.setLayout(grid)

  def buttonClicked(self):
    sender = self.sender()
    step = int(str(sender.text()).lstrip('+'))
    self.exercise.add(step)
    self.level.setText(QString('Lvl. %d' % self.exercise.level))
    self.progressbar.setValue(self.exercise.progress)
Exemple #16
0
    def setupCommandGUI(self, commands):
        for name, node in sorted(commands.items(), key=natural_keys):
            row = self.ui.gridLayout.rowCount() + 1

            label = QLabel(self.ui.groupBox)

            if not node.category:
                label.setText(('      ' * node.level) +
                              node.name.replace('___', ' '))
            else:
                label.setText(('&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;' *
                               node.level) + '<b>' +
                              node.name.replace('___', ' ') + '</b>')
            label.setObjectName('lableCommand_' + node.name)

            if not node.category:
                buttonStart = QPushButton(self.ui.groupBox)
                buttonStart.setText('Start')
                buttonStart.setObjectName('pushButtonCommand_' + node.name +
                                          '_start')
                buttonStart.clicked.connect(partial(self.onStart, name))

                buttonStop = QPushButton(self.ui.groupBox)
                buttonStop.setText('Stop')
                buttonStop.setObjectName('pushButtonCommand_' + node.name +
                                         '_stop')
                buttonStop.clicked.connect(partial(self.onStop, name))

                buttonRestart = QPushButton(self.ui.groupBox)
                buttonRestart.setText('Restart')
                buttonRestart.setObjectName('pushButtonCommand_' + node.name +
                                            '_restart')
                buttonRestart.clicked.connect(partial(self.onRestart, name))

                progressBar = None
                if node.name in self.progressTopics:
                    progressBar = QProgressBar(self.ui.groupBox)
                    progressBar.setObjectName('progressBarCommand_' +
                                              node.name)
                    progressBar.setValue(0)
                    progressBar.setMaximum(100)
                    progressBar.setMaximumWidth(300)

#                 if node.level == 0 or (node.level == 1 and node.parent.category):
#                     buttonStart.setEnabled(True)
#                     buttonStop.setEnabled(True)
#                     buttonRestart.setEnabled(True)
#                 else:
#                     buttonStart.setEnabled(False)
#                     buttonStop.setEnabled(False)
#                     buttonRestart.setEnabled(False)

                self.ui.gridLayout.addWidget(buttonStart, row, 1)
                self.ui.gridLayout.addWidget(buttonStop, row, 2)
                self.ui.gridLayout.addWidget(buttonRestart, row, 3)
                if not progressBar is None:
                    self.ui.gridLayout.addWidget(progressBar, row, 4)

            self.ui.gridLayout.addWidget(label, row, 0)
            self.setupCommandGUI(node.childs)
Exemple #17
0
class Popup(QDialog):
    def __init__(self, widget, parent = None):
        QDialog.__init__(self, parent)
        self.setModal(True)
        self.setWindowTitle("Plot save progress")

        layout = QVBoxLayout()
        layout.addWidget(widget)

        self.progress_bar = QProgressBar()
        self.progress_bar.setMinimum(0)
        self.progress_bar.setMaximum(1)
        self.progress_bar.setValue(0)
        layout.addWidget(self.progress_bar)

        buttons = QDialogButtonBox(QDialogButtonBox.Ok, Qt.Horizontal, self)
        layout.addWidget(buttons)
        
        self.setLayout(layout)

        self.connect(buttons, SIGNAL('accepted()'), self.accept)

        self.ok_button = buttons.button(QDialogButtonBox.Ok)
        self.ok_button.setEnabled(False)

    def closeEvent(self, event):
        """Ignore clicking of the x in the top right corner"""
        event.ignore()

    def keyPressEvent(self, event):
        """Ignore ESC keystrokes"""
        if not event.key() == Qt.Key_Escape:
            QDialog.keyPressEvent(self, event)
Exemple #18
0
class SeekOverlay(Overlay):
   def __init__(self, keyPressHandler, parent = None):
      Overlay.__init__(self, keyPressHandler, parent)
      
      self.setupUI()
      
      
   def setupUI(self):
      self.layout = QHBoxLayout(self)
      
      self.timeBar = QProgressBar()
      self.layout.addWidget(self.timeBar)
      
      
   def resizeEvent(self, event):
      textHeight = event.size().height() * .4
      self.timeBar.setStyleSheet('QProgressBar {font-size: %dpt;}' % textHeight)
      
      
   def setTime(self, current, total):
      current = int(current)
      total = int(total)
      self.timeBar.setMaximum(total)
      self.timeBar.setValue(current)
      self.timeBar.setFormat(MPlayer.formatTime(current) + '/' + MPlayer.formatTime(total))
Exemple #19
0
 def setValue(self, p_int):
     QProgressBar.setValue(self, p_int)
     if p_int > 70:
         self.change_color('rgb(76, 175, 80)')  # Green
     elif 70 >= p_int > 50:
         self.change_color('rgb(255, 193, 7)')  # Yellow
     elif p_int <= 50:
         self.change_color('rgb(244, 67, 54)')  # Red
class TestWindow(QWidget):
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setWindowTitle("LivePlot Example Runner")
        layout = QHBoxLayout(self)
        button_layout = QVBoxLayout()
        time_layout = QHBoxLayout()
        time_spin = QSpinBox()
        self.timer = QTimer()
        time_spin.valueChanged.connect(self.timer.setInterval)
        self.timer.timeout.connect(self.iterate)
        self.progress_bar = QProgressBar()
        time_spin.setValue(50)
        time_spin.setRange(0, 1000)
        time_layout.addWidget(QLabel("Sleep Time (ms)"))
        time_layout.addWidget(time_spin)
        button_layout.addLayout(time_layout)

        tests = {
            'plot y': test_plot_y,
            'plot xy': test_plot_xy,
            'plot parametric': test_plot_xy_parametric,
            'plot z': test_plot_z,
            'plot huge': test_plot_huge,
            'append y': test_append_y,
            'append xy': test_append_xy,
            'append z': test_append_z,
            'label': test_label,
        }
        fn_text_widget = QPlainTextEdit()
        fn_text_widget.setMinimumWidth(500)

        def make_set_iterator(iter):
            def set_iterator():
                fn_text_widget.setPlainText(inspect.getsource(iter))
                QApplication.instance().processEvents()
                self.iterator = iter()
                self.timer.start()
            return set_iterator

        for name, iter in tests.items():
            button = QPushButton(name)
            button.clicked.connect(make_set_iterator(iter))
            button_layout.addWidget(button)

        layout.addLayout(button_layout)
        text_layout = QVBoxLayout()
        text_layout.addWidget(fn_text_widget)
        text_layout.addWidget(self.progress_bar)
        layout.addLayout(text_layout)

    def iterate(self):
        try:
            self.iterator.next()
            self.progress_bar.setValue(self.progress_bar.value() + 1)
        except StopIteration:
            self.timer.stop()
            self.progress_bar.setValue(0)
Exemple #21
0
class TestWindow(QWidget):
    def __init__(self):
        super(TestWindow, self).__init__()
        self.setWindowTitle("LivePlot Example Runner")
        layout = QHBoxLayout(self)
        button_layout = QVBoxLayout()
        time_layout = QHBoxLayout()
        time_spin = QSpinBox()
        self.timer = QTimer()
        time_spin.valueChanged.connect(self.timer.setInterval)
        self.timer.timeout.connect(self.iterate)
        self.progress_bar = QProgressBar()
        time_spin.setValue(50)
        time_spin.setRange(0, 1000)
        time_layout.addWidget(QLabel("Sleep Time (ms)"))
        time_layout.addWidget(time_spin)
        button_layout.addLayout(time_layout)

        tests = {
            'plot y': test_plot_y,
            'plot xy': test_plot_xy,
            'plot parametric': test_plot_xy_parametric,
            'plot z': test_plot_z,
            'plot huge': test_plot_huge,
            'append y': test_append_y,
            'append xy': test_append_xy,
            'append z': test_append_z,
        }
        fn_text_widget = QPlainTextEdit()
        fn_text_widget.setMinimumWidth(500)

        def make_set_iterator(iter):
            def set_iterator():
                fn_text_widget.setPlainText(inspect.getsource(iter))
                QApplication.instance().processEvents()
                self.iterator = iter()
                self.timer.start()

            return set_iterator

        for name, iter in tests.items():
            button = QPushButton(name)
            button.clicked.connect(make_set_iterator(iter))
            button_layout.addWidget(button)

        layout.addLayout(button_layout)
        text_layout = QVBoxLayout()
        text_layout.addWidget(fn_text_widget)
        text_layout.addWidget(self.progress_bar)
        layout.addLayout(text_layout)

    def iterate(self):
        try:
            self.iterator.next()
            self.progress_bar.setValue(self.progress_bar.value() + 1)
        except StopIteration:
            self.timer.stop()
            self.progress_bar.setValue(0)
Exemple #22
0
    def executar(self):

        progressMessageBar = self.iface.messageBar().createMessage(
            u'ECO Downloader',
            u' Baixando Dados... Isso poderá levar alguns minutos.')
        progress = QProgressBar()
        progress.setMaximum(len(self.estacoes))
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar,
                                           self.iface.messageBar().INFO)

        opcao = self.opcao

        if opcao == 1:
            post_data = {'cboTipoReg': '10'}  # para chuvas

        elif opcao == 2:
            post_data = {'cboTipoReg': '8'}  # para cotas

        elif opcao == 3:
            post_data = {'cboTipoReg': '9'}  # para vazões

        elif opcao == 4:
            post_data = {'cboTipoReg': '12'}  # qualidade da água

        elif opcao == 5:
            post_data = {'cboTipoReg': '13'}  # resumo de descarga

        elif opcao == 6:
            post_data = {'cboTipoReg': '16'}  # perfil transversal

        contagem = 0
        for idx, est in enumerate(self.estacoes):

            time.sleep(1)
            progress.setValue(idx + 1)

            try:
                print '** %s ** - Procurando dados...' % (est, )
                r = requests.post(self.montar_url_estacao(est), data=post_data)
                link = self.obter_link_arquivo(r)
                self.salvar_arquivo_texto(est, link)
                print u'** %s ** (Concluído)' % (est, )
                contagem += 1
            except:
                print u'** %s ** - ERRO: Estacão não possui dados ou verifique sua conexão e tente novamente.\n' % (
                    est, )

        contagem = str(contagem)
        nEstacoes = str(len(self.estacoes))

        self.iface.messageBar().clearWidgets()
        self.iface.messageBar().pushInfo(
            u'ECO Downloader', contagem + u' das ' + nEstacoes +
            u' estações selecionadas foram baixadas com sucesso.')
Exemple #23
0
class BusyBar(QThread):
    """
    Adapted from: http://stackoverflow.com/questions/8007602/
    looping-qprogressbar-gives-error-qobjectinstalleventfilter-cannot-filter-e  
           
    Looping progress bar
    create the signal that the thread will emit
    
    .. note::
       This function creates a busy bar but I have not figured out how to \
       attach it to a process. Therefore, it is currently functionally \
       useless.
    """
    changeValue = pyqtSignal(int)

    def __init__(self, text=""):
        QThread.__init__(self, parent=None)
        self.text = text
        self.stop = False
        self.proBar = QProgressBar()
        self.proBar.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen)
        self.proBar.setRange(0, 100)
        self.proBar.setTextVisible(True)
        self.proBar.setFormat(self.text)
        self.proBar.setValue(0)
        self.proBar.setFixedSize(300, 40)
        self.proBar.setAlignment(Qt.AlignCenter)
        self.proBar.show()

        #self.changeValue.connect(self.proBar.setValue, Qt.QueuedConnection)
        # Make the Busybar delete itself and the QProgressBar when done
        self.finished.connect(self.onFinished)

    def run(self):
        """
        """
        while not self.stop:
            # keep looping while self is visible
            # Loop sending mail
            for i in range(100):
                # emit the signal instead of calling setValue
                # also we can't read the progress bar value from the thread
                self.changeValue.emit(i)
                time.sleep(0.01)
            self.changeValue.emit(0)

    def onFinished(self):
        """
        """
        self.proBar.deleteLater()
        self.deleteLater()

    def Kill(self):
        """
        """
        self.stop = True
Exemple #24
0
    def export_features(self):
        """
        Exportiert die Datenbanklayer als ESRI-Shapefile
        :return:
        """
        directory = QFileDialog.getExistingDirectory()
        if not directory:
            return

        # Abfrage, ob Daten überschrieben werden sollen, wenn Verzeichnis nicht leer
        override = True
        if os.listdir(directory):
            reply = self.raise_message("dir_not_empty")
            if reply == QMessageBox.Yes:
                pass
            else:
                override = False

        # Verzeichnis leer oder override = True
        if override:
            # progress bar
            QgsMessageLog.logMessage("Exportiere nach " + directory, "KKG Plugin", QgsMessageLog.INFO)
            layers = QgsMapLayerRegistry.instance().mapLayers().values()
            progress_message_bar = self.iface.messageBar().createMessage("Exportiere...")
            progress = QProgressBar()
            progress.setMaximum(len(layers))
            progress.setAlignment(QtCore.Qt.AlignLeft | QtCore.Qt.AlignVCenter)
            progress_message_bar.layout().addWidget(progress)
            self.iface.messageBar().pushWidget(progress_message_bar, self.iface.messageBar().INFO)
            # current extent
            extent = self.iface.mapCanvas().extent()

            for i in range(0, len(layers)):
                layer = layers[i]
                file_path = directory + "\\" + layer.name()

                errors = QgsVectorFileWriter.writeAsVectorFormat(layer,
                                                                 file_path,
                                                                 "UTF-8",
                                                                 None,
                                                                 "ESRI Shapefile",
                                                                 filterExtent=extent,
                                                                 symbologyExport=QgsVectorFileWriter.NoSymbology)
                if errors:
                    QgsMessageLog.logMessage(layer.name() + " konnte nicht geschrieben werden.", "KKG Plugin",
                                             QgsMessageLog.WARNING)
                else:
                    QgsMessageLog.logMessage(layer.name() + " erfolgreich geschrieben", "KKG Plugin",
                                             QgsMessageLog.INFO)

                progress.setValue(i + 1)

        self.iface.messageBar().clearWidgets()
        QgsMessageLog.logMessage("Export abgeschlossen", "KKG Plugin", QgsMessageLog.INFO)
        self._create_project_from_export(directory)
Exemple #25
0
class BusyBar(QThread):        
    """
    Adapted from: http://stackoverflow.com/questions/8007602/
    looping-qprogressbar-gives-error-qobjectinstalleventfilter-cannot-filter-e  
           
    Looping progress bar
    create the signal that the thread will emit
    
    .. note::
       This function creates a busy bar but I have not figured out how to \
       attach it to a process. Therefore, it is currently functionally \
       useless.
    """
    changeValue = pyqtSignal(int)
    def __init__(self, text = "" ):
        QThread.__init__(self, parent = None)
        self.text = text
        self.stop = False
        self.proBar = QProgressBar()
        self.proBar.setWindowFlags(Qt.WindowStaysOnTopHint | Qt.SplashScreen )
        self.proBar.setRange( 0, 100 )
        self.proBar.setTextVisible( True )
        self.proBar.setFormat( self.text )
        self.proBar.setValue( 0 )
        self.proBar.setFixedSize( 300 , 40 )
        self.proBar.setAlignment(Qt.AlignCenter)
        self.proBar.show()

        #self.changeValue.connect(self.proBar.setValue, Qt.QueuedConnection)
        # Make the Busybar delete itself and the QProgressBar when done        
        self.finished.connect(self.onFinished)

    def run(self):
        """
        """
        while not self.stop:                
            # keep looping while self is visible
            # Loop sending mail 
            for i in range(100):
                # emit the signal instead of calling setValue
                # also we can't read the progress bar value from the thread
                self.changeValue.emit( i )
                time.sleep(0.01)
            self.changeValue.emit( 0 )

    def onFinished(self):
        """
        """
        self.proBar.deleteLater()
        self.deleteLater()

    def Kill(self):
        """
        """
        self.stop = True
Exemple #26
0
class QtProgressBar(QtControl, ProxyProgressBar):
    """ A Qt implementation of an Enaml ProxyProgressBar.

    """
    #: A reference to the widget created by the proxy.
    widget = Typed(QProgressBar)

    #--------------------------------------------------------------------------
    # Initialization API
    #--------------------------------------------------------------------------
    def create_widget(self):
        """ Create the underlying progress bar widget.

        """
        self.widget = QProgressBar(self.parent_widget())

    def init_widget(self):
        """ Create and initialize the underlying widget.

        """
        super(QtProgressBar, self).init_widget()
        d = self.declaration
        self.set_minimum(d.minimum)
        self.set_maximum(d.maximum)
        self.set_value(d.value)
        self.set_text_visible(d.text_visible)

    #--------------------------------------------------------------------------
    # ProxyProgressBar API
    #--------------------------------------------------------------------------
    def set_minimum(self, value):
        """ Set the minimum value of the widget.

        """
        self.widget.setMinimum(value)

    def set_maximum(self, value):
        """ Set the maximum value of the widget.

        """
        self.widget.setMaximum(value)

    def set_value(self, value):
        """ Set the value of the widget.

        """
        self.widget.setValue(value)

    def set_text_visible(self, visible):
        """ Set the text visibility on the widget.

        """
        self.widget.setTextVisible(visible)
Exemple #27
0
 def ProgresBar(self):
     progressMessageBar = iface.messageBar().createMessage(
         "Doing something boring...")
     progress = QProgressBar()
     progress.setMaximum(10)
     progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     progressMessageBar.layout().addWidget(progress)
     iface.messageBar().pushWidget(progressMessageBar,
                                   iface.messageBar().INFO)
     for i in range(10):
         time.sleep(0.2)
         progress.setValue(i + 1)
     iface.messageBar().clearWidgets()
    def _launchImport(self):
        '''
        Launch the import
        '''
        
        if not self._validateMapping():
            return
        
        self.close()
        
        # Progress bar + message
        progressMessageBar = PagLuxembourg.main.qgis_interface.messageBar().createMessage(QCoreApplication.translate('ImportDxfDialog','Importing DXF'))
        progress = QProgressBar()
        progress.setMaximum(self._getEnabledLayerMappingCount())
        progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        progress2 = QProgressBar()
        progress2.setMaximum(self.dxflayer_points.featureCount() + self.dxflayer_linestrings.featureCount() + self.dxflayer_polygons.featureCount())
        progress2.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress2)
        PagLuxembourg.main.qgis_interface.messageBar().pushWidget(progressMessageBar, QgsMessageBar.INFO)
        
        # Start import session
        self._startImportSession()
        
        for layer_mapping in self.mapping.layerMappings():
            # Skip if not enabled
            if not layer_mapping.isEnabled():
                continue
            
            # Progression message
            progressMessageBar.setText(QCoreApplication.translate('ImportDxfDialog','Importing {}').format(layer_mapping.sourceLayerName()))
            
            # QGIS layer
            qgis_layer = self._getQgisLayerFromTableName(layer_mapping.destinationLayerName())
            
            layer_indexmapping = layer_mapping.asIndexFieldMappings(qgis_layer.dataProvider().fields())
            
            progress2.setValue(0)
        
            # Import features according to geometry type
            if qgis_layer.geometryType() == QGis.Point:
                self._importLayer(self.dxflayer_points, qgis_layer, layer_indexmapping, progress2)
            elif qgis_layer.geometryType() == QGis.Line:
                self._importLayer(self.dxflayer_linestrings, qgis_layer, layer_indexmapping, progress2)
            elif qgis_layer.geometryType() == QGis.Polygon:
                self._importLayer(self.dxflayer_linestrings, qgis_layer, layer_indexmapping, progress2)
                self._importLayer(self.dxflayer_polygons, qgis_layer, layer_indexmapping, progress2)

        # Commit import session
        self._commitImport()
class InputDockWidget(QDockWidget):

    def __init__(self, *args):
        QDockWidget.__init__(self, *args)
        self.setupUi(self)
        self.setWindowIcon(QIcon(':/icons/qtsixa.png'))
        self.color = QColor(Qt.lightGray)
        self.setMinimumWidth(350)
        self.setContentsMargins(0, 0, 0, 0)
        self.adjustSize()

    def setupUi(self, QtSixAMainW):
        QtSixAMainW.setObjectName(_fromUtf8('QtSixAMainW'))
        QtSixAMainW.resize(935, 513)
        triggers = TiggersView(self)
        triggers.show()
        bumpers = BumpersView(self)
        bumpers.show()
        face = FaceButtonsView(self)
        face.show()
        dpad = DpadView(self)
        dpad.show()
        select = StartSelectView(self)
        select.show()
        sixaxis = SixAxisView(self)
        sixaxis.show()
        hbox = QHBoxLayout()
        hbox.addStretch(1)
        hbox.addWidget(triggers)
        hbox.addWidget(bumpers)
        hbox.addWidget(dpad)
        hbox.addWidget(face)
        hbox.addWidget(select)
        hbox.addWidget(sixaxis)
        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox)
        self.setLayout(vbox)
        self.progress = QProgressBar(self)
        self.progress.setGeometry(20, 2, 50, 20)
        self.progress.setTextVisible(False)
        self.progress.setOrientation(Qt.Vertical)
        self.progress.setValue(80)
        self.progress.move(60,28)
        self.progress.show()
        print self.style().objectName()
        QApplication.setStyle(QStyleFactory.create('Cleanlooks'))

    def paintEvent(self, event = None):
        pass
    def _set_progressbar(self):
        """Set QGIS progress bar and display progress
        """

        progressMessageBar = self.iface.messageBar().createMessage(self.tr("Zpracovávám objekty".decode("utf-8")))
        progress = QProgressBar()
        progress.setMaximum(100)
        progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(
            progressMessageBar, self.iface.messageBar().INFO)
        progress.setValue(2)

        return progress
Exemple #31
0
def OeQ_push_progressbar(title='Be patient!', message='Background calculations are going on...', timeout=0,
                         maxcount=100):
    widget = iface.messageBar().createMessage(title, message)

    # set a new message bar
    progressbarwidget = QProgressBar()
    progressbarwidget.setAlignment(Qt.AlignLeft)
    progressbarwidget.setMaximum(maxcount)
    progressbarwidget.setValue(0)
    widget.layout().addWidget(progressbarwidget)

    # pass the progress bar to the message Bar
    baritem=iface.messageBar().pushWidget(widget, iface.messageBar().INFO)
    OeQ_unlockQgis()
    #print "THIS PRINTLN IS NECESSARY TO TRIGGER THE MESSAGEBAR"
    return {'widget':progressbarwidget,'baritem':baritem}
 def __init__(self, parent, msg = ''):
     '''
     progressBar class instatiation method. It creates a QgsMessageBar with provided msg and a working QProgressBar
     :param parent:
     :param msg: string
     '''
     self.iface = parent.iface
     widget = self.iface.messageBar().createMessage("GooGIS plugin:",msg)
     progressBar = QProgressBar()
     progressBar.setRange(0,0) #(1,steps)
     progressBar.setValue(0)
     progressBar.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
     widget.layout().addWidget(progressBar)
     QtGui.qApp.processEvents()
     self.iface.messageBar().pushWidget(widget, QgsMessageBar.INFO, 50)
     QtGui.qApp.processEvents()
Exemple #33
0
class MessageBarProgress:
    def __init__(self, algname=None):
        self.msg = []
        self.progressMessageBar = \
            iface.messageBar().createMessage(self.tr('Executing algorithm <i>{0}</i>'.format(algname if algname else '')))
        self.progress = QProgressBar()
        self.progress.setMaximum(100)
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progressMessageBar.layout().addWidget(self.progress)
        iface.messageBar().pushWidget(self.progressMessageBar,
                                      iface.messageBar().INFO)

    def error(self, msg):
        self.msg.append(msg)

    def setText(self, text):
        pass

    def setPercentage(self, i):
        self.progress.setValue(i)

    def setInfo(self, _):
        pass

    def setCommand(self, _):
        pass

    def setDebugInfo(self, _):
        pass

    def setConsoleInfo(self, _):
        pass

    def close(self):
        if self.msg:
            dlg = MessageDialog()
            dlg.setTitle(
                QCoreApplication.translate('MessageBarProgress',
                                           'Problem executing algorithm'))
            dlg.setMessage("<br>".join(self.msg))
            dlg.exec_()
        iface.messageBar().clearWidgets()

    def tr(self, string, context=''):
        if context == '':
            context = 'MessageBarProgress'
        return QCoreApplication.translate(context, string)
    def processToa(self):
        """Converts DN to TOA reflectance"""
        startTime = time.time()
        if self.dlg.cbOutput.isChecked() and os.path.exists(self.dlg.leOutput.text()):
            outputPath = self.dlg.leOutput.text()
        else:
            outputPath = os.path.dirname(self.dlg.leInput.text().split(',')[0])
        if self.dlg.rbRefNorm.isChecked():
            bitcode = '32'
            outname = '_refToa32.tif'
        elif self.dlg.rbRefMilli.isChecked():
            bitcode = '16'
            outname = '_refToa16.tif'

        progressMessageBar = self.iface.messageBar().createMessage("DN to TOA conversion...")
        progress = QProgressBar()
        progress.setMaximum(100)
        progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progress.setTextVisible(False)
        label = QLabel()
        label.setText('  {0}%'.format(0))
        progressMessageBar.layout().addWidget(label)
        progressMessageBar.layout().addWidget(progress)

        self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO)
        
        if self.dlg.comboBox.currentIndex() == 0:
            bandList = self.dlg.leInput.text().split(',')
            idBand = {int(os.path.splitext(os.path.basename(i))[0][-1])-1:i for i in bandList}
            for band in idBand.keys():
                self.imgfile = idBand[band]
                nbBand = band
                self.history(outputPath, outname)
                for i in self.meta.dnToToa(self.imgfile, outname=outname, bitcode=bitcode, outpath=outputPath, nbBand=nbBand):
                    progress.setValue(i)
                    label.setText('{0}%'.format(i))
        else:
            self.imgfile = self.dlg.leInput.text().split(',')[0]
            self.history(outputPath, outname)
            for i in self.meta.dnToToa(self.imgfile, outname=outname, bitcode=bitcode, outpath=outputPath):
                progress.setValue(i)
                label.setText('{0}%'.format(i))
        self.iface.messageBar().clearWidgets()
        self.bar.pushMessage("Image processed !", level=QgsMessageBar.INFO, duration=3)
        endTime = time.time()

        self.dlg.teHistory.append('<b>reflectance processing duration:</b><br>{0} seconds<br>'.format(str(endTime - startTime)))
Exemple #35
0
class MessageBarProgress:

    def __init__(self, algname=None):
        self.msg = []
        self.progressMessageBar = \
            iface.messageBar().createMessage(self.tr('Executing algorithm <i>{0}</i>'.format(algname if algname else '')))
        self.progress = QProgressBar()
        self.progress.setMaximum(100)
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progressMessageBar.layout().addWidget(self.progress)
        iface.messageBar().pushWidget(self.progressMessageBar,
                                      iface.messageBar().INFO)

    def error(self, msg):
        self.msg.append(msg)

    def setText(self, text):
        pass

    def setPercentage(self, i):
        self.progress.setValue(i)

    def setInfo(self, _):
        pass

    def setCommand(self, _):
        pass

    def setDebugInfo(self, _):
        pass

    def setConsoleInfo(self, _):
        pass

    def close(self):
        if self.msg:
            dlg = MessageDialog()
            dlg.setTitle(QCoreApplication.translate('MessageBarProgress', 'Problem executing algorithm'))
            dlg.setMessage("<br>".join(self.msg))
            dlg.exec_()
        iface.messageBar().clearWidgets()

    def tr(self, string, context=''):
        if context == '':
            context = 'MessageBarProgress'
        return QCoreApplication.translate(context, string)
Exemple #36
0
def OeQ_push_progressbar(title='Be patient!',
                         message='Background calculations are going on...',
                         timeout=0,
                         maxcount=100):
    widget = iface.messageBar().createMessage(title, message)

    # set a new message bar
    progressbarwidget = QProgressBar()
    progressbarwidget.setAlignment(Qt.AlignLeft)
    progressbarwidget.setMaximum(maxcount)
    progressbarwidget.setValue(0)
    widget.layout().addWidget(progressbarwidget)

    # pass the progress bar to the message Bar
    baritem = iface.messageBar().pushWidget(widget, iface.messageBar().INFO)
    OeQ_unlockQgis()
    #print "THIS PRINTLN IS NECESSARY TO TRIGGER THE MESSAGEBAR"
    return {'widget': progressbarwidget, 'baritem': baritem}
Exemple #37
0
    def progress_dialog(progress=0, title='CQFS Progress', label='Running...'):
        dialog = QProgressDialog()
        dialog.setWindowTitle(title)
        dialog.setLabelText(label)
        dialog.setAutoClose(True)

        bar = QProgressBar(dialog)
        bar.setTextVisible(True)
        bar.setValue(progress)
        bar.setMaximum(100)

        dialog.setBar(bar)
        dialog.setMinimumWidth(300)
        dialog.show()

        if int(progress) == 0:
            bar.setValue(0)
        return dialog, bar
Exemple #38
0
    def start(self):
        """
        To start the rebuild
        """
        snap_util = self.__iface.mapCanvas().snappingUtils()
        extent = self.__iface.mapCanvas().extent()
        self.__progressDialog = QProgressDialog()
        self.__progressDialog.setWindowTitle(
            QCoreApplication.translate("VDLTools", "Rebuild Index..."))
        self.__progressDialog.setLabelText(
            QCoreApplication.translate("VDLTools",
                                       "Percentage of indexed layers"))
        progressBar = QProgressBar(self.__progressDialog)
        progressBar.setTextVisible(True)
        cancelButton = QPushButton()
        cancelButton.setText(QCoreApplication.translate("VDLTools", "Cancel"))
        cancelButton.clicked.connect(self.kill)
        self.__progressDialog.setBar(progressBar)
        self.__progressDialog.setCancelButton(cancelButton)
        self.__progressDialog.setMinimumWidth(300)
        self.__progressDialog.show()

        lcs_list = snap_util.layers()
        step = 0
        self.killed = False
        for lc in lcs_list:
            if self.killed:
                break
            locator = snap_util.locatorForLayer(lc.layer)
            if locator.extent() is not None:
                txt = locator.extent().toString()
            else:
                txt = "None"
            print("old extent : " + txt)
            print("new extent : " + extent.toString())
            locator.setExtent(extent)
            if not locator.hasIndex():
                locator.init()
            else:
                locator.rebuildIndex()
            locator.setExtent(None)
            progressBar.setValue(100 * step / len(lcs_list))
            step += 1
        self.__progressDialog.close()
Exemple #39
0
    def processAlgorithm(self, progress):
        """Here is where the processing itself takes place."""

        INPUT_RASTER = self.getParameterValue(self.INPUT_RASTER)
        OUTPUT_RASTER = self.getOutputValue(self.OUTPUT_RASTER)
        MEDIAN_ITER = self.getParameterValue(self.MEDIAN_ITER)
        MEDIAN_SIZE = self.getParameterValue(self.MEDIAN_SIZE)

        # First we create the output layer. The output value entered by
        # the user is a string containing a filename, so we can use it
        # directly

        from scipy import ndimage
        data, im = dataraster.open_data_band(INPUT_RASTER)

        # get proj,geo and dimension (d) from data
        proj = data.GetProjection()
        geo = data.GetGeoTransform()
        d = data.RasterCount

        # add progress bar
        # And now we can process
        from PyQt4.QtGui import QProgressBar
        pb = QProgressBar()
        pb.setMaximum(d * MEDIAN_ITER)
        pbNow = 0

        outFile = dataraster.create_empty_tiff(OUTPUT_RASTER, im, d, geo, proj)

        for i in range(d):
            # Read data from the right band
            pbNow += 1
            pb.setValue(pbNow)

            tempBand = data.GetRasterBand(i + 1).ReadAsArray()
            tempBand = ndimage.filters.median_filter(tempBand,
                                                     size=(MEDIAN_SIZE,
                                                           MEDIAN_SIZE))

            # Save bandand outFile
            out = outFile.GetRasterBand(i + 1)
            out.WriteArray(tempBand)
            out.FlushCache()
            tempBand = None
Exemple #40
0
    def _draw_transfer_item(self, container, filename, id, part_number, peer_ip, percent):
        items_found = container.findItems(id, Qt.MatchExactly, 1)
        item = None
        if len(items_found) > 0:

            for i in items_found:
                if i.text(4) == peer_ip and i.text(2) == str(part_number):
                    item = i
                    break

        if item:
            container.itemWidget(item, 3).setValue(percent)
        else:
            item = QTreeWidgetItem(container, QStringList([str(filename), str(id), str(part_number), "0",  str(peer_ip)]))
            progress_bar = QProgressBar()
            progress_bar.setMinimum(0)
            progress_bar.setMaximum(100)
            progress_bar.setValue(percent)
            container.setItemWidget(item, 3, progress_bar)
Exemple #41
0
class WebWidget(QDockWidget):
	def __init__(self, name, parent=None):
		QDockWidget.__init__(self, name, parent)
		self.setObjectName(name)
		
		self.webView = QWebView(self)
		self.url = QUrl()
		self.lastUrl = QUrl()

		self.progressBar = QProgressBar(self)

		self.connect(self.webView, SIGNAL('loadFinished(bool)'), self.webViewDone)
		self.connect(self.webView, SIGNAL('loadProgress(int)'), self, SLOT('onWebViewStatusChange(int)'))

		self.setWidget(self.webView)



	def webViewDone(self):
		self.setTitleBarWidget(None)
		self.emit(SIGNAL('done()'))

	@pyqtSlot(int)
	def onWebViewStatusChange(self, val):
		self.progressBar.setValue(val)

	def keyPressEvent(self, e):
		if e.text() == '+' or e.text() == '-' or e.text() == '0':
			if e.text() == '+':	self.webView.setZoomFactor(self.webView.zoomFactor() + .05)
			elif e.text() == '-':	self.webView.setZoomFactor(self.webView.zoomFactor() - .05)
			elif e.text() == '0':	self.webView.setZoomFactor(1)

			self.config.saveZoomFactor(self.objectName(), self.webView.zoomFactor())

	def reload_(self):
		if not self.isVisible(): return
		self.setTitleBarWidget(self.progressBar)
		if self.url.toString() == self.lastUrl.toString():
			self.webView.reload()
		else:
			self.webView.load(self.url)
		self.lastUrl.setUrl(self.url.toString())
		self.webView.setZoomFactor(self.config.loadZoomFactor(self.objectName()))
    def load(self, reader):
        """Load LOG file using specified reader.

        SafecastReaderError is raised on failure.

        :param reader: reader class used for reading input data
        """
        if self._loaded:
            return # data already loaded

        # store metadata
        self._metadata = {
            'format': reader.format_version,
            'deadtime': reader.deadtime
        }

        # create progress bar widget
        progressMessageBar = iface.messageBar().createMessage(self.tr("Loading data..."))
        progress = QProgressBar()
        progress.setMaximum(100)
        progressMessageBar.layout().addWidget(progress)
        iface.messageBar().pushWidget(progressMessageBar, iface.messageBar().INFO)

        # load items as new point features (inform user about progress)
        i = 0
        count = reader.count()
        start = time.clock()
        for f in reader:
            self._process_row(f) # add features to the map layer
            i += 1
            if i % 100 == 0:
                percent = i / float(count) * 100
                progress.setValue(percent)
        endtime = time.clock() - start
        progress.setValue(100)
        iface.messageBar().clearWidgets()

        # inform user about successfull import
        iface.messageBar().pushMessage(self.tr("Info"),
                                       self.tr("{} features loaded (in {:.2f} sec).").format(count, endtime),
                                       level=QgsMessageBar.INFO, duration=3)
        # data loaded (avoid multiple imports)
        self._loaded = True
class MessageBarProgress:
    def __init__(self):
        self.progressMessageBar = \
            iface.messageBar().createMessage(self.tr('Executing algorithm'))
        self.progress = QProgressBar()
        self.progress.setMaximum(100)
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progressMessageBar.layout().addWidget(self.progress)
        iface.messageBar().pushWidget(self.progressMessageBar,
                                      iface.messageBar().INFO)

    def error(self, msg):
        iface.messageBar().clearWidgets()
        iface.messageBar().pushMessage(self.tr('Error'),
                                       msg,
                                       level=QgsMessageBar.CRITICAL,
                                       duration=3)

    def setText(self, text):
        pass

    def setPercentage(self, i):
        self.progress.setValue(i)

    def setInfo(self, _):
        pass

    def setCommand(self, _):
        pass

    def setDebugInfo(self, _):
        pass

    def setConsoleInfo(self, _):
        pass

    def close(self):
        iface.messageBar().clearWidgets()

    def tr(self, string, context=''):
        if context == '':
            context = 'MessageBarProgress'
        return QCoreApplication.translate(context, string)
Exemple #44
0
    def __init__(self, parent):
        QProgressBar.__init__(self, parent)

        self.fLeftClickDown = False

        self.fMinimum   = 0.0
        self.fMaximum   = 1.0
        self.fRealValue = 0.0

        self.fLabel = ""
        self.fPreLabel = " "
        self.fTextCall = None

        self.setFormat("(none)")

        # Fake internal value, 10'000 precision
        QProgressBar.setMinimum(self, 0)
        QProgressBar.setMaximum(self, 10000)
        QProgressBar.setValue(self, 0)
Exemple #45
0
 def __init__(self,inMsg=' Loading...',inMaxStep=1):
         # initialize progressBar            
         """
         """# Save reference to the QGIS interface
         QApplication.processEvents() # Help to keep UI alive
         
         widget = iface.messageBar().createMessage('Please wait  ',inMsg)            
         prgBar = QProgressBar()
         self.prgBar=prgBar
         self.iface=iface
         widget.layout().addWidget(self.prgBar)
         iface.messageBar().pushWidget(widget, iface.messageBar().WARNING)
         QApplication.setOverrideCursor(QtCore.Qt.WaitCursor)
         
         # if Max 0 and value 0, no progressBar, only cursor loading
         # default is set to 0
         prgBar.setValue(1)
         # set Maximum for progressBar
         prgBar.setMaximum(inMaxStep)
    def run(self):
    
            import urllib2    
    
            stringa1 = "http://smartroadsense.it/open_data.zip"
        
            mapCanvas = self.iface.mapCanvas()

#--------------------------------
            progressMessageBar = self.iface.messageBar().createMessage("SmartRoadSense: Loading remote CSV Open Data.  Please, wait...")
            progress = QProgressBar()

            progress.setMaximum(10)
            progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
            progressMessageBar.layout().addWidget(progress)

            self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO)
            
            for i in range(10):
                  time.sleep(1)
                  progress.setValue(i + 1)
            self.iface.messageBar().clearWidgets()            
#--------------------------------

            msg = ("Loading remote csv open data.  Please, wait...")
            self.iface.messageBar().pushMessage("SmartRoadSense:   ",
                                                msg,
                                                QgsMessageBar.INFO, 3)


            tempDir = unicode(QFileInfo(QgsApplication.qgisUserDbFilePath()).path()) + "/python/plugins/smartroadsense/temp/"
            
            stringaUrl = stringa1
 
            try:                   
               response = urllib2.urlopen(stringaUrl)
               print "downloading " + stringaUrl
               
               Zippo = response.read()

            except HTTPError, e:
               print "HTTP Error:",e.code , url
Exemple #47
0
class MessageBarProgress:

    def __init__(self):
        self.progressMessageBar = \
            iface.messageBar().createMessage(self.tr('Executing algorithm'))
        self.progress = QProgressBar()
        self.progress.setMaximum(100)
        self.progress.setAlignment(Qt.AlignLeft | Qt.AlignVCenter)
        self.progressMessageBar.layout().addWidget(self.progress)
        iface.messageBar().pushWidget(self.progressMessageBar,
                                      iface.messageBar().INFO)

    def error(self, msg):
        iface.messageBar().clearWidgets()
        iface.messageBar().pushMessage(self.tr('Error'),
            msg, level=QgsMessageBar.CRITICAL, duration=3)

    def setText(self, text):
        pass

    def setPercentage(self, i):
        self.progress.setValue(i)

    def setInfo(self, _):
        pass

    def setCommand(self, _):
        pass

    def setDebugInfo(self, _):
        pass

    def setConsoleInfo(self, _):
        pass

    def close(self):
        iface.messageBar().clearWidgets()

    def tr(self, string, context=''):
        if context == '':
            context = 'MessageBarProgress'
        return QCoreApplication.translate(context, string)
Exemple #48
0
class ProgressDialog(QDialog):

  def __init__(self, parent, title='', info_start='', maximum=100, add=0):
    QDialog.__init__(self, parent)
    self.add=add
    self.setWindowTitle(title)
    vbox=QVBoxLayout()
    self.info=QLabel(self)
    vbox.addWidget(self.info)
    self.info.setText(info_start)
    self.progressBar=QProgressBar()
    self.progressBar.setMaximum(maximum)
    self.progressBar.setMinimum(0)
    vbox.addWidget(self.progressBar)
    self.setLayout(vbox)

  def progress(self, value):
    param=value*100+self.add
    self.progressBar.setValue(param)
    app=QApplication.instance()
    app.processEvents()
    def run(self):
        msgBox = QMessageBox();
        msgBox.setWindowTitle(u"Répercussion des modification réalisées")
        msgBox.setInformativeText(u"Voulez-vous lancer la répercussion des changements du linéaire sur le plan de circulation ?")
        msgBox.setStandardButtons(QMessageBox.Ok |  QMessageBox.Cancel)
        msgBox.setDefaultButton(QMessageBox.Ok)
        ret = msgBox.exec_()
        
        progressMessageBar = self.iface.messageBar().createMessage(u"Répercussion du linéaire : Traitement en cours ....")
        progress = QProgressBar()
        progress.setMaximum(10)
        progressMessageBar.layout().addWidget(progress)
        self.iface.messageBar().pushWidget(progressMessageBar, self.iface.messageBar().INFO)

        if ret == QMessageBox.Ok:
            for i in range(10):
                time.sleep(1)
                progress.setValue(i + 1)
            self.runSql()
        else:
            self.iface.messageBar().clearWidgets()
Exemple #50
0
class TrackProgressDialog(QDialog):
    finished = pyqtSignal()

    def __init__(self, parent=None, numStages=1):
        QDialog.__init__(self, parent)

        self.currentStep = 0
        self.progress = None

        l = QVBoxLayout()
        self.setLayout(l)

        self.overallProgress = QProgressBar()
        self.overallProgress.setRange(0, numStages)
        self.overallProgress.setFormat("step %v of " + str(numStages))

        self.currentStepProgress = QProgressBar()
        self.currentStepProgress.setRange(0, 100)
        self.currentStepProgress.setFormat("%p %")

        self.overallLabel = QLabel("Overall progress")
        self.currentStepLabel = QLabel("Current step")

        l.addWidget(self.overallLabel)
        l.addWidget(self.overallProgress)
        l.addWidget(self.currentStepLabel)
        l.addWidget(self.currentStepProgress)
        l.maximumSize()

        self.update()

    def __onNewStep(self, description):
        self.currentStep += 1
        self.currentStepProgress.setValue(0)
        self.overallProgress.setValue(self.currentStep)
        self.currentStepLabel.setText(description)
        self.update()

    def __onCurrentStepProgressChanged(self, progress):
        timesHundred = round(1000.0 * progress)
        timesTen = round(100.0 * progress)
        if (not self.currentStepProgress.value()
                == timesTen) and (timesHundred - 10 * timesTen) == 0:
            self.currentStepProgress.setValue(timesTen)
            self.update()

    def run(self):
        self.trackProgress = TrackProgress(self)
        self.trackProgress.progress.connect(
            self.__onCurrentStepProgressChanged, Qt.BlockingQueuedConnection)
        self.trackProgress.newStep.connect(self.__onNewStep,
                                           Qt.BlockingQueuedConnection)
        self.trackProgress.done.connect(self.onTrackDone)
        self.trackProgress.start()

    def onTrackDone(self):
        self.trackProgress.wait(
        )  # Join the extractor thread so its safe to immediately destroy the window
        self.finished.emit()
        self.close()
Exemple #51
0
class downloadItemMainInfoClass(QWidget):
  def __init__(self, title, parent = None):
    QWidget.__init__(self, parent)
    self.vLayout = QVBoxLayout(self)
    margins = self.vLayout.contentsMargins()
    self.vLayout.setContentsMargins(margins.left(), 0, margins.right(), 0)


    # Torrent primary data
    self.title = title

    # Torrent title
    self.vLayout.addWidget(QLabel("<b>%s</b>" % title))

    self.progressLabel = QLabel() 
    self.vLayout.addWidget(self.progressLabel)

    # Progress percent
    self.progressLayout = QHBoxLayout()
    self.vLayout.addLayout(self.progressLayout)
    # Progress percent label
    self.percentLabel = QLabel("0%")
    self.progressLayout.addWidget(self.percentLabel)
    # Progress percent bar
    self.downloadedBar = QProgressBar()
    self.downloadedBar.setTextVisible(False)
    self.progressLayout.addWidget(self.downloadedBar)
    # Pause/Stop/etc buttons...

    # Speed
    self.speedLabel = QLabel()
    self.vLayout.addWidget(self.speedLabel)

  def fillData(self, size, downloaded, uploaded, ratio, percent, downspeed, upspeed, state):
    progressLabel = "%s/%s, uploaded %s (Ratio %0.1f)"
    speedLabel = "%s, ↓ %s/s ↑ %s/s"
    self.progressLabel.setText(progressLabel % (from_bit_to(downloaded), from_bit_to(size), from_bit_to(uploaded), ratio))
    self.percentLabel.setText(("%0.1f" % percent) + "%")
    self.speedLabel.setText(self.trUtf8(speedLabel % (states[state][0], from_bit_to(downspeed), from_bit_to(upspeed))))
    self.downloadedBar.setValue(percent)
Exemple #52
0
class ThreadManagerDialog(QDialog):
    def __init__( self, iface, title="Worker Thread"):
        QDialog.__init__( self, iface)#.mainWindow() )
        self.iface = iface
        self.setWindowTitle(title)
        self.setLayout(QVBoxLayout())
        self.primaryLabel = QLabel(self)
        self.layout().addWidget(self.primaryLabel)
        self.primaryBar = QProgressBar(self)
        self.layout().addWidget(self.primaryBar)
        self.secondaryLabel = QLabel(self)
        self.layout().addWidget(self.secondaryLabel)
        self.secondaryBar = QProgressBar(self)
        self.layout().addWidget(self.secondaryBar)
        self.closeButton = QPushButton("Close")
        self.closeButton.setEnabled(False)
        self.layout().addWidget(self.closeButton)
        self.closeButton.clicked.connect(self.reject)
    def run(self):
        self.runThread()
        self.exec_()
    def runThread( self):
        QObject.connect( self.workerThread, SIGNAL( "jobFinished( PyQt_PyObject )" ), self.jobFinishedFromThread )
        QObject.connect( self.workerThread, SIGNAL( "primaryValue( PyQt_PyObject )" ), self.primaryValueFromThread )
        QObject.connect( self.workerThread, SIGNAL( "primaryRange( PyQt_PyObject )" ), self.primaryRangeFromThread )
        QObject.connect( self.workerThread, SIGNAL( "primaryText( PyQt_PyObject )" ), self.primaryTextFromThread )
        QObject.connect( self.workerThread, SIGNAL( "secondaryValue( PyQt_PyObject )" ), self.secondaryValueFromThread )
        QObject.connect( self.workerThread, SIGNAL( "secondaryRange( PyQt_PyObject )" ), self.secondaryRangeFromThread )
        QObject.connect( self.workerThread, SIGNAL( "secondaryText( PyQt_PyObject )" ), self.secondaryTextFromThread )
        self.workerThread.start()
    def cancelThread( self ):
        self.workerThread.stop()
    def jobFinishedFromThread( self, success ):
        self.workerThread.stop()
        self.primaryBar.setValue(self.primaryBar.maximum())
        self.secondaryBar.setValue(self.secondaryBar.maximum())
        self.emit( SIGNAL( "jobFinished( PyQt_PyObject )" ), success )
        self.closeButton.setEnabled( True )
    def primaryValueFromThread( self, value ):
        self.primaryBar.setValue(value)
    def primaryRangeFromThread( self, range_vals ):
        self.primaryBar.setRange( range_vals[ 0 ], range_vals[ 1 ] )
    def primaryTextFromThread( self, value ):
        self.primaryLabel.setText(value)
    def secondaryValueFromThread( self, value ):
        self.secondaryBar.setValue(value)
    def secondaryRangeFromThread( self, range_vals ):
        self.secondaryBar.setRange( range_vals[ 0 ], range_vals[ 1 ] )
    def secondaryTextFromThread( self, value ):
        self.secondaryLabel.setText(value)
Exemple #53
0
 def updateshows(self):
     ''' Update local shows with remote content '''
     
     label = QLabel('Updating: ')
     bar = QProgressBar()
     bar.setMinimum(0)
     bar.setMaximum(self.ui.showlist.model().rowCount())
     bar.setValue(bar.minimum())
     
     self.ui.statusbar.addWidget(label)
     self.ui.statusbar.addWidget(bar)
     
     for row in range(self.ui.showlist.model().rowCount()):
         self.backend.updateshow(self.ui.showlist.model().getshow(row).id)
         bar.setValue(row)
         
     self.ui.statusbar.removeWidget(bar)
     self.ui.statusbar.removeWidget(label)
     
     now = datetime.now()
     self.settings.set(settings.categories.application, settings.keys.lastupdated, now)
     self.setlastupdatedstatus(now)
     self.displayshowstatuses()
Exemple #54
0
    def CRC_Calculation(byteArray):
        numArray = [0, 2577006594, 2553349383, 27985157, 2607222541, 50138895, 55970314, 2597063176, 2647333657, 72424219, 100277790, 2623544860, 111940628, 2671121430, 2661093651, 117903633, 2425566001, 151597875, 144848438, 2436380212, 200555580, 2456697918, 2479175995, 174012729, 223881256, 2495752234, 2506698031, 217263405, 2520721189, 262481703, 235807266, 2543067680, 2317575009, 330916707, 303195750, 2340972132, 289696876, 2296278126, 2306173291, 284125545, 401111160, 2389866618, 2413395327, 373521789, 2358212469, 353728375, 348025458, 2367976048, 447762512, 2200588370, 2189514071, 454776149, 2178375517, 407723871, 434526810, 2155633240, 2273004361, 518081355, 524963406, 2261798476, 471614532, 2240169030, 2217558339, 498549057, 3208889281, 651805635, 661833414, 3202926276, 606391500, 3183398094, 3155544523, 630180297, 579393752, 3138574554, 3132743135, 589553117, 3119503317, 544593879, 568251090, 3091518160, 802222320, 3058364658, 3085039095, 779875829, 3031957501, 757989375, 747043578, 3038575352, 2988174313, 729934827, 707456750, 3014717164, 696050916, 2967921894, 2974671331, 685236705, 895525024, 2902106274, 2907809191, 885761445, 2919739309, 933081007, 909552298, 2947328680, 2829827001, 825342907, 815447742, 2835398332, 869053620, 2857809078, 2885530035, 845656497, 2784203665, 1013552019, 1036162710, 2757269140, 1049926812, 2802752670, 2795870619, 1061132697, 943229064, 2711783562, 2684980623, 965971341, 2740946821, 986023815, 997098114, 2733933184, 3582100097, 1276674691, 1303611270, 3559491460, 1323666828, 3615460750, 3604252811, 1330546825, 1212783000, 3520305562, 3497565343, 1239587997, 3543045781, 1253349015, 1260360594, 3531969424, 1158787504, 3700142514, 3709908151, 1153086645, 3732324029, 1206697663, 1179106234, 3755850680, 3638209193, 1094757035, 1089187758, 3648106412, 1136502180, 3660031398, 3683426467, 1108779169, 1604444640, 3325813218, 3348161767, 1577772261, 3301371629, 1566371567, 1559751658, 3312315368, 3261790969, 1542519547, 1515978750, 3284271100, 1494087156, 3231184374, 3241996531, 1487335665, 3476214481, 1453904595, 1459869654, 3466188756, 1414913500, 3452952030, 3429161179, 1442765017, 1392101832, 3412314570, 3402157263, 1397935309, 3382625989, 1342490311, 1370473410, 3358966720, 1791050048, 4082843970, 4075832391, 1802126405, 4054208077, 1748782671, 1771522890, 4027403080, 4144650841, 1854954075, 1866162014, 4137770844, 1819104596, 4126627158, 4099690579, 1841713233, 4199707249, 1674080883, 1650685814, 4227430260, 1630895484, 4172250494, 4177819771, 1620998265, 1738107240, 4261636458, 4289227887, 1714580589, 4244530789, 1701078631, 1691312994, 4250231648, 3772916257, 2037916195, 2027104038, 3779667748, 2072325420, 3793693998, 3820234795, 2049845289, 2099853624, 3836950842, 3843570751, 2088909885, 3863885365, 2144613943, 2122265394, 3890557744, 1886458128, 3924496658, 3896513559, 1910117397, 3944095261, 1921785375, 1931942682, 3938261784, 3988392457, 1948256779, 1972047630, 3960540940, 1994196228, 4014408966, 4008443907, 2004221953]
        num = 0
        j = 0

        progressMessageBar = define._messagBar.createMessage("Reading the file ...")
        progress = QProgressBar()
        progress.setAlignment(Qt.AlignLeft|Qt.AlignVCenter)
        progressMessageBar.layout().addWidget(progress)
        define._messagBar.pushWidget(progressMessageBar, define._messagBar.INFO)
        maxium = len(byteArray)
        progress.setMaximum(maxium)
        progress.setValue(0)

        for i in range(len(byteArray)):
            byte0 = None
            if isinstance(byteArray, bytearray):
                byte0 = Type.ByteFunc.d2b(num ^ ord(chr(byteArray[i])))
            else:
                byte0 = Type.ByteFunc.d2b(num ^ ord(byteArray[i]))
            num = num >> 8
            num = num ^ numArray[ord(byte0) % 36]
            progress.setValue(i)
            QApplication.processEvents()
        progress.setValue(maxium)
        define._messagBar.hide()

        resultByteArray = bytearray(4)
        for i in range(4):
            resultByteArray[i] = '0'
        resultByteArray[0] = Type.ByteFunc.d2b(num)
        resultByteArray[1] = Type.ByteFunc.d2b(num >> 8)
        resultByteArray[2] = Type.ByteFunc.d2b(num >> 16)
        resultByteArray[3] = Type.ByteFunc.d2b(num >> 24)

        stringBuilder = StringBuilder()
        for i in range(4):
            stringBuilder.Append(hex(ord(chr(resultByteArray[i]))).replace("0x", "").upper())
        return stringBuilder.ToString()
Exemple #55
0
class Ui_Form (QWidget):
    '''
    Ui class. Generated with pyuic4.
    '''
    def __init__ (self, parent=None):
        
        QWidget.__init__(self, parent)
        self.timer = QTimer (self)
        
        self.image    = QImage (720, 450, QImage.Format_RGB888)
        
        self.__engine = REngineThread ()
        self.__model  = Model ()
        self.__fsm    = DebugStateMachine (self)
    
        
    def wireEngineUp (self):
        '''
        this method connects the REngine's signals.
        '''
        self.connect (self.__engine, SIGNAL ("update (float)"), self.updateImage)
        self.connect (self.__engine, SIGNAL ("thread_completed()"), self.__fsm.finaliseRender)
        self.connect (self.__engine, SIGNAL ("inters_created (PyQt_PyObject, PyQt_PyObject)"), self.widget.addIntersection)
        self.connect (self.__engine, SIGNAL ("vector_created (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addArrow)
        self.connect (self.__engine, SIGNAL ("line_created   (PyQt_PyObject, PyQt_PyObject, QString)"), self.widget.addLine)
    
    def wireOGLViewerUp (self):
        '''
        this method connects the REngine's signals.
        '''
        self.widget.setModel (self.__model)
        
        QObject.connect (self.widget, SIGNAL ("MatrixChanged (PyQt_PyObject)"), self.displayGLMatrix)

        # call the function run regularly when the focus is on it. (60 FPS if interval = 20)
        QObject.connect (self.timer, SIGNAL ('timeout()'), self.widget.run)
    
    def freezeGLFrameRate (self):
        
        self.timer.stop ()
    
    def speedUpGLFrameRate (self):
        
        self.timer.start ()
        self.timer.setInterval (20)
        
    def setupUi (self, Form):
        
        font = QFont ()
        font.setPointSize (9)
        font.setBold (False)
        font.setWeight (50)
        
        sizePolicy = QSizePolicy (QSizePolicy.Fixed, QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch (0)
        sizePolicy.setVerticalStretch (0)
        
        Form.setObjectName (_fromUtf8("Form"))
        Form.resize (971, 930)
        self.plainTextEdit = QPlainTextEdit (Form)
        self.plainTextEdit.setGeometry (QRect (740, 280, 221, 611))
        self.plainTextEdit.setObjectName (_fromUtf8 ("plainTextEdit"))
        self.plainTextEdit.setFont (font)
        
        self.widget = OGLViewer (Form)
        self.widget.setUi_Form (self)
        self.widget.setGeometry (QRect (10, 10, 720, 450))
        sizePolicy.setHeightForWidth (self.widget.sizePolicy().hasHeightForWidth())
        self.widget.setSizePolicy (sizePolicy)
        self.widget.setObjectName (_fromUtf8 ("widget"))
        
        self.wireOGLViewerUp ()
        self.wireEngineUp ()
        
        self.label_view = QLabel (Form)
        self.label_view.setGeometry  (QRect (10, 470, 720, 450))
        sizePolicy.setHeightForWidth (self.label_view.sizePolicy().hasHeightForWidth())
        self.label_view.setSizePolicy (sizePolicy)
        self.label_view.setObjectName (_fromUtf8 ("label_view"))
        self.initLabel ()          
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
        
        # buttons definitions
        
        self.renderBtn    = QPushButton (Form)
        self.pauseBtn     = QPushButton (Form)
        self.stopBtn      = QPushButton (Form)
        self.upBtn        = QPushButton (Form)
        self.downBtn      = QPushButton (Form)
        self.moreDownBtn  = QPushButton (Form)
        self.moreUpBtn    = QPushButton (Form)
        self.rightBtn     = QPushButton (Form)
        self.moreRightBtn = QPushButton (Form)
        self.leftBtn      = QPushButton (Form)
        self.furtherLeft  = QPushButton (Form)
        self.grid_switch  = QPushButton (Form)
        
        buttons_properties_list = [[self.renderBtn,    True,  QRect (740, 140, 61, 21), "render"],
                                   [self.pauseBtn,     False, QRect (740, 120, 61, 21), "pause"],
                                   [self.stopBtn,      False, QRect (740, 100, 61, 21), "stop"],
                                   [self.upBtn,        False, QRect (820, 120, 21, 21), "one_row_up"],
                                   [self.downBtn,      False, QRect (820, 140, 21, 21), "one_row_down"],
                                   [self.moreDownBtn,  False, QRect (820, 160, 21, 21), "ten_rows_down"],
                                   [self.moreUpBtn,    False, QRect (820, 100, 21, 21), "ten_rows_up"],
                                   [self.rightBtn,     False, QRect (780, 180, 21, 21), "one_column_right"],
                                   [self.moreRightBtn, False, QRect (800, 180, 21, 21), "ten_columns_right"],
                                   [self.leftBtn,      False, QRect (760, 180, 21, 21), "one_column_left"],
                                   [self.furtherLeft,  False, QRect (740, 180, 21, 21), "ten_columns_left"],
                                   [self.grid_switch,  False, QRect (870, 230, 91, 31), "grid_switch"]]
        
        for button in buttons_properties_list:
            button[0].setEnabled  (button[1])
            button[0].setGeometry (button[2])
            button[0].setFont (font)
            button[0].setObjectName (_fromUtf8 (button[3]))
        
        # other UI elements
        
        self.progressBar = QProgressBar (Form)
        self.progressBar.setGeometry (QRect (740, 901, 221, 20))
        self.progressBar.setProperty ("value", 0)
        self.progressBar.setObjectName (_fromUtf8("progressBar"))
        self.progressBar.setMinimum (0)
        self.progressBar.setMaximum (100)
        
        self.slider_label = QLabel (Form)
        self.slider_label.setGeometry (QRect(900, 260, 61, 16))
        self.slider_label.setFont(font)
        self.slider_label.setObjectName (_fromUtf8("slider_label"))
        self.slider_label.setEnabled (True)
        
        self.arrowSizeSlider = QSlider (Form)
        self.arrowSizeSlider.setGeometry (QRect (740, 258, 151, 22))
        self.arrowSizeSlider.setMinimum (2)
        self.arrowSizeSlider.setMaximum (40)
        self.arrowSizeSlider.setSingleStep (1)
        self.arrowSizeSlider.setProperty ("value", 4)
        self.arrowSizeSlider.setOrientation (Qt.Horizontal)
        self.arrowSizeSlider.setObjectName  (_fromUtf8("arrowSizeSlider"))

        self.retranslateUi (Form)
        QMetaObject.connectSlotsByName (Form)
    
    def retranslateUi (self, Form):
        
        Form.setWindowTitle       (_translate ("Form", "RayTracing Debugging Tool", None))
        
        self.renderBtn.setText    (_translate ("Form", "Render", None))
        self.pauseBtn.setText     (_translate ("Form", "Pause",  None))
        self.stopBtn.setText      (_translate ("Form", "Stop",   None))
        self.upBtn.setText        (_translate ("Form", "^",      None))
        self.downBtn.setText      (_translate ("Form", "v",      None))
        self.moreDownBtn.setText  (_translate ("Form", "+",      None))
        self.moreUpBtn.setText    (_translate ("Form", "-",      None))
        self.rightBtn.setText     (_translate ("Form", ">",      None))
        self.moreRightBtn.setText (_translate ("Form", "+",      None))
        self.leftBtn.setText      (_translate ("Form", "<",      None))
        self.furtherLeft.setText  (_translate ("Form", "-",      None))
        
        self.grid_switch.setText  (_translate ("Form", "Grid on/off", None))
        self.slider_label.setText (_translate ("Form", "Arrows size", None))
        
        self.connect (self.renderBtn,       SIGNAL ("clicked()"),        self.__fsm.startRendering)
        self.connect (self.pauseBtn,        SIGNAL ("clicked()"),        self.__fsm.pauseRendering)
        self.connect (self.stopBtn,         SIGNAL ("clicked()"),        self.__fsm.stopRendering)
        self.connect (self.arrowSizeSlider, SIGNAL ("sliderMoved(int)"), self.resizeArrows)
    
    def initLabel (self):
        
        color = QColor (250, 250, 250)
        self.image.fill (color)
        
        '''
        # test init
        for i in range (0, 200, 20):
            for x in range (i, i+20):
                for y in range (i, i+20):
                    self.image.setPixel (x,y, qRgb (0, 0, 0))
        '''
    
    def enableUIButtons (self, boolean_dict):
        '''
        method used by the debug state machine to manage the greyed-out state of buttons.
        '''
        b_dict = dict (boolean_dict)
        
        self.renderBtn.setEnabled    (b_dict['renderBtn'])
        self.pauseBtn.setEnabled     (b_dict['pauseBtn'])
        self.stopBtn.setEnabled      (b_dict['stopBtn'])
        self.upBtn.setEnabled        (b_dict['upBtn'])
        self.downBtn.setEnabled      (b_dict['downBtn'])
        self.moreDownBtn.setEnabled  (b_dict['moreDownBtn'])
        self.moreUpBtn.setEnabled    (b_dict['moreUpBtn'])
        self.rightBtn.setEnabled     (b_dict['rightBtn'])
        self.moreRightBtn.setEnabled (b_dict['moreRightBtn'])
        self.leftBtn.setEnabled      (b_dict['leftBtn'])
        self.furtherLeft.setEnabled  (b_dict['furtherLeft'])
        
        if b_dict['progressBar'] == 'completed':
            self.progressBar.setValue (100)
        elif b_dict['progressBar'] == 'reset':
            self.progressBar.reset ()
    
    def addScreenshot (self):
        '''
        it grabs a screenshot of OpenGL viewer and add it into the QImage instance.
        '''
        self.image = self.widget.grabFrameBuffer ()
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
    
    def prepAndStartEngineUp (self):
        '''
        it preps the engine and start it up.
        '''
        self.__engine.setImage (self.image)
        self.__engine.setCameraNormalMatrix (self.widget.getNormalMatrix(), self.widget.getFovy ())
        self.__engine.setModel (self.__model)
        self.__engine.start ()
    
    def addCamera (self): self.widget.addCamera ()
    def setIsStoppedFlag (self, boo):  self.__engine.setIsStoppedFlag (boo)
    def setIsPausedFlag  (self, boo):  self.__engine.setIsPausedFlag  (boo)
    def changeRenderBtnName (self, title):  self.renderBtn.setText (_translate ("Form", title, None))
    
    # listeners  - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
    
    def resizeArrows (self, e):
        self.widget.changeArrowsSize (e*0.5)
    def updateImage (self, e):
        self.pixmap_item = self.label_view.setPixmap (QPixmap.fromImage (self.image))
        self.progressBar.setValue (int(100*e))
    def displayGLMatrix (self, e):
        '''
        this method is registered to the MatrixChanged event fired from the OGLViewer
        component. It prints the model matrix. Only for debugging purposes.
        '''
        pass
Exemple #56
0
class NotUsedAnalysisProgress(QDialog):
    " Progress of the not used analysis "

    Functions = 0
    Classes = 1
    Globals = 2

    def __init__(self, what, sourceModel, parent=None):
        QDialog.__init__(self, parent)

        if what not in [self.Functions, self.Classes, self.Globals]:
            raise Exception( "Unsupported unused analysis type: " + \
                             str( what ) )

        self.__cancelRequest = False
        self.__inProgress = False

        self.__what = what  # what is in source model
        self.__srcModel = sourceModel  # source model of globals or
        # functions or classes

        # Avoid pylint complains
        self.__progressBar = None
        self.__infoLabel = None
        self.__foundLabel = None
        self.__found = 0  # Number of found

        self.__createLayout()
        self.setWindowTitle(self.__formTitle())
        QTimer.singleShot(0, self.__process)
        return

    def keyPressEvent(self, event):
        " Processes the ESC key specifically "
        if event.key() == Qt.Key_Escape:
            self.__onClose()
        else:
            QDialog.keyPressEvent(self, event)
        return

    def __formTitle(self):
        " Forms the progress dialog title "
        title = "Unused "
        if self.__what == self.Functions:
            title += 'function'
        elif self.__what == self.Classes:
            title += 'class'
        else:
            title += 'globlal variable'
        return title + " analysis"

    def __formInfoLabel(self, name):
        " Forms the info label "
        if self.__what == self.Functions:
            return 'Function: ' + name
        if self.__what == self.Classes:
            return 'Class: ' + name
        return 'Globlal variable: ' + name

    def __whatAsString(self):
        " Provides 'what' as string "
        if self.__what == self.Functions:
            return 'function'
        if self.__what == self.Classes:
            return 'class'
        return 'global variable'

    def __updateFoundLabel(self):
        " Updates the found label "
        text = "Found: " + str(self.__found) + " candidate"
        if self.__found != 1:
            text += "s"
        self.__foundLabel.setText(text)
        return

    def __createLayout(self):
        """ Creates the dialog layout """

        self.resize(450, 20)
        self.setSizeGripEnabled(True)

        verticalLayout = QVBoxLayout(self)

        # Note label
        noteLabel = QLabel( "<b>Note</b>: the analysis is " \
                            "suggestive and not precise. " \
                            "Use the results with caution.\n", self )
        verticalLayout.addWidget(noteLabel)

        # Info label
        self.__infoLabel = QLabel(self)
        verticalLayout.addWidget(self.__infoLabel)

        # Progress bar
        self.__progressBar = QProgressBar(self)
        self.__progressBar.setValue(0)
        self.__progressBar.setOrientation(Qt.Horizontal)
        verticalLayout.addWidget(self.__progressBar)

        # Found label
        self.__foundLabel = QLabel(self)
        verticalLayout.addWidget(self.__foundLabel)

        # Buttons
        buttonBox = QDialogButtonBox(self)
        buttonBox.setOrientation(Qt.Horizontal)
        buttonBox.setStandardButtons(QDialogButtonBox.Close)
        verticalLayout.addWidget(buttonBox)

        buttonBox.rejected.connect(self.__onClose)
        return

    def __onClose(self):
        " triggered when the close button is clicked "

        self.__cancelRequest = True
        if not self.__inProgress:
            self.close()
        return

    def __process(self):
        " Analysis process "

        self.__inProgress = True

        mainWindow = GlobalData().mainWindow
        editorsManager = mainWindow.editorsManagerWidget.editorsManager
        modified = editorsManager.getModifiedList(
            True)  # True - only project files
        if modified:
            modNames = [modItem[0] for modItem in modified]
            label = "File"
            if len(modified) >= 2:
                label += "s"
            label += ": "
            logging.warning( "The analisys is performed for the content of saved files. " \
                             "The unsaved modifications will not be taken into account. " \
                             + label + ", ".join( modNames ) )

        self.__updateFoundLabel()
        self.__progressBar.setRange(0,
                                    len(self.__srcModel.rootItem.childItems))
        QApplication.processEvents()
        QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))

        count = 0
        candidates = []
        for treeItem in self.__srcModel.rootItem.childItems:
            if self.__cancelRequest:
                break

            name = str(treeItem.data(0)).split('(')[0]
            path = os.path.realpath(treeItem.getPath())
            lineNumber = int(treeItem.data(2))
            absPosition = treeItem.sourceObj.absPosition

            count += 1
            self.__progressBar.setValue(count)
            self.__infoLabel.setText(self.__formInfoLabel(name))
            QApplication.processEvents()

            # Analyze the name
            found = False
            try:
                # True is for throwing exceptions
                locations = getOccurrences(path, absPosition, True)

                if len( locations ) == 1 and \
                   locations[ 0 ][ 1 ] == lineNumber:
                    found = True
                    index = getSearchItemIndex(candidates, path)
                    if index < 0:
                        widget = mainWindow.getWidgetForFileName(path)
                        if widget is None:
                            uuid = ""
                        else:
                            uuid = widget.getUUID()
                        newItem = ItemToSearchIn(path, uuid)
                        candidates.append(newItem)
                        index = len(candidates) - 1
                    candidates[index].addMatch(name, lineNumber)

            except Exception, exc:
                # There is nothing interesting with exceptions here.
                # It seems to me that rope throws them in case if the same item
                # is declared multiple times in a file. I also suspect that
                # exceptions may come up in case of syntactic errors.
                # So I just suppress them.
                pass

                #logging.warning( "Error detected while analysing " + \
                #                 self.__whatAsString() + " '" + name + \
                #                 "'. Message: " + str( exc ) )

            if found:
                self.__found += 1
                self.__updateFoundLabel()
            QApplication.processEvents()

        if self.__found == 0:
            # The analysis could be interrupted
            if not self.__cancelRequest:
                logging.info("No unused candidates found")
        else:
            mainWindow.displayFindInFiles("", candidates)

        QApplication.restoreOverrideCursor()
        self.__infoLabel.setText('Done')
        self.__inProgress = False

        self.accept()
        return