Example #1
0
class DelayWidget(WebWidget):
	def __init__(self, name, cfg, parent = None):
		WebWidget.__init__(self, name, parent)

		self.config = cfg

		self.url.setUrl(self.config.loadLinks()[str(self.objectName())]['data'])

		self.timer = QTimer(self)
		self.timer.setInterval(1000)
		self.timer.setSingleShot(1)

		self.timeoutTimer = QTimer(self)
		self.timeoutTimer.setInterval(10000)
		self.timeoutTimer.setSingleShot(1)

		self.connect(self.timeoutTimer , SIGNAL('timeout()') , self.clear)
		self.connect(self.timer        , SIGNAL('timeout()') , self.reload_)
		self.connect(self              , SIGNAL('done()')    , self.clear)

	def clear(self):
		self.config.saveDelayWidgetBusy(False)

	def reload_(self):
		if not self.isVisible(): return
		if not self.timeoutTimer.isActive():
			self.timeoutTimer.start()
		if self.config.loadDelayWidgetBusy():
			self.timer.start()
		else:
			self.timeoutTimer.stop()
			self.config.saveDelayWidgetBusy(True)
			WebWidget.reload_(self)
def show():
    import numpy as np

    import sys , h5py ; from numpy import float32 , uint8
    from vigra.filters import hessianOfGaussianEigenvalues , gaussianSmoothing
    from vigra.analysis import watersheds
    from vigra.analysis import labelVolumeWithBackground, extendedLocalMinima3D
    from PyQt4.QtCore import QTimer ; from PyQt4 . QtGui import QApplication
    app = QApplication ( sys.argv )
    from volumina.api import Viewer
    v = Viewer ()
    v . title = " Volumina Demo "
    v . showMaximized ()
    print "blubb"

    print a

    data = np.random.random((50,50,50))

    v . addGrayscaleLayer ( data , name =" raw data ")

    t = QTimer ()
    t.setInterval (200)

    app.exec_ ()
Example #3
0
class CalendarWidget(QFrame):
    def __init__(self, parent = None):
        QFrame.__init__(self, parent)
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.updateCurrentDateTime)
        self.timer.start()

    def paintEvent(self, event):
        QFrame.paintEvent(self, event)
        text = QDateTime.currentDateTime().toString(Qt.SystemLocaleLongDate)
        logicalRect = QRectF(QPointF(0, 0), QSizeF(QFontMetrics(self.font()).size(Qt.TextSingleLine, text)))
        physicalRect, frameWidth = QRectF(self.rect()), self.frameWidth()
        physicalRect.adjust(frameWidth, frameWidth, -frameWidth, -frameWidth)
        scaleForWidth = physicalRect.width() / logicalRect.width()
        scaleForHeight = physicalRect.height() / logicalRect.height()
        logicalRect.moveTo(frameWidth / scaleForWidth , frameWidth / scaleForHeight)

        painter = QStylePainter(self)
        painter.scale(scaleForWidth, scaleForHeight)
        painter.drawText(logicalRect, Qt.AlignCenter, text)

    def updateCurrentDateTime(self):
        if self.isVisible():
            self.update()
class ErrorMessageFilter(QObject):
    """
    In a parallel program, the same error may occur in several threads in close succession.
    For example, all slice views will notice a "filter too large" error simultaneously.
    This class collects error messages for a certain time (currently: 200ms) and then
    displays each unique message only once.
    """
    def __init__(self, parent):
        super(QObject, self).__init__(parent)
        self.messages = {}
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(200)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timeout)
        
    def showErrorMessage(self, caption, text):
        if not self.timer.isActive():
            self.timer.start()
        self.messages[text] = caption
        
    def timeout(self):
        for text, caption in self.messages.iteritems():
            QMessageBox.critical(self.parent(), caption, text)
        self.messages = {}
        
Example #5
0
    def _check_path_exists(self, path, text_box):
        #Validates if the specified folder exists
        dir = QDir()

        if not dir.exists(path):
            msg = self.tr(u"'{0}' directory does not exist.".format(path))
            self.notif_bar.insertErrorNotification(msg)

            #Highlight textbox control
            text_box.setStyleSheet(INVALIDATESTYLESHEET)

            timer = QTimer(self)
            #Sync interval with that of the notification bar
            timer.setInterval(self.notif_bar.interval)
            timer.setSingleShot(True)

            #Remove previous connected slots (if any)
            receivers = timer.receivers(SIGNAL('timeout()'))
            if receivers > 0:
                self._timer.timeout.disconnect()

            timer.start()
            timer.timeout.connect(lambda:self._restore_stylesheet(
                text_box)
            )

            return False

        return True
class DeviceReader(QThread):
    """Used for polling data from the Input layer during configuration"""
    raw_axis_data_signal = pyqtSignal(object)
    raw_button_data_signal = pyqtSignal(object)
    mapped_values_signal = pyqtSignal(object)

    def __init__(self, input):
        QThread.__init__(self)

        self._input = input
        self._read_timer = QTimer()
        self._read_timer.setInterval(25)

        self.connect(self._read_timer, SIGNAL("timeout()"), self._read_input)

    def stop_reading(self):
        """Stop polling data"""
        self._read_timer.stop()

    def start_reading(self):
        """Start polling data"""
        self._read_timer.start()

    def _read_input(self):
        [rawaxis, rawbuttons, mapped_values] = self._input.read_raw_values()
        self.raw_axis_data_signal.emit(rawaxis)
        self.raw_button_data_signal.emit(rawbuttons)
        self.mapped_values_signal.emit(mapped_values)
Example #7
0
class StartPage(QWidget):
    """ Interfáz QML """

    def __init__(self):
        QWidget.__init__(self)
        box = QVBoxLayout(self)
        box.setContentsMargins(0, 0, 0, 0)
        view = QDeclarativeView()
        view.setMinimumSize(400, 400)
        qml = os.path.join(paths.PATH, "ui", "StartPage.qml")
        path = QDir.fromNativeSeparators(qml)
        view.setSource(QUrl.fromLocalFile(path))
        view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
        self._root = view.rootObject()
        box.addWidget(view)

        self._current_text = ""
        # Timer
        self.timer = QTimer(self)
        self.timer.setInterval(3000)
        self._show_welcome_text()
        self.timer.timeout.connect(self._show_text)
        self.timer.start()

    def _show_welcome_text(self):
        self._root.show_text(WELCOME)

    def _show_text(self):
        if not self._current_text:
            self.timer.setInterval(7000)
        result = random.choice(TEXTS)
        # Para evitar que se repita
        if result != self._current_text:
            self._root.show_text(result)
        self._current_text = result
class TarayiciTaramaBaslat(QtGui.QWidget):
	def __init__(self,parent=None):
		super(TarayiciTaramaBaslat, self).__init__(parent)
		self.timer = QTimer(self)
		self.timer.timeout.connect(self.time)
		self.timer.setInterval(1000)
		self.timer.start()
		print("timer başladı")

		google=GoogleTaramayaBasla(parent=self)
		mozilla=MozillaTaramayaBasla(parent=self)

		self.mozillaMaxHistoryId=int(MozillaDatabaseController.mozillaMaxIdGetir())
		self.googleMaxHistoryId=GoogleDatabaseController.googleMaxIdGetir()

	def time(self):
		if(User.uid == ""):
			print("timer durdu")
			self.timer.deleteLater()
			self.timer.destroyed()
		mozilla=MozillaTaramayaBasla(parent=self)
		self.mozillaMaxHistoryId=mozilla.tara(mozillaMaxHistoryId=self.mozillaMaxHistoryId)

		google=GoogleTaramayaBasla(parent=self)
		self.googleMaxHistoryId=google.tara(googleMaxHistoryId=self.googleMaxHistoryId)
Example #9
0
 def __init__(self, thread, parent):
     QDialog.__init__(self, parent)
     self.ui = Ui_PlotPreview()
     self.ui.setupUi(self)
     self.parent = parent
     icon = QIcon()
     icon.addPixmap(QPixmap(":/icons/reload.png"), QIcon.Normal, QIcon.Off)
     self.update_btn = QPushButton(icon, "Update")
     self.ui.buttonBox.addButton(self.update_btn, QDialogButtonBox.ApplyRole)
     self.update_btn.clicked.connect(self.render_image)
     self._pix = None
     self._image_list = None
     self._thread = thread
     self.scene = QGraphicsScene()
     self.scene.setSceneRect(0,0,1,1)
     self.ui.imageView.setScene(self.scene)
     self.pix_item = None
     self.ui.imageView.setEnabled(False)
     self.ui.imageView.setInteractive(False)
     self.ui.imageView.setDragMode(QGraphicsView.ScrollHandDrag)
     self.pic_w = None
     self.pic_c = None
     self.show_pic_w = None
     self.show_pic_c = None
     timer = QTimer(self)
     timer.setSingleShot(True)
     timer.setInterval(500)
     self.timer = timer
     timer.timeout.connect(self.render_image)
     if parameters.instance.use_OpenGL:
         self.ui.imageView.setViewport(QGLWidget(QGLFormat(QGL.SampleBuffers)))
Example #10
0
class GenericTerminalOutputBox(QtGui.QLineEdit):
    def __init__(self) -> None:
        super().__init__()
        self.animate = False
        self.timer = QTimer(self)
        self.timer.setInterval(5)
        self.timer.timeout.connect(self._add_character)
        self.buffer = ""

    def set_timer_interval(self, num: int) -> None:
        self.timer.setInterval(num)

    def _add_character(self) -> None:
        if not self.buffer:
            self.timer.stop()
            return
        super().setText(self.text() + self.buffer[0])
        self.buffer = self.buffer[1:]

    def setText(self, text: str) -> None:
        if not self.animate or not text:
            super().setText(text)
            return
        super().setText(text[0])
        if len(text) > 1:
            self.buffer = text[1:]
            self.timer.start()
 def __init__(self, parent, logger, pic_url=None, fallback_pic=None, smooth_scaling=False, update=False, timeout=0, no_proxy=False):
     """Constructor
     
     @param parent: parent QObject
     @param pic_url -- URL to download and display
     @param fallback_pic -- Picture to display if pic_url is not yet downloaded or is not available
     @param smooth_scaling -- Use a smooth image resizing algorithm (slower)
     @param update -- automatically update periodically
     @param timeout -- number of seconds between updates
     @param no_proxy -- True to disable proxy for pic_url
     """
     super(ResizingWebImageLabel, self).__init__(parent, logger, smooth_scaling, QSize(640, 480))
     
     self.fallback_pic = fallback_pic
     self.pic_url = pic_url
     self.pic_path = None
     self.no_proxy = no_proxy
     
     self.displayFallbackPic()
             
     self.timeout = int(timeout)*1000
     if update:
         updateImageTimer = QTimer(self)
         updateImageTimer.setInterval(self.timeout)
         updateImageTimer.timeout.connect(self.update)
         updateImageTimer.start(self.timeout)
Example #12
0
File: gps.py Project: skeenp/Roam
class FileGPSService(GPSService):
    def __init__(self, filename):
        super(FileGPSService, self).__init__()
        self.file = None
        self.timer = QTimer()
        self.timer.setInterval(100)
        self.timer.timeout.connect(self._read_from_file)
        self.filename = filename

    def connectGPS(self, portname):
        # Normally the portname is passed but we will take a filename
        # because it's a fake GPS service  
        if not self.isConnected:
            self.file = open(self.filename, "r")
            self.timer.start()
            self.isConnected = True

    def _read_from_file(self):
        line = self.file.readline()
        if not line:
            self.file.seek(0)
            line = self.file.readline()
        self.parse_data(line)

    def disconnectGPS(self):
        if self.file:
            self.file.close()
        self.timer.stop()
        self.file = None
        self.gpsdisconnected.emit()
Example #13
0
class Stopper(QObject):
    start_timer = pyqtSignal()
    stop_timer = pyqtSignal()

    def __init__(self):
        super(Stopper, self).__init__()

        print "current thread 2 %r" % QThread.currentThread()
        self.timer = QTimer()
        self.thread_of_timer = self.timer.thread()
        print "stopper.timer thread: %r" % self.thread_of_timer
        self.timer.setInterval(1000)
        self.timer.timeout.connect(self.prnt_msg)
        self.start_timer.connect(self.start)
        self.stop_timer.connect(self.stop)

    def start(self):
        print "starting"
        self.timer.start()

    def stop(self):
        print "stopping"
        print QThread.currentThread()
        print self.thread()
        print self.timer.thread()
        print "Timer thread has changed: %s" % (self.thread_of_timer is self.timer.thread())
        self.timer.stop()

    def prnt_msg(self):
        print "timer running"
Example #14
0
 def register_timer(self, time_delta, callback):
     """Registers a callback function to be run after time_delta ms."""
     timer = QTimer(self.window)
     timer.setSingleShot(True)
     timer.timeout.connect(callback)
     timer.setInterval(time_delta)
     timer.start()
Example #15
0
def ask_password_dialog(parent, title, prompt, timeout = None):
    if parent is None:
        app = qt4tools.create_qapplication()
        translator = qt4tools.get_translator()
        app.installTranslator(translator)

    import icon
    dialog = QInputDialog()

    timer = QTimer()
    if not timeout is None:
        dialog.connect(timer, SIGNAL("timeout()"), dialog.reject)
        timer.setInterval(timeout * 1000)
        timer.start()

    dialog.setWindowIcon(icon.BIT_LOGO)
    dialog.setWindowTitle(title)
    dialog.setLabelText(prompt)
    dialog.setTextEchoMode(QLineEdit.Password)
    QApplication.processEvents()

    ret = dialog.exec_()

    timer.stop()
    if ret:
        password = dialog.textValue()
    else:
        password = ''
    del(dialog)

    return(password)
Example #16
0
class Plugin:
  def __init__(self):
    self.timer = QTimer(None)
    self.timer.setInterval(10000)
    self.timer.timeout.connect(self.Timeout)
    self.timer.setSingleShot(True)
    self.action = QAction("Preview mode", None)
    self.action.setCheckable(True)
    self.action.triggered.connect(self.Enabled)
    clementine.ui.AddAction("playlist_menu", self.action)
    clementine.player.Playing.connect(self.Playing)
    clementine.player.Paused.connect(self.Stopped)
    clementine.player.Stopped.connect(self.Stopped)
    self.enabled = False

  def Enabled(self, enabled):
    self.enabled = enabled
    if enabled:
      if clementine.player.GetState() == 2:  # Playing
        self.timer.start()
    else:
      self.timer.stop()

  def Playing(self):
    if self.enabled:
      self.timer.start()

  def Stopped(self):
    self.timer.stop()

  def Timeout(self):
    if clementine.player.GetState() == 2:
      clementine.player.Next()
class ErrorMessageFilter(QObject):
    """
    In a parallel program, the same error may occur in several threads in close succession.
    For example, all slice views will notice a "filter too large" error simultaneously.
    This class collects error messages for a certain time (currently: 1000ms) and then
    displays each unique message only once.
    """
    def __init__(self, parent):
        super(QObject, self).__init__(parent)
        self.messages = {}
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(1000)
        self.connect(self.timer, QtCore.SIGNAL("timeout()"), self.timeout)
        
    def showErrorMessage(self, caption, text):
        if not self.timer.isActive():
            self.timer.start()
        self.messages[caption] = text
        
    def timeout(self):
        # Must copy now because the eventloop is allowed to run during QMessageBox.critical, below.
        # That is, self.messages might change while the loop is executing (not allowed).
        messages = copy.copy(self.messages)
        for caption, text in messages.iteritems():
            QMessageBox.critical(self.parent(), caption, text)
        self.messages = {}
        
Example #18
0
class LabelableSegmentationEdgesLayer( SegmentationEdgesLayer ):
    """
    Shows a set of user-labeled edges.
    """
    
    labelsChanged = pyqtSignal( dict ) # { id_pair, label_class }
    
    def __init__(self, datasource, label_class_pens, initial_labels={}, delay_ms=1000):
        # Class 0 (no label) is the default pen
        super(LabelableSegmentationEdgesLayer, self).__init__( datasource, default_pen=label_class_pens[0] )
        self._delay_ms = delay_ms
        self._label_class_pens = label_class_pens

        # Initialize the labels and pens
        self.overwrite_edge_labels(initial_labels)
        
        self._buffered_updates = {}

        # To avoid sending lots of single updates if the user is clicking quickly,
        # we buffer the updates into a dict that is only sent after a brief delay.
        self._timer = QTimer(self)
        self._timer.setInterval(self._delay_ms)
        self._timer.setSingleShot(True)
        self._timer.timeout.connect( self._signal_buffered_updates )

    def overwrite_edge_labels(self, new_edge_labels):
        self._edge_labels = defaultdict(lambda: 0, new_edge_labels)

        # Change the pens accordingly
        pen_table = {}
        for id_pair, label_class in self._edge_labels.items():
            pen_table[id_pair] = self._label_class_pens[label_class]
        self.pen_table.overwrite(pen_table)
    
    def handle_edge_clicked(self, id_pair):
        """
        Overridden from SegmentationEdgesLayer
        """
        num_classes = len(self._label_class_pens)
        old_class = self._edge_labels[id_pair]
        new_class = (old_class+1) % num_classes

        # Update the display
        self.pen_table[id_pair] = self._label_class_pens[new_class]

        # For now, edge_labels dictionary will still contain 0-labeled edges.
        # We could delete them, but why bother?
        self._edge_labels[id_pair] = new_class

        # Buffer the update for listeners
        self._buffered_updates[id_pair] = new_class
        
        # Reset the timer
        self._timer.start()

    def _signal_buffered_updates(self):
        updates = self._buffered_updates
        self._buffered_updates = {}
        self.labelsChanged.emit( updates )
        
Example #19
0
class PreviewEnabledRenderingFunction(object):
    def __init__(self, scene, timeout=250):
        self.scene = scene
        self._fine_rendering_allocated_time = None
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._timer.setInterval(timeout)
        QObject.connect(self._timer, SIGNAL('timeout()'), self.render)

    def abort_rendering(self):
        self._timer.stop()
        if self._fine_rendering_allocated_time is not None:
            self.scene.renderer.allocated_render_time = \
                self._fine_rendering_allocated_time
            self._fine_rendering_allocated_time = None

    def render(self):
        self.scene.renderer.allocated_render_time = \
            self._fine_rendering_allocated_time
        self.scene.render()

    def render_preview(self):
        self._fine_rendering_allocated_time = \
            self.scene.renderer.allocated_render_time
        self.scene.renderer.allocated_render_time = 0
        self.scene.render()
        self._timer.start()

    def __call__(self):
        self.render_preview()
Example #20
0
class UpTimeWidget(QLabel):

    def __init__(self):
        super(UpTimeWidget, self).__init__()
        self.setObjectName("status_label")
        self.setStyleSheet("font: 10pt;")
        # Inicio
        self.tiempo = 0

        self.lbl_tiempo = "Tiempo: %smin"
        self.setText(self.tr(self.lbl_tiempo % (0)))

        # Timer
        self.timer = QTimer()
        self.timer.setInterval(60000)
        self.timer.timeout.connect(self.actualizar_tiempo)
        self.timer.start()

    def actualizar_tiempo(self):
        """ Actualiza el label cada 60 segundos """

        self.tiempo += 1
        if self.tiempo == 60:
            tiempo = "1hr"
        elif self.tiempo > 60:
            horas = int(str(self.tiempo / 60).split('.')[0])
            hora = str(horas) + "hs"
            minutos = str(self.tiempo - (horas * 60)) + "min"
            tiempo = hora + minutos
        else:
            tiempo = str(self.tiempo) + "min"
        self.setText(self.tr("Tiempo: %s" % tiempo))
Example #21
0
class QnoteroQuery(QLineEdit):

	"""The search input box"""

	def __init__(self, qnotero):
	
		"""
		Constructor
		
		Arguments:
		qnotero -- a Qnotero instance
		"""		
	
		QLineEdit.__init__(self, qnotero)
		self.qnotero = qnotero
		self.timer = QTimer(self)
		self.needUpdate = True		
		self.textChanged.connect(self._textChanged)

	def keyPressEvent(self, e):
	
		"""
		Handle key presses
		
		Arguments:
		e -- a QKeyEvent
		"""
	
		if e.key() == Qt.Key_Return:
			self.qnotero.search(setFocus=False)
			return
		if e.key() == Qt.Key_Down:
			if self.needUpdate:
				self.qnotero.search(setFocus=True)								
			elif self.qnotero.ui.listWidgetResults.count() > 0:
				self.qnotero.ui.listWidgetResults.setFocus()
			self.qnotero.ui.listWidgetResults.setCurrentItem( \
				self.qnotero.ui.listWidgetResults.item(0))
			return
		
		QLineEdit.keyPressEvent(self, e)		
		self.timer.stop()
		self.timer = QTimer(self)
		self.timer.setSingleShot(True)
		self.timer.setInterval(getConfig("autoFire"))
		self.timer.timeout.connect(self.search)
		self.timer.start()

	def search(self):
	
		"""Perform a search without losing focus"""
				
		self.qnotero.search(setFocus=False)		
		
	def _textChanged(self):
	
		"""Set the needUpdate flag"""
		
		self.needUpdate = True
Example #22
0
 def __init__(self, text, parent=None):
     super(PopupButton, self).__init__(text, parent)
     timer = QTimer()
     timer.setSingleShot(True)
     timer.setInterval(500)
     timer.timeout.connect(self.showPopup)
     self.timer = timer
     self.popup = None
Example #23
0
 def _poll(self):
     self.ad_status.fetch_data(self.mainwindow.client)
     timer = QTimer()
     timer.setSingleShot(True)
     timer.setInterval(20000) # ms
     timer.start()
     self.connect(timer, SIGNAL('timeout()'), self._poll)
     self.connect(self, SIGNAL('destroyed()'), timer.stop)
Example #24
0
    def __init__(self, run_model):
        QDialog.__init__(self)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)
        self.setModal(True)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, SimulationRunner)
        self.run_model = run_model
        self.run_model.observable().attach(SimulationRunner.SIMULATION_FINISHED_EVENT, self.simulationFinished.emit)


        layout = QVBoxLayout()
        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.simulations_tracker = SimulationsTracker()
        self.simulations_tracker.observable().attach(SimulationsTracker.LIST_CHANGED_EVENT, self.statusChanged)
        states = self.simulations_tracker.getList()

        self.progress = Progress()

        for state in states:
            self.progress.addState(state.state, QColor(*state.color), 100.0 * state.count / state.total_count)

        layout.addWidget(self.progress)

        legend_layout = QHBoxLayout()

        for state in states:
            legend_layout.addWidget(Legend(state.name, QColor(*state.color)))

        layout.addLayout(legend_layout)

        self.running_time = QLabel("")

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)

        layout.addStretch()
        layout.addLayout(button_layout)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)
        self.simulationFinished.connect(self.hideKillAndShowDone)

        timer = QTimer(self)
        timer.setInterval(500)
        timer.timeout.connect(self.setRunningTime)
        timer.start()
Example #25
0
    def schedule(self, interval, function, *args):
        timer = QTimer()
        timer.setInterval(interval * 1000)
        timer.setSingleShot(True)

        self.params[timer] = (None, function, args)

        timer.start()
        timer.timeout.connect(self.timeout)
class SignalStream(QObject):
    '''SignalStream is a file-like object that emits a text signal on writing

    This class is used to provide threadsafe communication of data to the GUI.
    A SignalStream can be used in place of sys.stdout and the instance's 
    write_signal can be connected to a slot that processes the text to where it
    ought to go.  Since signals and slots are threadsafe, this lets you pass
    text from anywhere to anywhere reasonably safely

    SignalStream uses some intelligent buffering to prevent the signalstorm that
    happened the first time I used it.  Signal emit only happens when flush()
    is called - so an application can force a flush - but in order to make sure
    that happens reasonable often SignalStream can be initialized with a QTimer
    on an interval (default: 100ms) and the QTimer will make sure to call flush()
    every 100ms.
    '''

    write_signal = pyqtSignal(str)

    def __init__(self, interval_ms=100):
        '''Create a SignalStream that emits text at least every interval_ms'''

        super(SignalStream, self).__init__()
        self.mutex = QMutex()

        self.data = []
        self.thread = QThread()

        self.pbar_timer = QTimer()
        self.pbar_timer.moveToThread(self.thread)
        self.pbar_timer.setInterval(interval_ms)
        self.pbar_timer.timeout.connect(self.flush)
        self.thread.started.connect(self.pbar_timer.start)
        self.thread.start()

    def __del__(self):
        self.thread.quit()
        self.thread.wait()

    def write(self, m):
        '''Add the message in m to this stream's cache'''
        locker = QMutexLocker(self.mutex)

        self.data.append(m)

    @pyqtSlot()
    def flush(self):
        '''Write all data in the stream and clear the stream's cache'''
        locker = QMutexLocker(self.mutex)

        if self.data:
            self.write_signal.emit(''.join(self.data))
            self.data = []

    def set_interval(self, interval_ms):
        '''Alter the pbar_timer period'''
        self.pbar_timer.setInteval(interval_ms)
Example #27
0
class Tracker(QObject):
    sig_error = pyqtSignal(str)
    sig_started = pyqtSignal()
    sig_inview = pyqtSignal(bool) # True if in view, else False

    def __init__(self, parent):
        super(Tracker, self).__init__(parent)
        self.name = self.__class__.__name__

        # Ros Stuff
        self.sub_tf = parent.sub_tf
        self.pub_tf = parent.pub_tf

        # Timer that checks if we have failed to start
        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.failed)
        self.timeout = 2000 #ms
        self.timer.setInterval(self.timeout)

    def started(self):
        """ Called when starting was possible """
        if self.timer.isActive():
            self.timer.stop()
            self.sig_started.emit()
            rospy.loginfo("Started [%s]" , self.name)



    def onStart(self):
        pass
    def getStartMsg(self):
        return "Default start msg.."
    def getFailMsg(self):
        return "Default fail msg"
    def onStop(self):
        pass


    def start(self):
        rospy.loginfo("Starting [%s]", self.name)
        self.timer.start()
        return self.onStart()

    def failed(self, msg=None):
        """ Called when starting not possible """
        if msg is None:
            msg = self.getFailMsg()
        self.sig_error.emit(msg)
        rospy.logerr("Failed to start [%s]: %s" , self.name, msg)
        self.stop()

    def stop(self):
        self.timer.stop()
        rospy.loginfo("Stopping [%s]", self.name)
        self.onStop()
Example #28
0
class MitScheme(QObject):
    """MIT scheme shell. Implements REPL. Graphical frontend for original terminal version.
    """
    
    processIsRunningChanged = pyqtSignal(bool)
    """
    processStopped(isRunning)
    
    **Signal** emitted, when MIT Scheme process starts and stops
    """  # pylint: disable=W0105

    def __init__(self, interpreterPath):
        QObject.__init__(self)
        self._term = MitSchemeTermWidget(self)
        self._term.setLanguage('Scheme')
        self._interpreterPath = interpreterPath
        
        self._processOutputTimer = QTimer()  # I use Qt timer, because we must append data to GUI in the GUI thread
        self._processOutputTimer.timeout.connect(self._processOutput)
        self._processOutputTimer.setInterval(100)

        self._buffPopen = enki.lib.buffpopen.BufferedPopen(interpreterPath)
        self._schemeIsRunning = False
        
        self._term.appendOutput("Execute any command to run the scheme interpreter\n")

    def __del__(self):
        self.stop()
    
    def widget(self):
        """MIT Scheme emulator
        """
        return self._term

    def start(self):
        """Start scheme process
        """
        if self._schemeIsRunning:
            return

        try:
            self._buffPopen.start()
        except OSError, ex:
            text = '<p>Interpreter path: %s</p>' % self._interpreterPath
            text += '<p>Error: %s</p>' % unicode(str(ex), 'utf8')
            text += '<p>Make sure MIT Scheme is installed and go to '\
                    '<b>Settings -> Settings -> Modes -> MIT&nbsp;Scheme</b> to correct the path</p>'
            text = '<html>%s</html' % text
            QMessageBox.critical (core.mainWindow(),
                                  "Failed to run MIT Scheme", 
                                  text)
            raise UserWarning("Failed to run the interpreter")

        self._processOutputTimer.start()
        self._schemeIsRunning = True
        self.processIsRunningChanged.emit(self._schemeIsRunning)
Example #29
0
 def __create_bridge():
     """
     Creates the bridge for asyncore and Qt
     """
     timer = QTimer()
     bridge = __AsyncoreQtBridge(timer)
     timer.setInterval(0)
     timer.timeout.connect(bridge.pull)
     timer.start()
     return bridge
Example #30
0
    def schedule(self, interval, function, *args):
        timer = QTimer()
        timer.setInterval(interval * 1000)
        timer.setSingleShot(True)

        count = self.count
        self.count += 1

        timer.start()
        self.app.connect(timer, SIGNAL("timeout()"), lambda: self.timeout(count, None, function, *args))
        self.timers[count] = timer
Example #31
0
class _CameraWidget(QWidget):
    imagecaptured = pyqtSignal(QPixmap)
    done = pyqtSignal()

    def __init__(self, parent=None):
        super(_CameraWidget, self).__init__(parent)
        self.cameralabel = QLabel()
        self.cameralabel.setScaledContents(True)
        self.setLayout(QGridLayout())
        self.toolbar = QToolBar()
        self.swapaction = self.toolbar.addAction("Swap Camera")
        self.swapaction.triggered.connect(self.swapcamera)
        self.cameralabel.mouseReleaseEvent = self.takeimage
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.toolbar)
        self.layout().addWidget(self.cameralabel)
        self.timer = QTimer()
        self.timer.setInterval(20)
        self.timer.timeout.connect(self.showimage)
        self.cam = None
        self.pixmap = None
        self.currentdevice = 1

    def swapcamera(self):
        self.stop()
        if self.currentdevice == 0:
            self.start(1)
        else:
            self.start(0)

    def showimage(self):
        if self.cam is None:
            return

        img = self.cam.getImage()
        self.image = ImageQt(img)
        pixmap = QPixmap.fromImage(self.image)
        self.cameralabel.setPixmap(pixmap)

    def takeimage(self, *args):
        self.timer.stop()

        img = self.cam.getImage()
        self.image = ImageQt(img)
        self.pixmap = QPixmap.fromImage(self.image)
        self.cameralabel.setPixmap(self.pixmap)
        self.imagecaptured.emit(self.pixmap)
        self.done.emit()

    def start(self, dev=1):
        try:
            self.cam = vc.Device(dev)
            self.currentdevice = dev
        except vidcap.error:
            if dev == 0:
                utils.error("Could not start camera")
                return
            self.start(dev=0)
            return

        self.timer.start()

    def stop(self):
        self.timer.stop()
        del self.cam
        self.cam = None
Example #32
0
class SolidStateRelayV2(COMCUPluginBase, Ui_SolidStateRelayV2):
    qtcb_monoflop = pyqtSignal(bool)

    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletSolidStateRelayV2, *args)

        self.setupUi(self)

        self.ssr = self.device

        self.qtcb_monoflop.connect(self.cb_monoflop)
        self.ssr.register_callback(self.ssr.CALLBACK_MONOFLOP_DONE,
                                   self.qtcb_monoflop.emit)

        self.ssr_button.clicked.connect(self.ssr_clicked)
        self.go_button.clicked.connect(self.go_clicked)

        self.monoflop = False
        self.timebefore = 500

        self.a_pixmap = load_masked_pixmap(
            'plugin_system/plugins/solid_state_relay/relay_a.bmp')
        self.b_pixmap = load_masked_pixmap(
            'plugin_system/plugins/solid_state_relay/relay_b.bmp')

        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update)
        self.update_timer.setInterval(50)

    def get_state_async(self, state):
        width = self.ssr_button.width()
        if self.ssr_button.minimumWidth() < width:
            self.ssr_button.setMinimumWidth(width)

        s = state
        if s:
            self.ssr_button.setText('Switch Off')
            self.ssr_image.setPixmap(self.a_pixmap)
        else:
            self.ssr_button.setText('Switch On')
            self.ssr_image.setPixmap(self.b_pixmap)

    def get_monoflop_async(self, monoflop):
        state, time, time_remaining = monoflop
        if time > 0:
            self.timebefore = time
            self.time_spinbox.setValue(self.timebefore)
        if time_remaining > 0:
            if not state:
                self.state_combobox.setCurrentIndex(0)
            self.monoflop = True
            self.time_spinbox.setEnabled(False)
            self.state_combobox.setEnabled(False)

    def start(self):
        async_call(self.ssr.get_state, None, self.get_state_async,
                   self.increase_error_count)
        async_call(self.ssr.get_monoflop, None, self.get_monoflop_async,
                   self.increase_error_count)
        self.update_timer.start()

    def stop(self):
        self.update_timer.stop()

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletSolidStateRelayV2.DEVICE_IDENTIFIER

    def ssr_clicked(self):
        width = self.ssr_button.width()
        if self.ssr_button.minimumWidth() < width:
            self.ssr_button.setMinimumWidth(width)

        if 'On' in self.ssr_button.text():
            self.ssr_button.setText('Switch Off')
            self.ssr_image.setPixmap(self.a_pixmap)
        else:
            self.ssr_button.setText('Switch On')
            self.ssr_image.setPixmap(self.b_pixmap)

        state = not 'On' in self.ssr_button.text()
        try:
            self.ssr.set_state(state)
        except ip_connection.Error:
            return

        self.monoflop = False
        self.time_spinbox.setValue(self.timebefore)
        self.time_spinbox.setEnabled(True)
        self.state_combobox.setEnabled(True)

    def go_clicked(self):
        time = self.time_spinbox.value()
        state = self.state_combobox.currentIndex() == 0
        try:
            if self.monoflop:
                time = self.timebefore
            else:
                self.timebefore = self.time_spinbox.value()

            self.ssr.set_monoflop(state, time)

            self.monoflop = True
            self.time_spinbox.setEnabled(False)
            self.state_combobox.setEnabled(False)

            if state:
                self.ssr_button.setText('Switch Off')
                self.ssr_image.setPixmap(self.a_pixmap)
            else:
                self.ssr_button.setText('Switch On')
                self.ssr_image.setPixmap(self.b_pixmap)
        except ip_connection.Error:
            return

    def cb_monoflop(self, state):
        self.monoflop = False
        self.time_spinbox.setValue(self.timebefore)
        self.time_spinbox.setEnabled(True)
        self.state_combobox.setEnabled(True)
        if state:
            self.ssr_button.setText('Switch Off')
            self.ssr_image.setPixmap(self.a_pixmap)
        else:
            self.ssr_button.setText('Switch On')
            self.ssr_image.setPixmap(self.b_pixmap)

    def update_time_remaining(self, time_remaining):
        if self.monoflop:
            self.time_spinbox.setValue(time_remaining)

    def update(self):
        if self.monoflop:
            try:
                async_call(self.ssr.get_monoflop, None,
                           lambda a: self.update_time_remaining(a[2]),
                           self.increase_error_count)
            except ip_connection.Error:
                pass
Example #33
0
class Downloader(QObject):

    NOT_FOUND = 0
    NO_ERROR = 0
    TIMEOUT_ERROR = 4
    UNKNOWN_ERROR = -1

    def __init__(self, parent=None):
        QObject.__init__(self, parent)
        self.queue = []
        self.requestingUrls = []
        self.replies = []

        self.eventLoop = QEventLoop()
        self.sync = False
        self.fetchedFiles = {}
        self.clearCounts()

        self.timer = QTimer()
        self.timer.setSingleShot(True)
        self.timer.timeout.connect(self.fetchTimedOut)

        # network settings
        self.userAgent = "QuickMapServices tile layer (+https://github.com/nextgis/quickmapservices)"
        self.max_connection = 4
        self.default_cache_expiration = 24
        self.errorStatus = Downloader.NO_ERROR

    def clearCounts(self):
        self.fetchSuccesses = 0
        self.fetchErrors = 0
        self.cacheHits = 0

    def fetchTimedOut(self):
        self.log("Downloader.timeOut()")
        self.abort()
        self.errorStatus = Downloader.TIMEOUT_ERROR

    def abort(self):
        # clear queue and abort sent requests
        self.queue = []
        self.timer.stop()
        for reply in self.replies:
            reply.abort()
        self.errorStatus = Downloader.UNKNOWN_ERROR

    def replyFinished(self):
        reply = self.sender()
        url = reply.request().url().toString()
        self.log("replyFinished: %s" % url)
        if not url in self.fetchedFiles:
            self.fetchedFiles[url] = None
        self.requestingUrls.remove(url)
        self.replies.remove(reply)
        isFromCache = 0
        httpStatusCode = reply.attribute(
            QNetworkRequest.HttpStatusCodeAttribute)
        if reply.error() == QNetworkReply.NoError:
            self.fetchSuccesses += 1
            if reply.attribute(QNetworkRequest.SourceIsFromCacheAttribute):
                self.cacheHits += 1
                isFromCache = 1
            elif not reply.hasRawHeader("Cache-Control"):
                cache = QgsNetworkAccessManager.instance().cache()
                if cache:
                    metadata = cache.metaData(reply.request().url())
                    # self.log("Expiration date: " + metadata.expirationDate().toString().encode("utf-8"))
                    if metadata.expirationDate().isNull():
                        metadata.setExpirationDate(
                            QDateTime.currentDateTime().addSecs(
                                self.default_cache_expiration * 60 * 60))
                        cache.updateMetaData(metadata)
                        self.log(
                            "Default expiration date has been set: %s (%d h)" %
                            (url, self.default_cache_expiration))

            if reply.isReadable():
                data = reply.readAll()
                self.fetchedFiles[url] = data
            else:
                qDebug("http status code: " + str(httpStatusCode))
        else:
            if self.sync and httpStatusCode == 404:
                self.fetchedFiles[url] = self.NOT_FOUND
            self.fetchErrors += 1
            if self.errorStatus == self.NO_ERROR:
                self.errorStatus = self.UNKNOWN_ERROR

        self.emit(SIGNAL('replyFinished(QString, int, int)'), url,
                  reply.error(), isFromCache)
        reply.deleteLater()

        if debug_mode:
            qDebug("queue: %d, requesting: %d" %
                   (len(self.queue), len(self.requestingUrls)))

        if len(self.queue) + len(self.requestingUrls) == 0:
            # all replies have been received
            if self.sync:
                self.logT("eventLoop.quit()")
                self.eventLoop.quit()
            else:
                self.timer.stop()
        elif len(self.queue) > 0:
            # start fetching the next file
            self.fetchNext()
        self.log("replyFinished End: %s" % url)

    def fetchNext(self):
        if len(self.queue) == 0:
            return
        url = self.queue.pop(0)
        self.log("fetchNext: %s" % url)

        request = QNetworkRequest(QUrl(url))
        request.setRawHeader("User-Agent", self.userAgent)
        reply = QgsNetworkAccessManager.instance().get(request)
        reply.finished.connect(self.replyFinished)
        self.requestingUrls.append(url)
        self.replies.append(reply)
        return reply

    def fetchFiles(self, urlList, timeout_ms=0):
        self.log("fetchFiles()")
        self.sync = True
        self.queue = []
        self.clearCounts()
        self.errorStatus = Downloader.NO_ERROR
        self.fetchedFiles = {}

        if len(urlList) == 0:
            return self.fetchedFiles

        for url in urlList:
            self.addToQueue(url)

        for i in range(self.max_connection):
            self.fetchNext()

        if timeout_ms > 0:
            self.timer.setInterval(timeout_ms)
            self.timer.start()

        self.logT("eventLoop.exec_(): " + str(self.eventLoop))
        self.eventLoop.exec_()
        self.log("fetchFiles() End: %d" % self.errorStatus)
        if timeout_ms > 0:
            self.timer.stop()
        return self.fetchedFiles

    def addToQueue(self, url):
        if url in self.queue:
            return False
        self.queue.append(url)
        return True

    def queueCount(self):
        return len(self.queue)

    def finishedCount(self):
        return len(self.fetchedFiles)

    def unfinishedCount(self):
        return len(self.queue) + len(self.requestingUrls)

    def log(self, msg):
        if debug_mode:
            qDebug(msg)

    def logT(self, msg):
        if debug_mode:
            qDebug("%s: %s" % (str(threading.current_thread()), msg))

    def fetchFilesAsync(self, urlList, timeout_ms=0):
        self.log("fetchFilesAsync()")
        self.sync = False
        self.queue = []
        self.clearCounts()
        self.errorStatus = Downloader.NO_ERROR
        self.fetchedFiles = {}

        if len(urlList) == 0:
            return self.fetchedFiles

        for url in urlList:
            self.addToQueue(url)

        for i in range(self.max_connection):
            self.fetchNext()

        if timeout_ms > 0:
            self.timer.setInterval(timeout_ms)
            self.timer.start()
Example #34
0
class CAN(PluginBase, Ui_CAN):
    qtcb_frame_read = pyqtSignal(int, int, object, int)

    def __init__(self, *args):
        PluginBase.__init__(self, BrickletCAN, *args)

        self.setupUi(self)

        self.can = self.device

        self.qtcb_frame_read.connect(self.cb_frame_read)
        self.can.register_callback(self.can.CALLBACK_FRAME_READ,
                                   self.qtcb_frame_read.emit)

        self.last_filename = os.path.join(get_home_path(),
                                          'can_bricklet_history.log')

        self.filter_mask = 0
        self.filter1 = 0
        self.filter2 = 0

        self.frame_read_callback_was_enabled = False

        self.tree_frames.header().resizeSection(0, 150)
        self.tree_frames.header().resizeSection(1, 135)
        self.tree_frames.header().resizeSection(2, 135)
        self.tree_frames.header().resizeSection(3, 300)
        self.tree_frames.header().resizeSection(4, 100)

        self.edit_data.setValidator(HexValidator(max_bytes=8))

        self.combo_frame_type.currentIndexChanged.connect(
            self.frame_type_changed)
        self.combo_baud_rate.currentIndexChanged.connect(
            self.configuration_changed)
        self.combo_transceiver_mode.currentIndexChanged.connect(
            self.configuration_changed)
        self.spin_write_timeout.valueChanged.connect(
            self.configuration_changed)

        self.combo_filter_mode.currentIndexChanged.connect(
            self.filter_mode_changed)
        self.spin_filter_mask_extended.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter_mask_standard.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter_mask_data1.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter_mask_data2.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter1_extended.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter1_standard.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter1_data1.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter1_data2.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter2_extended.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter2_standard.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter2_data1.valueChanged.connect(
            self.mask_or_filter_changed)
        self.spin_filter2_data2.valueChanged.connect(
            self.mask_or_filter_changed)

        self.button_write_frame.clicked.connect(self.write_frame)
        self.button_clear_history.clicked.connect(self.tree_frames.clear)
        self.button_save_history.clicked.connect(self.save_history)
        self.button_save_configuration.clicked.connect(self.save_configuration)
        self.button_save_read_filter.clicked.connect(self.save_read_filter)

        self.error_log_timer = QTimer(self)
        self.error_log_timer.timeout.connect(self.update_error_log)
        self.error_log_timer.setInterval(1000)

        self.frame_type_changed()
        self.filter_mode_changed()

    def start(self):
        self.frame_read_callback_was_enabled = False

        async_call(self.can.is_frame_read_callback_enabled, None,
                   self.is_frame_read_callback_enabled_async,
                   self.increase_error_count)
        async_call(self.can.get_configuration, None,
                   self.get_configuration_async, self.increase_error_count)
        async_call(self.can.get_read_filter, None, self.get_read_filter_async,
                   self.increase_error_count)

        self.update_error_log()
        self.error_log_timer.start()

    def stop(self):
        self.error_log_timer.stop()

        if not self.frame_read_callback_was_enabled:
            try:
                self.can.disable_frame_read_callback()
            except:
                pass

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletCAN.DEVICE_IDENTIFIER

    def cb_frame_read(self, frame_type, identifier, data, length):
        parts = []
        max_length = 0
        extended = False

        if frame_type == self.can.FRAME_TYPE_STANDARD_DATA:
            parts.append('Standard Data')
            max_length = 8
        elif frame_type == self.can.FRAME_TYPE_STANDARD_REMOTE:
            parts.append('Standard Remote')
        elif frame_type == self.can.FRAME_TYPE_EXTENDED_DATA:
            parts.append('Extended Data')
            max_length = 8
            extended = True
        elif frame_type == self.can.FRAME_TYPE_EXTENDED_REMOTE:
            parts.append('Extended Remote')
            extended = True
        else:
            parts.append('Unknown')

        if extended:
            parts.append(
                self.spin_identifier_extended.textFromValue((identifier >> 11)
                                                            & 0x3FFFF))
        else:
            parts.append('')

        parts.append(
            self.spin_identifier_standard.textFromValue(identifier & 0x7FF))
        parts.append(' '.join(
            ['%02X' % c for c in data[:min(length, max_length)]]))
        parts.append(str(length))

        scroll_bar = self.tree_frames.verticalScrollBar()
        at_bottom = scroll_bar.value() == scroll_bar.maximum()

        self.tree_frames.addTopLevelItem(QTreeWidgetItem(parts))

        if at_bottom:
            self.tree_frames.scrollToBottom()

    def is_frame_read_callback_enabled_async(self, enabled):
        self.frame_read_callback_was_enabled = enabled
        self.can.enable_frame_read_callback()

    def get_configuration_async(self, conf):
        self.combo_baud_rate.setCurrentIndex(conf.baud_rate)
        self.combo_transceiver_mode.setCurrentIndex(conf.transceiver_mode)
        self.spin_write_timeout.setValue(conf.write_timeout)
        self.button_save_configuration.setEnabled(False)

    def get_read_filter_async(self, read_filter):
        self.combo_filter_mode.setCurrentIndex(read_filter.mode)

        self.spin_filter_mask_extended.setValue((read_filter.mask >> 11)
                                                & 0x3FFFF)
        self.spin_filter_mask_standard.setValue(read_filter.mask & 0x7FF)
        self.spin_filter_mask_data1.setValue((read_filter.mask >> 19) & 0xFF)
        self.spin_filter_mask_data2.setValue((read_filter.mask >> 11) & 0xFF)

        self.spin_filter1_extended.setValue((read_filter.filter1 >> 11)
                                            & 0x3FFFF)
        self.spin_filter1_standard.setValue(read_filter.filter1 & 0x7FF)
        self.spin_filter1_data1.setValue((read_filter.filter1 >> 19) & 0xFF)
        self.spin_filter1_data2.setValue((read_filter.filter1 >> 11) & 0xFF)

        self.spin_filter2_extended.setValue((read_filter.filter2 >> 11)
                                            & 0x3FFFF)
        self.spin_filter2_standard.setValue(read_filter.filter2 & 0x7FF)
        self.spin_filter2_data1.setValue((read_filter.filter2 >> 19) & 0xFF)
        self.spin_filter2_data2.setValue((read_filter.filter2 >> 11) & 0xFF)

        self.button_save_read_filter.setEnabled(False)

    def get_error_log_async(self, log):
        self.label_write_error_level.setText(str(log.write_error_level))
        self.label_read_error_level.setText(str(log.read_error_level))

        if log.transceiver_disabled:
            self.label_transceiver_status.setText('Disabled by Error')
        else:
            self.label_transceiver_status.setText('Active')

        self.label_write_timeouts.setText(str(log.write_timeout_count))
        self.label_read_register_overflows.setText(
            str(log.read_register_overflow_count))
        self.label_read_buffer_overflows.setText(
            str(log.read_buffer_overflow_count))

    def frame_type_changed(self):
        frame_type = self.combo_frame_type.currentIndex()
        extended = frame_type in [
            self.can.FRAME_TYPE_EXTENDED_DATA,
            self.can.FRAME_TYPE_EXTENDED_REMOTE
        ]
        remote = frame_type in [
            self.can.FRAME_TYPE_STANDARD_REMOTE,
            self.can.FRAME_TYPE_EXTENDED_REMOTE
        ]

        self.spin_identifier_extended.setEnabled(extended)
        self.edit_data.setDisabled(remote)

    def configuration_changed(self):
        self.button_save_configuration.setEnabled(True)

    def filter_mode_changed(self):
        index = self.combo_filter_mode.currentIndex()
        disabled = index == self.can.FILTER_MODE_DISABLED
        accept_all = index == self.can.FILTER_MODE_ACCEPT_ALL
        match_standard_and_data = index == self.can.FILTER_MODE_MATCH_STANDARD_AND_DATA
        match_extended = index == self.can.FILTER_MODE_MATCH_EXTENDED

        self.spin_filter_mask_extended.setDisabled(disabled or accept_all)
        self.spin_filter_mask_standard.setDisabled(disabled or accept_all)
        self.spin_filter_mask_data1.setDisabled(disabled or accept_all)
        self.spin_filter_mask_data2.setDisabled(disabled or accept_all)

        self.spin_filter1_extended.setDisabled(disabled or accept_all)
        self.spin_filter1_standard.setDisabled(disabled or accept_all)
        self.spin_filter1_data1.setDisabled(disabled or accept_all)
        self.spin_filter1_data2.setDisabled(disabled or accept_all)

        self.spin_filter2_extended.setDisabled(disabled or accept_all)
        self.spin_filter2_standard.setDisabled(disabled or accept_all)
        self.spin_filter2_data1.setDisabled(disabled or accept_all)
        self.spin_filter2_data2.setDisabled(disabled or accept_all)

        self.spin_filter_mask_extended.setVisible(match_extended)
        self.spin_filter_mask_data1.setVisible(match_standard_and_data)
        self.spin_filter_mask_data2.setVisible(match_standard_and_data)

        self.spin_filter1_extended.setVisible(match_extended)
        self.spin_filter1_data1.setVisible(match_standard_and_data)
        self.spin_filter1_data2.setVisible(match_standard_and_data)

        self.spin_filter2_extended.setVisible(match_extended)
        self.spin_filter2_data1.setVisible(match_standard_and_data)
        self.spin_filter2_data2.setVisible(match_standard_and_data)

        self.button_save_read_filter.setEnabled(True)

    def mask_or_filter_changed(self):
        self.button_save_read_filter.setEnabled(True)

    def update_error_log(self):
        async_call(self.can.get_error_log, None, self.get_error_log_async,
                   self.increase_error_count)

    def write_frame(self):
        frame_type = self.combo_frame_type.currentIndex()
        extended = frame_type in [
            self.can.FRAME_TYPE_EXTENDED_DATA,
            self.can.FRAME_TYPE_EXTENDED_REMOTE
        ]
        identifier = self.spin_identifier_standard.value()

        if extended:
            identifier |= self.spin_identifier_extended.value() << 11

        data_str = self.edit_data.text().replace(' ', '')
        data = []

        while len(data_str) > 0:
            data.append(int(data_str[:2], 16))
            data_str = data_str[2:]

        data += [0] * max(8 - len(data), 0)
        data = data[:8]
        length = self.spin_length.value()

        async_call(self.can.write_frame,
                   (frame_type, identifier, data, length),
                   self.write_frame_async, self.write_frame_error)

    def write_frame_async(self, success):
        if not success:
            QMessageBox.critical(
                get_main_window(), 'Write Frame',
                'Could not write frame due to write buffer overflow.',
                QMessageBox.Ok)

    def write_frame_error(self):
        self.increase_error_count()
        self.button_write_frame.setEnabled(True)

    def save_history(self):
        filename = get_save_file_name(get_main_window(), 'Save History',
                                      self.last_filename)

        if len(filename) == 0:
            return

        self.last_filename = filename

        try:
            f = open(filename, 'wb')
        except Exception as e:
            QMessageBox.critical(
                get_main_window(), 'Save History Error',
                u'Could not open {0} for writing:\n\n{1}'.format(filename, e))
            return

        root = self.tree_frames.invisibleRootItem()
        content = ['Frame Type;Identifier [Hex];Data [Hex];Length\n']

        for i in range(root.childCount()):
            child = root.child(i)
            row = []

            for c in range(child.columnCount()):
                row.append(child.text(c))

            content.append(';'.join(row) + '\n')

        try:
            # FIXME: add progress dialog if content is bigger than some megabytes
            f.write(''.join(content).encode('utf-8'))
        except Exception as e:
            QMessageBox.critical(
                get_main_window(), 'Save History Error',
                u'Could not write to {0}:\n\n{1}'.format(filename, e))

        f.close()

    def save_configuration(self):
        baud_rate = self.combo_baud_rate.currentIndex()
        transceiver_mode = self.combo_transceiver_mode.currentIndex()
        write_timeout = self.spin_write_timeout.value()

        # FIXME: add validation
        self.can.set_configuration(baud_rate, transceiver_mode, write_timeout)
        self.button_save_configuration.setEnabled(False)

    def save_read_filter(self):
        mode = self.combo_filter_mode.currentIndex()
        mask = 0
        filter1 = 0
        filter2 = 2

        if mode == self.can.FILTER_MODE_MATCH_STANDARD:
            mask = self.spin_filter_mask_standard.value()
            filter1 = self.spin_filter1_standard.value()
            filter2 = self.spin_filter2_standard.value()
        elif mode == self.can.FILTER_MODE_MATCH_STANDARD_AND_DATA:
            mask = (self.spin_filter_mask_data1.value() << 19) | (
                self.spin_filter_mask_data2.value() <<
                11) | self.spin_filter_mask_standard.value()
            filter1 = (self.spin_filter1_data1.value() << 19) | (
                self.spin_filter1_data2.value() <<
                11) | self.spin_filter1_standard.value()
            filter2 = (self.spin_filter2_data1.value() << 19) | (
                self.spin_filter2_data2.value() <<
                11) | self.spin_filter2_standard.value()
        elif mode == self.can.FILTER_MODE_MATCH_EXTENDED:
            mask = (self.spin_filter_mask_extended.value() <<
                    11) | self.spin_filter_mask_standard.value()
            filter1 = (self.spin_filter1_extended.value() <<
                       11) | self.spin_filter1_standard.value()
            filter2 = (self.spin_filter2_extended.value() <<
                       11) | self.spin_filter2_standard.value()

        # FIXME: add validation
        self.can.set_read_filter(mode, mask, filter1, filter2)
        self.button_save_read_filter.setEnabled(False)
Example #35
0
class MyGlWidget(QGLWidget):
    "PySideApp uses Qt library to create an opengl context, listen to keyboard events, and clean up"

    def __init__(self, renderer, glformat, app, scene):
        self.scene = scene
        "Creates an OpenGL context and a window, and acquires OpenGL resources"
        super(MyGlWidget, self).__init__(glformat)
        self.renderer = renderer
        self.app = app
        # Use a timer to rerender as fast as possible
        self.timer = QTimer(self)
        self.timer.setSingleShot(True)
        self.timer.setInterval(0)
        self.timer.timeout.connect(self.render_vr)
        # Accept keyboard events
        self.setFocusPolicy(Qt.StrongFocus)

    def __enter__(self):
        "setup for RAII using 'with' keyword"
        return self

    def __exit__(self, type_arg, value, traceback):
        "cleanup for RAII using 'with' keyword"
        self.dispose_gl()

    def initializeGL(self):
        if self.renderer is not None:
            self.renderer.init_gl()
        self.timer.start()

    def paintGL(self):
        "render scene one time"
        self.renderer.render_scene()
        self.swapBuffers()  # Seems OK even in single-buffer mode

    def render_vr(self):
        self.makeCurrent()
        self.paintGL()
        self.doneCurrent()
        self.timer.start()  # render again real soon now

    def disposeGL(self):
        if self.renderer is not None:
            self.makeCurrent()
            self.renderer.dispose_gl()
            self.doneCurrent()

    def keyPressEvent(self, event):
        key = event.key()
        step = 0.125 / self.scene.mesh.size_scale

        if key == Qt.Key_Escape:
            self.app.quit()
        elif key == Qt.Key_W:  #forward "w"
            self.scene.mesh.y_offset += step
        elif key == Qt.Key_S:  #back "s"
            self.scene.mesh.y_offset -= step
        elif key == Qt.Key_D:  #right "d"
            self.scene.mesh.x_offset += step
        elif key == Qt.Key_A:  #left "a"
            self.scene.mesh.x_offset -= step
        elif key == Qt.Key_R:  #up "r"
            self.scene.mesh.z_offset += step
        elif key == Qt.Key_F:  #down "f"
            self.scene.mesh.z_offset -= step
        elif key == Qt.Key_Equal:  #scale up "+"
            self.scene.mesh.size_scale += self.scene.mesh.size_scale / 10
            self.scene.mesh.initialize = True
        elif key == Qt.Key_Minus:  #scale down "-"
            self.scene.mesh.size_scale -= self.scene.mesh.size_scale / 10
            self.scene.mesh.initialize = True
        elif key == Qt.Key_Up:  #speed down "up arrow"
            self.scene.mesh.gravity.time_scale += 10
        elif key == Qt.Key_Down:  #speed down "down arrow"
            if self.scene.mesh.gravity.time_scale >= 10:
                self.scene.mesh.gravity.time_scale -= 10 - 0.1
        elif key == Qt.Key_Space:  #reset universe
            self.scene.mesh.gravity.__reset_universe__()
            self.scene.mesh.initialize = True  #any hidden verts will now be re-shown
Example #36
0
class GLPlotWidget(QGLWidget):
    # default window size
    width, height = 735, 855
    pos_x0 = -0.02
    pos_y0 = -0.74
    gpos_x0 = []
    gpos_y0 = []
    ang = 0.0
    mstate = 0
    nums = 10
    step = 1
    stepc = 0
    prevKey = QtCore.Qt.Key_Right
    virtKey = QtCore.Qt.Key_Right
    prevKeyGhost = []
    akeys = [
        QtCore.Qt.Key_Left, QtCore.Qt.Key_Right, QtCore.Qt.Key_Up,
        QtCore.Qt.Key_Down
    ]
    ghost_last_move = [[0 for _ in range(6)] for _ in range(5)]
    score = 0
    lives = 3
    numg = 2
    follow_pcman = [False, False, False, False, False]
    follow_cnt = [0, 0, 0, 0, 0]
    sound_counter = 0
    tick_interval0 = 80
    tick_interval = 80
    isDead = False
    started = False
    walls_x = [-842, -702, -502, -302, -102, 98, 298, 498, 698, 838]
    walls_y = [-874, -674, -474, -274, -74, 126, 326, 526, 726, 986]

    wall_sample_ghost = [[], [], [], [], []]

    def set_data(self, data):
        self.data = data
        self._pBits = self.makeRectImage()

    def read_texture(self, filename):
        img = Image.open(filename)
        img_data = np.array(list(img.getdata()), np.int32)
        textID = gl.glGenTextures(1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, textID)
        gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
        gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP)
        gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP)
        gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                           gl.GL_NEAREST)
        gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                           gl.GL_NEAREST)
        gl.glTexEnvf(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_DECAL)
        gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.size[0],
                        img.size[1], 0, gl.GL_RGB, gl.GL_UNSIGNED_BYTE,
                        img_data)
        return textID

    def initializeGL(self):
        # background color
        gl.glClearColor(0, 0, 0, 0)

        # setup textures (walls background without points/meat and with points/meat
        self.texture_0 = self.read_texture("Resources/pacman1.jpg")
        self.texture_1 = self.read_texture("Resources/pacman2.jpg")
        self.texture_ghost = []
        texId = self.read_texture("Resources/ghost_red.jpg")
        self.texture_ghost.append(texId)
        texId = self.read_texture("Resources/ghost_pink.jpg")
        self.texture_ghost.append(texId)
        texId = self.read_texture("Resources/ghost_green.jpg")
        self.texture_ghost.append(texId)
        texId = self.read_texture("Resources/ghost_orange.jpg")
        self.texture_ghost.append(texId)
        texId = self.read_texture("Resources/ghost_blue.jpg")
        self.texture_ghost.append(texId)

        self.gpos_x0 = [-1.02, 0.98, -1.2, 1.2, 0.0]
        self.gpos_y0 = [3.26, 3.26, 1.0, 1.0, 1.0]
        self.gpos_x = list(self.gpos_x0)
        self.gpos_y = list(self.gpos_y0)
        self.pos_x = self.pos_x0
        self.pos_y = self.pos_y0

        self.prevKeyGhost.append(QtCore.Qt.Key_Left)
        self.prevKeyGhost.append(QtCore.Qt.Key_Right)
        self.prevKeyGhost.append(QtCore.Qt.Key_Left)
        self.prevKeyGhost.append(QtCore.Qt.Key_Right)
        self.prevKeyGhost.append(QtCore.Qt.Key_Left)

        # create a Vertex Buffer Object with the specified data
        self.vbo = []
        for i in range(0, self.nums):
            self.vbo.append(glvbo.VBO(self.data[i]))

        self.drawScore()
        self.drawLives()
        self.drawTitle()

    def drawTitle(self):
        self.drawText(20, 10,
                      "Pac-Man Python version by Mirza Coralic (c) 2020", 300,
                      12)

    def drawScore(self):
        self.drawText(170, self.height - 53, str(self.score), 150, 40)

    def drawLives(self):
        self.drawText(490, self.height - 53, str(self.lives), 30, 40)

    def drawBackground(self, textId):
        k = 855.0 / 735.0  # aspect ratio of widget window
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glBindTexture(gl.GL_TEXTURE_2D, textId)
        gl.glBegin(gl.GL_QUADS)
        gl.glTexCoord2f(0, 1)
        gl.glVertex2f(-10.0, -10.0 * k)
        gl.glTexCoord2f(1, 1)
        gl.glVertex2f(10.0, -10.0 * k)
        gl.glTexCoord2f(1, 0)
        gl.glVertex2f(10.0, 10.0 * k)
        gl.glTexCoord2f(0, 0)
        gl.glVertex2f(-10.0, 10.0 * k)
        gl.glEnd()
        gl.glDisable(gl.GL_TEXTURE_2D)

    def drawGhost(self, idx):
        w = 41.0 * 10.0 / 735.0
        k = 855.0 / 735.0  # aspect ratio of widget window
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_ghost[idx])
        gl.glBegin(gl.GL_QUADS)
        gl.glTexCoord2f(0, 1)
        gl.glVertex2f(-w, -w)
        gl.glTexCoord2f(1, 1)
        gl.glVertex2f(w, -w)
        gl.glTexCoord2f(1, 0)
        gl.glVertex2f(w, w)
        gl.glTexCoord2f(0, 0)
        gl.glVertex2f(-w, w)
        gl.glEnd()
        gl.glDisable(gl.GL_TEXTURE_2D)

    def drawPacman(self):
        # bind the VBO
        self.vbo[self.mstate].bind()
        # tell OpenGL that the VBO contains an array of vertices
        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        # these vertices contain 2 single precision coordinates
        gl.glVertexPointer(2, gl.GL_FLOAT, 0, self.vbo[self.mstate])
        # draw triangles of pacman from the VBO
        gl.glDrawArrays(gl.GL_TRIANGLE_FAN, 0, self.data[self.mstate].shape[0])

    def worldToScreen(self, x, y, flip):
        # project the point to screen
        point = glu.gluProject(x, y, 1.0, self.model_view, self.proj,
                               self.view)  # -0.75 -> pos_y0

        if flip:
            sx = round(point[0])
            sy = round(self.view[3] - point[1])
            return ([sx, sy])
        else:
            return ([point[0], point[1]])

    def readPixels(self, wh, idx):
        px = self.pos_x
        py = self.pos_y
        if idx > -1:
            px = self.gpos_x[idx]
            py = self.gpos_y[idx]

        x0, y0 = self.worldToScreen(px, py, False)
        w = wh
        h = wh
        gl.glReadBuffer(gl.GL_BACK)
        img = gl.glReadPixels(x0 - w / 2, y0 - h / 2, w, h, gl.GL_LUMINANCE,
                              gl.GL_UNSIGNED_BYTE)
        im = Image.frombytes("L", (w, h), img)  # (self.height*3 + 3) & -4, -1)
        im = ImageOps.flip(im)
        return im

    def checkLeftWall(self, preKey, sx, sy, wall_sample):
        if preKey == QtCore.Qt.Key_Left or preKey == QtCore.Qt.Key_Right:
            imL = wall_sample.crop([24, 30, 26, 70])
            imLb = np.fromstring(imL.tobytes(), np.uint8)
            thL = imLb.sum() / 80
            #print('thL = ' + str(thL) + '   pos_x = ' + str(self.pos_x))
            return (thL < 40 and sy in self.walls_y)  # 50

        if preKey == QtCore.Qt.Key_Up or preKey == QtCore.Qt.Key_Down:
            imL2 = wall_sample.crop([0, 28, 30, 72])
            imL2b = np.fromstring(imL2.tobytes(), np.uint8)
            thL2 = imL2b.sum() / 1320
            #print('thL2 = ' + str(thL2))
            return (thL2 < 16 and sy in self.walls_y)  # 10

    def checkRightWall(self, preKey, sx, sy, wall_sample):
        if preKey == QtCore.Qt.Key_Left or preKey == QtCore.Qt.Key_Right:
            imR = wall_sample.crop([100 - 26, 30, 100 - 24, 70])
            imRb = np.fromstring(imR.tobytes(), np.uint8)
            thR = imRb.sum() / 80
            #print('thR = ' + str(thR) + '   pos_x = ' + str(self.pos_x))
            return (thR < 40 and sy in self.walls_y)

        if preKey == QtCore.Qt.Key_Up or preKey == QtCore.Qt.Key_Down:
            imR2 = wall_sample.crop([70, 28, 100, 72])
            imR2b = np.fromstring(imR2.tobytes(), np.uint8)
            thR2 = imR2b.sum() / 1320
            #print('thR2 = ' + str(thR2))
            return (thR2 < 16 and sy in self.walls_y)

    def checkUpWall(self, preKey, sx, sy, wall_sample):
        if preKey == QtCore.Qt.Key_Up or preKey == QtCore.Qt.Key_Down:
            imU = wall_sample.crop([30, 24, 70, 26])
            imUb = np.fromstring(imU.tobytes(), np.uint8)
            thU = imUb.sum() / 80
            #print('thU = ' + str(thU) + '   pos_y = ' + str(self.pos_y) + '    sy = ' + str(sy))
            return (
                thU < 40 and sx in self.walls_x and sy < 980
            )  # pos_y<9.80 correction because upper wall not drawn correctly

        if preKey == QtCore.Qt.Key_Left or preKey == QtCore.Qt.Key_Right:
            imU2 = wall_sample.crop([28, 0, 72, 30])
            imU2b = np.fromstring(imU2.tobytes(), np.uint8)
            thU2 = imU2b.sum() / 1320
            #print('thU2 = ' + str(thU2))
            return (thU2 < 16 and sx in self.walls_x)

    def checkDownWall(self, preKey, sx, sy, wall_sample):
        if preKey == QtCore.Qt.Key_Up or preKey == QtCore.Qt.Key_Down:
            imD = wall_sample.crop([30, 74, 70, 76])
            imDb = np.fromstring(imD.tobytes(), np.uint8)
            thD = imDb.sum() / 80
            #print('thD = ' + str(thD))
            return (thD < 40 and sx in self.walls_x)

        if preKey == QtCore.Qt.Key_Left or preKey == QtCore.Qt.Key_Right:
            imD2 = wall_sample.crop([28, 70, 72, 100])
            imD2b = np.fromstring(imD2.tobytes(), np.uint8)
            thD2 = imD2b.sum() / 1320
            #print('thD2 = ' + str(thD2))
            return (thD2 < 16 and sx in self.walls_x)

    def checkMeat(self):
        imM = self.meat_sample
        imMb = np.fromstring(imM.tobytes(), np.uint8)
        thM = imMb.sum() / 100
        #print('thM = ' + str(thM))
        return (thM > 40)

    def moveLeft(self, idx, sx, sy, checkOnly):
        preKey = self.prevKey
        wall_sample = self.wall_sample
        if idx > -1:
            preKey = self.prevKeyGhost[idx]
            wall_sample = self.wall_sample_ghost[idx]

        ret = self.checkLeftWall(preKey, sx, sy, wall_sample)

        if ret and not checkOnly:
            if idx == -1:
                if self.pos_x < -9.6:
                    self.pos_x = 9.38
                else:
                    self.pos_x += -0.2
                    self.ang = 180.0
                    self.prevKey = QtCore.Qt.Key_Left
            else:
                if self.gpos_x[idx] < -9.6:
                    self.gpos_x[idx] = 9.38
                else:
                    self.gpos_x[idx] += -0.2
                    self.prevKeyGhost[idx] = QtCore.Qt.Key_Left

        return ret

    def moveRight(self, idx, sx, sy, checkOnly):
        preKey = self.prevKey
        wall_sample = self.wall_sample
        if idx > -1:
            preKey = self.prevKeyGhost[idx]
            wall_sample = self.wall_sample_ghost[idx]

        ret = self.checkRightWall(preKey, sx, sy, wall_sample)
        if ret and not checkOnly:
            if idx == -1:
                if self.pos_x > 9.5:
                    self.pos_x = -9.42
                else:
                    self.pos_x += 0.2
                    self.ang = 0.0
                    self.prevKey = QtCore.Qt.Key_Right
            else:
                if self.gpos_x[idx] > 9.5:
                    self.gpos_x[idx] = -9.42
                else:
                    self.gpos_x[idx] += 0.2
                    self.prevKeyGhost[idx] = QtCore.Qt.Key_Right

        return ret

    def moveUp(self, idx, sx, sy, checkOnly):
        preKey = self.prevKey
        wall_sample = self.wall_sample
        if idx > -1:
            preKey = self.prevKeyGhost[idx]
            wall_sample = self.wall_sample_ghost[idx]

        ret = self.checkUpWall(preKey, sx, sy, wall_sample)
        if ret and not checkOnly:
            if idx == -1:
                self.pos_y += 0.2
                self.ang = 90.0
                self.prevKey = QtCore.Qt.Key_Up
            else:
                self.gpos_y[idx] += 0.2
                self.prevKeyGhost[idx] = QtCore.Qt.Key_Up

        return ret

    def moveDown(self, idx, sx, sy, checkOnly):
        preKey = self.prevKey
        wall_sample = self.wall_sample
        if idx > -1:
            preKey = self.prevKeyGhost[idx]
            wall_sample = self.wall_sample_ghost[idx]

        ret = self.checkDownWall(preKey, sx, sy, wall_sample)
        if ret and not checkOnly:
            if idx == -1:
                self.pos_y += -0.2
                self.ang = -90.0
                self.prevKey = QtCore.Qt.Key_Down
            else:
                self.gpos_y[idx] += -0.2
                self.prevKeyGhost[idx] = QtCore.Qt.Key_Down

        return ret

    def keyPressEvent(self, e):
        if e.key() == QtCore.Qt.Key_Q:
            reply = QMessageBox.question(
                self, "Message", "Are you sure you want to quit?",
                QMessageBox.Close | QMessageBox.Cancel)

            if reply == QMessageBox.Close:
                sys.exit()

        elif e.key() == QtCore.Qt.Key_X:
            #sx, sy = self.worldToScreen(self.pos_x, self.pos_y,True)
            sx = 100.0 * self.pos_x
            self.walls_x.append(int(round(sx)))
        elif e.key() == QtCore.Qt.Key_Y:
            #sx, sy = self.worldToScreen(self.pos_x, self.pos_y, True)
            sy = 100.0 * self.pos_y
            self.walls_y.append(int(round(sy)))
        elif e.key() == QtCore.Qt.Key_P:
            print('X: ' + str(self.walls_x))
            print('Y: ' + str(self.walls_y))

        ret = self.checkMovement(e.key(), -1,
                                 True)  # idx = -1 for pacman, idx>=0 ghosts
        if ret:
            self.virtKey = e.key()
            self.pressedKeyRetry = e.key()
        else:
            self.pressedKeyRetry = e.key()

        self.pressedKey = e.key()

        if not self.started:
            self.timer = QTimer()
            self.timer.timeout.connect(self.tick)
            self.timer.start(self.tick_interval)  #80 normal speed
            self.started = True

    def checkMovement(self, ekey, idx, checkOnly):
        sx = 0
        sy = 0
        if idx < 0:
            sx = int(round(100.0 * self.pos_x))
            sy = int(round(100.0 * self.pos_y))
        else:
            sx = int(round(100.0 * self.gpos_x[idx]))
            sy = int(round(100.0 * self.gpos_y[idx]))
        ret = False
        if ekey == QtCore.Qt.Key_Left:
            ret = self.moveLeft(idx, sx, sy, checkOnly)
        elif ekey == QtCore.Qt.Key_Right:
            ret = self.moveRight(idx, sx, sy, checkOnly)
        elif ekey == QtCore.Qt.Key_Up:
            ret = self.moveUp(idx, sx, sy, checkOnly)
        elif ekey == QtCore.Qt.Key_Down:
            ret = self.moveDown(idx, sx, sy, checkOnly)

        return ret

    def tick(self):
        ret = False

        if not self.isDead:
            kRet = self.pressedKeyRetry
            kVirt = self.virtKey

            if kRet != kVirt:
                ret = self.checkMovement(kRet, -1, True)
                if ret:
                    kVirt = kRet
                    self.virtKey = kVirt

            ret = self.checkMovement(kVirt, -1, False)

            if ret:
                if self.sound_counter == 0 or self.sound_counter > int(
                        480.0 / self.tick_interval):
                    playsound('Resources/wakka.wav', False)
                    self.sound_counter = 0
                self.sound_counter += 1
            else:
                self.sound_counter = 0

        # state machine for pacman render (self.nums number of states)
        if self.isDead:
            if self.mstate < self.nums - 1:
                self.mstate += 1
            else:
                self.mstate = 0
                self.step = 1
                self.stepc = 0
                self.isDead = False
                self.started = False
                self.timer.stop()

                if self.lives == 0:
                    reply = QMessageBox.question(
                        self, "Message", "GAME OVER!!! Want to play again?",
                        QMessageBox.Yes | QMessageBox.No)

                    if reply == QMessageBox.No:
                        sys.exit()
                    self.resetGame()
                else:
                    self.pos_x = self.pos_x0
                    self.pos_y = self.pos_y0

        else:
            if self.mstate > -1 and self.mstate < 4:  # 4 states
                self.mstate += self.step
            if self.stepc < 4 - 2:
                self.stepc += 1
            else:
                self.stepc = 0
                self.step = -self.step

        self.moveGhosts()

        self.updateGL()

        eaten = self.checkMeat()

        if eaten:
            # add to score and update/show score text
            self.score += 1
            self.eraseRectOnImage()
            self.drawScore()

            if self.score > 299:
                self.mstate = 0
                self.step = 1
                self.stepc = 0
                self.isDead = False
                self.started = False
                self.timer.stop()

                reply = QMessageBox.question(
                    self, "Message", "YOU WIN THE GAME. Want to play again?",
                    QMessageBox.Yes | QMessageBox.No)

                if reply == QMessageBox.No:
                    sys.exit()
                self.resetGame()

        if not self.isDead:
            self.checkDie()

        if self.score == 40:
            self.gpos_x[2] = self.gpos_x0[0]
            self.gpos_x[3] = self.gpos_x0[1]
            self.gpos_y[2] = self.gpos_y0[0]
            self.gpos_y[3] = self.gpos_y0[1]
            self.numg = 4
            self.updateGL()
        elif self.score == 80:
            self.gpos_x[4] = self.gpos_x0[0]
            self.gpos_y[4] = self.gpos_y0[0]
            self.numg = 5
            self.updateGL()
        elif self.score == 200:
            self.tick_interval = int(2.0 / 3.0 * self.tick_interval0)
            self.timer.setInterval(self.tick_interval)
        elif self.score == 250:
            self.tick_interval = self.tick_interval0
            self.timer.setInterval(self.tick_interval)
        '''testing
        if 1:
            #sx, sy = self.worldToScreen(self.pos_x, self.pos_y, True)
            sx = int(round(100.0*self.pos_x))
            sy = int(round(100.0*self.pos_y))
            pos = '{:3d}'.format(sx) + ',' + '{:1.3f}'.format(sx)
            self.drawText(480, self.height - 53,pos , 250, 40)
            #bottom -8.74, -8.54 up
        '''

    def moveGhosts(self):
        for i in range(0, self.numg):
            ekey = self.prevKeyGhost[i]  #==QtCore.Qt.Key_Left
            ret = self.checkMovement(ekey, i, True)

            rn = random.randint(0, 2)
            crossroad = (
                (int(round(100. * self.gpos_x[i])) in self.walls_x) and
                (int(round(100. * self.gpos_y[i])) in self.walls_y)) and (rn
                                                                          == 1)

            rem_key = ekey
            rem_key2 = ekey

            rn = random.randint(0, 1)
            rn2 = random.randint(0, 2)

            if rn == 1:
                if self.pos_x > self.gpos_x[i]:
                    rem_key = QtCore.Qt.Key_Left
                else:
                    rem_key = QtCore.Qt.Key_Right
            else:
                if self.pos_y < self.gpos_y[i]:
                    rem_key = QtCore.Qt.Key_Up
                else:
                    rem_key = QtCore.Qt.Key_Down

            if ekey == QtCore.Qt.Key_Left:
                rem_key2 = QtCore.Qt.Key_Right
            elif ekey == QtCore.Qt.Key_Right:
                rem_key2 = QtCore.Qt.Key_Left
            if ekey == QtCore.Qt.Key_Up:
                rem_key2 = QtCore.Qt.Key_Down
            if ekey == QtCore.Qt.Key_Down:
                rem_key2 = QtCore.Qt.Key_Up

            if i == 0:
                '''
                if self.follow_pcman[0]:
                    print('Following: ON')
                    print('.')
                else:
                    print('Following: OFF')
                    print('.')
                '''

                rn3 = random.randint(0, 50)
                if rn3 == 1 and not self.follow_pcman[i]:
                    self.follow_pcman[i] = True
                    #print('--- Following turned on. ---')

                if self.follow_pcman[i]:
                    if self.follow_cnt[i] > 300:
                        self.follow_pcman[i] = False
                        self.follow_cnt[i] = 0
                        #print('--- Following turned off. Timed out. ---')

                    move_hist = [_ - 16777234 for _ in self.ghost_last_move[i]]
                    if move_hist == [1, 2, 0, 3, 1,
                                     2]:  # stuck pos in foolowing mode
                        self.follow_pcman[i] = False
                        self.ghost_last_move[i] = [0 for _ in range(6)]
                        #print('--- Following off. Stucked. ---')
                    # print(move_hist)

                if self.follow_pcman[i]:
                    self.follow_cnt[i] += 1
                    glkey = self.ghost_last_move[i][-1]
                    gremov = QtCore.Qt.Key_Left
                    if glkey == QtCore.Qt.Key_Left:
                        gremov = QtCore.Qt.Key_Right
                    elif glkey == QtCore.Qt.Key_Right:
                        gremov = QtCore.Qt.Key_Left
                    if glkey == QtCore.Qt.Key_Up:
                        gremov = QtCore.Qt.Key_Down
                    elif glkey == QtCore.Qt.Key_Down:
                        gremov = QtCore.Qt.Key_Up

                    gdist_x = math.fabs(self.gpos_x[i] - self.pos_x)
                    gdist_y = math.fabs(self.gpos_y[i] - self.pos_y)

                    gadd = [0, 0]
                    gadd_x = 0
                    gadd_y = 0
                    if self.gpos_x[i] < self.pos_x:
                        gadd_x = QtCore.Qt.Key_Right
                    else:
                        gadd_x = QtCore.Qt.Key_Left
                    if self.gpos_y[i] > self.pos_y:
                        gadd_y = QtCore.Qt.Key_Down
                    else:
                        gadd_y = QtCore.Qt.Key_Up

                    if gdist_x < gdist_y:
                        gadd = [gadd_y, gadd_x]
                    else:
                        gadd = [gadd_x, gadd_y]

                    gkeys = gadd + self.akeys
                    if self.follow_cnt[i] > 1:
                        gkeys.remove(gremov)
                    ret2 = False
                    for m in range(0, 5):
                        ret2 = self.checkMovement(gkeys[m], i, True)
                        if ret2:
                            self.checkMovement(gkeys[m], i, False)
                            self.ghost_last_move[i].append(gkeys[m])
                            self.ghost_last_move[i].pop(0)
                            break

            if self.follow_pcman[i]:
                continue

            if (not ret) or crossroad:
                tkeys = list(self.akeys)
                tkeys.remove(ekey)
                if (rem_key in tkeys) and rn2 == 1:
                    tkeys.remove(rem_key)
                elif (rem_key2 in tkeys):
                    tkeys.remove(rem_key2)
                rn = random.randint(0, len(tkeys) - 1)
                ekey2 = tkeys[rn]
                self.checkMovement(ekey2, i, False)
            else:
                self.checkMovement(ekey, i, False)

    def checkDie(self):
        for i in range(0, self.numg):
            if math.fabs(self.pos_x - self.gpos_x[i]) < 1.0 and math.fabs(
                    self.pos_y - self.gpos_y[i]) < 1.0:
                playsound('Resources/die.wav', False)
                self.isDead = True
                self.mstate = 0
                self.lives -= 1
                self.drawLives()

    def resetGame(self):
        self.started = False
        self.isDead = False
        self.numg = 2
        self.lives = 3
        self.score = 0
        self.tick_interval = self.tick_interval0
        self.pos_x = self.pos_x0
        self.pos_y = self.pos_y0
        self.gpos_x = list(self.gpos_x0)
        self.gpos_y = list(self.gpos_y0)
        self.texture_1 = self.read_texture("Resources/pacman2.jpg")
        self.updateGL()
        self.drawLives()
        self.drawScore()

    def drawText(self, off_x, off_y, text, w, h):
        font = ImageDraw2.Font("yellow", "Resources/monkey.otf", h)
        img = Image.new("RGB", (w, h), (0, 0, 0))
        draw = ImageDraw2.Draw(img)
        draw.text((0, -3 * h / 10), text, font)  # -12
        #img_flip = img.transpose(Image.FLIP_TOP_BOTTOM)
        #img.show()

        self.text_pBits = img.tobytes("raw", "RGB")

        gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_1)
        gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, off_x, off_y, w, h, gl.GL_RGB,
                           gl.GL_UNSIGNED_BYTE, self.text_pBits)
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)

    def makeRectImage(self):
        img = Image.new("RGB", (34, 34), (0, 0, 0))
        img_flip = img.transpose(Image.FLIP_TOP_BOTTOM)
        pBits = img_flip.tobytes("raw", "RGB")
        self._pBits = pBits
        return self._pBits

    def eraseRectOnImage(self):
        off_x, off_y = self.worldToScreen(self.pos_x, self.pos_y, True)
        if off_x + 17 > self.width or off_x - 17 < 0:
            return

        gl.glBindTexture(gl.GL_TEXTURE_2D, self.texture_1)
        gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, off_x - 17, off_y - 17, 34, 34,
                           gl.GL_RGB, gl.GL_UNSIGNED_BYTE, self._pBits)
        gl.glBindTexture(gl.GL_TEXTURE_2D, 0)

    def paintGL(self):
        # clear the buffer
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        self.drawBackground(self.texture_0)
        self.wall_sample = self.readPixels(100, -1)

        for i in range(0, self.numg):
            self.wall_sample_ghost[i] = self.readPixels(100, i)

        self.drawBackground(self.texture_1)
        self.meat_sample = self.readPixels(10, -1)

        for i in range(0, 5):
            gl.glPushMatrix()
            gl.glTranslatef(self.gpos_x[i], self.gpos_y[i], 0)
            self.drawGhost(i)
            gl.glPopMatrix()

        # set yellow color of pacman
        gl.glColor(1, 1, 0)

        gl.glPushMatrix()
        gl.glTranslatef(self.pos_x, self.pos_y, 0)
        if self.isDead:
            gl.glRotated(90, 0, 0, 1)
        else:
            gl.glRotated(self.ang, 0, 0, 1)
        self.drawPacman()
        gl.glPopMatrix()

    def resizeGL(self, width, height):
        # update the window size
        self.width, self.height = width, height
        # paint within the whole window
        gl.glViewport(0, 0, width, height)
        # set orthographic projection (2D only)
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        # the window corner OpenGL coordinates are (-+1, -+1)
        k = 855.0 / 735.0
        gl.glOrtho(-10, 10, -10 * k, 10 * k, -1, 1)

        # get projection matrix, view matrix and the viewport rectangle
        self.model_view = np.array(gl.glGetDoublev(gl.GL_MODELVIEW_MATRIX))
        self.proj = np.array(gl.glGetDoublev(gl.GL_PROJECTION_MATRIX))
        self.view = np.array(gl.glGetIntegerv(gl.GL_VIEWPORT))
Example #37
0
class MotionDetectorV2(COMCUPluginBase, Ui_MotionDetectorV2):
    qtcb_motion_detected = pyqtSignal()
    qtcb_detection_cylce_ended = pyqtSignal()

    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletMotionDetectorV2, *args)

        self.motion_detector_v2 = self.device

        self.changing = False

        self.setupUi(self)

        self.qtcb_motion_detected.connect(self.cb_motion_detected)
        self.motion_detector_v2.register_callback(
            self.motion_detector_v2.CALLBACK_MOTION_DETECTED,
            self.qtcb_motion_detected.emit)

        self.qtcb_detection_cylce_ended.connect(self.cb_detection_cycle_ended)
        self.motion_detector_v2.register_callback(
            self.motion_detector_v2.CALLBACK_DETECTION_CYCLE_ENDED,
            self.qtcb_detection_cylce_ended.emit)

        self.left_syncer = SliderSpinSyncer(self.slider_left,
                                            self.spin_left,
                                            self.indicator_changed,
                                            spin_signal='valueChanged')
        self.right_syncer = SliderSpinSyncer(self.slider_right,
                                             self.spin_right,
                                             self.indicator_changed,
                                             spin_signal='valueChanged')
        self.bottom_syncer = SliderSpinSyncer(self.slider_bottom,
                                              self.spin_bottom,
                                              self.indicator_changed,
                                              spin_signal='valueChanged')

        self.all_syncer = SliderSpinSyncer(self.slider_all,
                                           self.spin_all,
                                           self.all_changed,
                                           spin_signal='valueChanged')

        self.sensitivity_syncer = SliderSpinSyncer(self.slider_sensitivity,
                                                   self.spin_sensitivity,
                                                   self.sensitivity_changed,
                                                   spin_signal='valueChanged')

        def set_indicator(l, r, b):
            self.changing = True
            self.spin_left.setValue(l)
            self.spin_right.setValue(r)
            self.spin_bottom.setValue(b)
            self.changing = False
            self.indicator_changed()

        self.button_off.clicked.connect(lambda: set_indicator(0, 0, 0))
        self.button_on.clicked.connect(lambda: set_indicator(255, 255, 255))
        self.button_left.clicked.connect(lambda: set_indicator(255, 0, 0))
        self.button_right.clicked.connect(lambda: set_indicator(0, 255, 0))
        self.button_bottom.clicked.connect(lambda: set_indicator(0, 0, 255))

        self.indicator_update = False
        self.indicator_value = [0, 0, 0]
        self.sensitivity_update = False
        self.sensitivity_value = 50

        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update)
        self.update_timer.setInterval(50)
        self.update_timer.start()

    def start(self):
        async_call(self.motion_detector_v2.get_indicator, None,
                   self.get_indicator_async, self.increase_error_count)
        async_call(self.motion_detector_v2.get_motion_detected, None,
                   self.get_motion_detected_async, self.increase_error_count)
        async_call(self.motion_detector_v2.get_sensitivity, None,
                   self.get_sensitivity_async, self.increase_error_count)

    def stop(self):
        pass

    # Make sure that we update values with at most a 50ms interval
    def update(self):
        if self.indicator_update:
            self.indicator_update = False
            self.motion_detector_v2.set_indicator(*self.indicator_value)
        if self.sensitivity_update:
            self.sensitivity_update = False
            self.motion_detector_v2.set_sensitivity(self.sensitivity_value)

    def sensitivity_changed(self, value):
        self.sensitivity_value = value
        self.sensitivity_update = True

    def get_sensitivity_async(self, sensitivity):
        self.spin_sensitivity.setValue(sensitivity)

    def get_motion_detected_async(self, motion):
        if motion == self.motion_detector_v2.MOTION_DETECTED:
            self.cb_motion_detected()
        elif motion == self.motion_detector_v2.MOTION_NOT_DETECTED:
            self.cb_detection_cycle_ended()

    def cb_motion_detected(self):
        self.label_motion.setText("<font color='red'>Motion Detected</font>")

    def cb_detection_cycle_ended(self):
        self.label_motion.setText("No Motion Detected")

    def indicator_changed(self, *args):
        if self.changing:
            return

        left, right, bottom = self.spin_left.value(), self.spin_right.value(
        ), self.spin_bottom.value()

        self.changing = True
        self.spin_all.setValue((left + right + bottom) / 3)
        self.changing = False

        self.indicator_value = [left, right, bottom]
        self.indicator_update = True
        self.label_color_left.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(0, 0, left))
        self.label_color_right.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(0, 0, right))
        self.label_color_bottom.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(
                0, 0, bottom))

    def all_changed(self, *args):
        if self.changing:
            return

        x = self.spin_all.value()

        self.changing = True
        self.spin_left.setValue(x)
        self.spin_right.setValue(x)
        self.spin_bottom.setValue(x)
        self.changing = False

        self.indicator_value = [x, x, x]
        self.indicator_update = True
        self.label_color_left.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(0, 0, x))
        self.label_color_right.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(0, 0, x))
        self.label_color_bottom.setStyleSheet(
            'QLabel {{ background: #{:02x}{:02x}{:02x} }}'.format(0, 0, x))

    def get_indicator_async(self, indicator):
        self.changing = True
        self.spin_left.setValue(indicator.top_left)
        self.spin_right.setValue(indicator.top_right)
        self.spin_bottom.setValue(indicator.bottom)
        self.changing = False
        self.indicator_changed()

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletMotionDetectorV2.DEVICE_IDENTIFIER
Example #38
0
class _CameraWidget(QWidget):
    imagecaptured = pyqtSignal(QPixmap)
    done = pyqtSignal()

    def __init__(self, parent=None):
        super(_CameraWidget, self).__init__(parent)
        self.cameralabel = QLabel()
        self.cameralabel.setScaledContents(True)
        self.setLayout(QGridLayout())
        self.toolbar = QToolBar()
        spacer = QWidget()
        # spacer.setMinimumWidth(30)
        spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed)
        self.toolbar.setIconSize(QSize(48, 48))
        self.toolbar.addWidget(spacer)
        self.swapaction = self.toolbar.addAction(QIcon(":/widgets/cameraswap"), "Swap Camera")
        self.swapaction.triggered.connect(self.swapcamera)
        self.cameralabel.mouseReleaseEvent = self.takeimage
        self.layout().setContentsMargins(0, 0, 0, 0)
        self.layout().addWidget(self.toolbar)
        self.layout().addWidget(self.cameralabel)
        self.timer = QTimer()
        self.timer.setInterval(20)
        self.timer.timeout.connect(self.showimage)
        self.cam = None
        self.pixmap = None
        self.currentdevice = 1

    def swapcamera(self):
        self.stop()
        if self.currentdevice == 0:
            self.start(1)
        else:
            self.start(0)

    def showimage(self):
        if self.cam is None:
            return

        img = self.cam.getImage()
        self.image = ImageQt(img)
        pixmap = QPixmap.fromImage(self.image)
        self.cameralabel.setPixmap(pixmap)

    def takeimage(self, *args):
        self.timer.stop()

        img = self.cam.getImage()
        self.image = ImageQt(img)
        self.pixmap = QPixmap.fromImage(self.image)
        self.cameralabel.setPixmap(self.pixmap)
        self.imagecaptured.emit(self.pixmap)
        self.done.emit()

    @property
    def camera_res(self):
        width, height = tuple(roam.config.settings['camera_res'].split(','))
        return width, height

    def start(self, dev=1):
        try:
            self.cam = vc.Device(dev)
            try:
                width, height = self.camera_res
                self.cam.setResolution(int(width), int(height))
            except KeyError:
                pass
            self.currentdevice = dev
        except vidcap.error:
            if dev == 0:
                utils.error("Could not start camera")
                raise CameraError("Could not start camera")
            self.start(dev=0)
            return

        roam.config.settings['camera'] = self.currentdevice
        self.timer.start()

    def stop(self):
        self.timer.stop()
        del self.cam
        self.cam = None
Example #39
0
class IO16(PluginBase, Ui_IO16):
    qtcb_monoflop = pyqtSignal('char', int, int)

    def __init__(self, *args):
        PluginBase.__init__(self, BrickletIO16, *args)

        self.setupUi(self)

        self.io = self.device

        self.has_monoflop = self.firmware_version >= (1, 1, 2)

        self.cbe_port_a = CallbackEmulator(
            functools.partial(self.io.get_port, 'a'),
            functools.partial(self.cb_port, 'a'), self.increase_error_count)
        self.cbe_port_b = CallbackEmulator(
            functools.partial(self.io.get_port, 'b'),
            functools.partial(self.cb_port, 'b'), self.increase_error_count)

        self.port_value = {
            'a': [
                self.av0, self.av1, self.av2, self.av3, self.av4, self.av5,
                self.av6, self.av7
            ],
            'b': [
                self.bv0, self.bv1, self.bv2, self.bv3, self.bv4, self.bv5,
                self.bv6, self.bv7
            ]
        }

        self.port_direction = {
            'a': [
                self.ad0, self.ad1, self.ad2, self.ad3, self.ad4, self.ad5,
                self.ad6, self.ad7
            ],
            'b': [
                self.bd0, self.bd1, self.bd2, self.bd3, self.bd4, self.bd5,
                self.bd6, self.bd7
            ]
        }

        self.port_config = {
            'a': [
                self.ac0, self.ac1, self.ac2, self.ac3, self.ac4, self.ac5,
                self.ac6, self.ac7
            ],
            'b': [
                self.bc0, self.bc1, self.bc2, self.bc3, self.bc4, self.bc5,
                self.bc6, self.bc7
            ]
        }

        self.port_time = {
            'a': [
                self.at0, self.at1, self.at2, self.at3, self.at4, self.at5,
                self.at6, self.at7
            ],
            'b': [
                self.bt0, self.bt1, self.bt2, self.bt3, self.bt4, self.bt5,
                self.bt6, self.bt7
            ]
        }

        self.monoflop_active = {
            'a': [False, False, False, False, False, False, False, False],
            'b': [False, False, False, False, False, False, False, False]
        }

        self.monoflop_timebefore = {
            'a': [500, 500, 500, 500, 500, 500, 500, 500],
            'b': [500, 500, 500, 500, 500, 500, 500, 500]
        }

        self.init_async_generator = self.init_async()
        self.init_async_generator.next()

        self.save_button.clicked.connect(self.save_clicked)
        self.port_box.currentIndexChanged.connect(self.port_changed)
        self.pin_box.currentIndexChanged.connect(self.pin_changed)
        self.direction_box.currentIndexChanged.connect(self.direction_changed)
        self.debounce_save.clicked.connect(self.debounce_save_clicked)
        self.time_spinbox.valueChanged.connect(self.time_changed)
        self.go_button.clicked.connect(self.go_clicked)

        self.qtcb_monoflop.connect(self.cb_monoflop)
        self.io.register_callback(self.io.CALLBACK_MONOFLOP_DONE,
                                  self.qtcb_monoflop.emit)

        self.update_timer = QTimer()
        self.update_timer.timeout.connect(self.update)
        self.update_timer.setInterval(50)

        if not self.has_monoflop:
            self.go_button.setText("Go (FW Versiom >= 1.1.2 required)")
            self.go_button.setEnabled(False)
        else:
            self.update_timer.start()

        self.port_changed(0)

    def init_async(self):
        self.init_value = 0
        self.init_dir = 0
        self.init_config = 0
        self.init_monoflop = 0

        def get_port_async(value):
            self.init_value = value
            self.init_async_generator.next()

        def get_port_configuration_async(conf):
            self.init_dir, self.init_config = conf
            self.init_async_generator.next()

        def get_monoflop_async(init_monoflop):
            self.init_monoflop = init_monoflop
            self.init_async_generator.next()

        def get_debounce_period_async(debounce_period):
            self.debounce_edit.setText(str(debounce_period))
            self.port_changed(0)

        for port in ['a', 'b']:
            async_call(self.io.get_port, port, get_port_async,
                       self.increase_error_count)
            yield
            async_call(self.io.get_port_configuration, port,
                       get_port_configuration_async, self.increase_error_count)
            yield

            time = [0, 0, 0, 0, 0, 0, 0, 0]
            time_remaining = [0, 0, 0, 0, 0, 0, 0, 0]

            if self.has_monoflop:
                for pin in range(8):
                    async_call(self.io.get_port_monoflop, (port, pin),
                               get_monoflop_async, self.increase_error_count)
                    yield

                    time[pin] = self.init_monoflop.time
                    time_remaining[pin] = self.init_monoflop.time_remaining

            self.init_values(port, self.init_value, self.init_dir,
                             self.init_config, time, time_remaining)

        async_call(self.io.get_debounce_period, None,
                   get_debounce_period_async, self.increase_error_count)

    def start(self):
        self.cbe_port_a.set_period(50)
        self.cbe_port_b.set_period(50)

        if self.has_monoflop:
            self.update_timer.start()

    def stop(self):
        self.cbe_port_a.set_period(0)
        self.cbe_port_b.set_period(0)

        self.update_timer.stop()

    def destroy(self):
        pass

    def get_url_part(self):
        return 'io16'

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletIO16.DEVICE_IDENTIFIER

    def init_values(self, port, value, dir, config, time, time_remaining):
        for i in range(8):
            if dir & (1 << i):
                self.port_direction[port][i].setText('Input')

                if config & (1 << i):
                    self.port_config[port][i].setText('Pull-Up')
                else:
                    self.port_config[port][i].setText('Default')
            else:
                self.port_direction[port][i].setText('Output')

                if config & (1 << i):
                    self.port_config[port][i].setText('High')
                else:
                    self.port_config[port][i].setText('Low')

            if value & (1 << i):
                self.port_value[port][i].setText('High')
            else:
                self.port_value[port][i].setText('Low')

            self.port_time[port][i].setText(str(time_remaining[i]))

            if time[i] > 0:
                self.monoflop_timebefore[port][i] = time[i]

            if time_remaining[i] > 0:
                self.monoflop_active[port][i] = True

        self.update_monoflop_ui_state()

    def update_monoflop_ui_state(self):
        port = self.port_box.currentText().lower()
        pin = int(self.pin_box.currentText())

        if self.port_direction[port][pin].text() == 'Output' and \
           self.direction_box.currentText() == 'Output' and \
           self.has_monoflop:
            self.time_spinbox.setEnabled(not self.monoflop_active[port][pin])
            self.go_button.setEnabled(True)
        else:
            self.time_spinbox.setEnabled(False)
            self.go_button.setEnabled(False)

        self.time_spinbox.setValue(self.monoflop_timebefore[port][pin])

    def save_clicked(self):
        port = self.port_box.currentText().lower()
        pin = int(self.pin_box.currentText())
        direction = self.direction_box.currentText()[0].lower()
        if direction == 'o':
            value = self.value_box.currentText() == 'High'
            self.port_value[port][pin].setText(self.value_box.currentText())
        else:
            value = self.value_box.currentText() == 'Pull-Up'

        try:
            self.io.set_port_configuration(port, 1 << pin, direction, value)
        except ip_connection.Error:
            return

        self.port_direction[port][pin].setText(
            self.direction_box.currentText())
        self.port_config[port][pin].setText(self.value_box.currentText())

        self.monoflop_active[port][pin] = False
        self.port_time[port][pin].setText('0')

        self.update_monoflop_ui_state()

    def cb_port(self, port, value):
        for i in range(8):
            if value & (1 << i):
                self.port_value[port][i].setText('High')
            else:
                self.port_value[port][i].setText('Low')

    def port_changed(self, port):
        self.pin_changed(int(self.pin_box.currentText()))

    def pin_changed(self, pin):
        port = self.port_box.currentText().lower()

        if self.port_direction[port][pin].text() == 'Input':
            index = 0
        else:
            index = 1

        self.direction_box.setCurrentIndex(index)
        self.direction_changed(index)
        self.update_monoflop_ui_state()

    def direction_changed(self, direction):
        port = self.port_box.currentText().lower()
        pin = int(self.pin_box.currentText())

        self.value_box.clear()

        if direction == 1:
            self.value_box.addItem('High')
            self.value_box.addItem('Low')

            if self.port_config[port][pin].text() == 'High':
                self.value_box.setCurrentIndex(0)
            else:
                self.value_box.setCurrentIndex(1)
        else:
            self.value_box.addItem('Pull-Up')
            self.value_box.addItem('Default')

            if self.port_config[port][pin].text() == 'Pull-Up':
                self.value_box.setCurrentIndex(0)
            else:
                self.value_box.setCurrentIndex(1)

        self.update_monoflop_ui_state()

    def debounce_save_clicked(self):
        debounce = int(self.debounce_edit.text())
        try:
            self.io.set_debounce_period(debounce)
        except ip_connection.Error:
            return

    def time_changed(self, time):
        port = self.port_box.currentText().lower()
        pin = int(self.pin_box.currentText())

        if not self.monoflop_active[port][pin]:
            self.monoflop_timebefore[port][pin] = time

    def go_clicked(self):
        port = self.port_box.currentText().lower()
        pin = int(self.pin_box.currentText())

        if self.value_box.currentText() == 'High':
            value = 1
        else:
            value = 0

        try:
            time = self.monoflop_timebefore[port][pin]
            self.io.set_port_monoflop(port, 1 << pin, value << pin, time)

            if value:
                self.port_value[port][pin].setText('High')
                self.port_config[port][pin].setText('High')
            else:
                self.port_value[port][pin].setText('Low')
                self.port_config[port][pin].setText('Low')

            self.monoflop_active[port][pin] = True
            self.time_spinbox.setEnabled(False)
            self.port_time[port][pin].setText(str(time))
        except ip_connection.Error:
            return

    def cb_monoflop(self, port, pin_mask, value_mask):
        for pin in range(8):
            if pin_mask & (1 << pin):
                self.monoflop_active[port][pin] = False
                self.port_time[port][pin].setText('0')

                if port == self.port_box.currentText().lower() and \
                   pin == int(self.pin_box.currentText()):
                    self.time_spinbox.setValue(
                        self.monoflop_timebefore[port][pin])
                    self.time_spinbox.setEnabled(True)

                if value_mask & (1 << pin):
                    self.port_value[port][pin].setText('High')
                    self.port_config[port][pin].setText('High')
                else:
                    self.port_value[port][pin].setText('Low')
                    self.port_config[port][pin].setText('Low')

    def update_async(self, port, pin, monoflop):
        selected_port = self.port_box.currentText().lower()
        selected_pin = int(self.pin_box.currentText())

        _, _, time_remaining = monoflop
        if port == selected_port and pin == selected_pin and self.monoflop_active[
                port][pin]:
            self.time_spinbox.setValue(time_remaining)

        self.port_time[port][pin].setText(str(time_remaining))

    def update(self):
        for port in ['a', 'b']:
            for pin in range(8):
                if self.monoflop_active[port][pin]:

                    def get_lambda(port, pin):
                        return lambda x: self.update_async(port, pin, x)

                    async_call(self.io.get_port_monoflop, (port, pin),
                               get_lambda(port, pin),
                               self.increase_error_count)
class Window(QtGui.QMainWindow, Ui_MainWindow):
    def __init__(self):
        QtGui.QMainWindow.__init__(self)
        Ui_MainWindow.__init__(self)
        self.setupUi(self)
        self.initUI()

    def initUI(self):
        self.w = QWidget()

        # a figure instance to plot on
        self.figure = Figure()

        # this is the Canvas Widget that displays the `figure`
        # it takes the `figure` instance as a parameter to __init__
        self.canvas = FigureCanvas(self.figure)

        # this is the Navigation widget
        # it takes the Canvas widget and a parent
        self.toolbar = NavigationToolbar(self.canvas, self)

        # set the layout for the main window
        self.dispLayout.addWidget(self.toolbar)
        self.dispLayout.addWidget(self.canvas)

        #buttons
        self.nextFrame.clicked.connect(self.dispNextImg)
        self.prevFrame.clicked.connect(self.dispPrevImg)
        self.selectFileBut.clicked.connect(self.getFile)
        self.playVidBut.clicked.connect(self.play)
        self.makeTiffBut.clicked.connect(self.makeTiff2)
        self.displayC.clicked.connect(self.dispCDef)
        self.displayC.clicked.connect(self.displayTempValues)
        self.displayF.clicked.connect(self.dispFDef)
        self.displayF.clicked.connect(self.displayTempValues)
        self.sl.valueChanged.connect(self.slValueChange)
        self.saveCvImageBut.clicked.connect(self.saveCvImage)
        #cid = self.canvas.mpl_connect('button_press_event', self.on_press)
        self.saveAsVideoSS.clicked.connect(self.saveVideoSS)
        self.pauseVidBut.clicked.connect(self.pauseVideo)
        #self.startEdit.returnPressed(frame = str(self.startEdit.text()))
        #self.startEdit.returnPressed(frame = str(self.startEdit.text()))

        #self.history.verticalScrollBar().setValue(self.history.verticalScrollBar().maximum())

        # timer
        self.timer = QTimer(self)
        self.timer.setInterval(timerHz)
        self.timer.timeout.connect(self.playVid5)
        self.timer.start()

    def dispCDef(self):
        global toggleUnitState
        toggleUnitState = 'C'
        self.history.insertPlainText('Display ' + str(toggleUnitState) + '\n')
        self.history.moveCursor(QTextCursor.End)

    def dispFDef(self):
        global toggleUnitState
        toggleUnitState = 'F'
        self.history.insertPlainText('Display ' + str(toggleUnitState) + '\n')
        self.history.moveCursor(QTextCursor.End)

    def startTimer(self):
        global hz
        self.timer.stop()
        print(hz)
        self.timer.setInterval(timerHz)
        self.timer.timeout.connect(self.playVid5)
        self.timer.start()
        print('Re-Started Timer')

    def stopTimer(self):
        self.timer.stop()

    def speed(self):
        global framerate
        hzIndex = self.comboBoxHz.currentIndex()
        if hzIndex == 0:
            framerate = 0.5
            print('Half Framerate')
        elif hzIndex == 1:
            framerate = 1
            print('Normal Framerate')
        elif hzIndex == 2:
            framerate = 2
            print('Double Framerate')
        else:
            hz = 111
        self.startTimer()

    def slValueChange(self):
        global frame
        #global fileSelected
        #if fileSelected != "":
        #print('SlValueChange Def Called')
        frame = self.sl.value()
        self.dispImg()
        self.canvas.draw()

    def setSlider(self):
        global lastFrame
        #print('Set Slider Function Called')
        #print('Enable Slider')
        self.sl.setEnabled(True)
        #print('Set Minimum')
        self.sl.setMinimum(1)
        #print(lastFrame)
        #print('Set Maximum')
        self.sl.setMaximum(lastFrame)
        self.sl.setValue(1)
        self.sl.setTickPosition(QSlider.TicksBelow)
        self.sl.setTickInterval(9)
        self.slStartF.setText('First Frame: 1')
        self.slMidF.setText('Mid Frame: ' + str(lastFrame / 2))
        self.slEndF.setText('Last Frame: ' + str(lastFrame))
        self.slStartT.setText('0 Seconds')
        self.slMidT.setText(str(lastFrame / (2 * 9)) + ' Seconds')
        self.slEndT.setText(str(lastFrame / 9) + ' Seconds')

    def saveVideoSS(self):
        global frame
        global editLastFrame
        global videoState
        videoState = 'pause'
        if fileSelected != "":
            fileNameVid = ""
            dlgVid = QFileDialog()
            #dlg.setNameFilter('PNG files (*.png)')
            dlgVid.setDefaultSuffix('.avi')
            fileNameVid = dlgVid.getSaveFileName(
                self.w,
                'Navigate to Directory and Choose a File Name to Save To',
                'untitled.avi', 'AVI Video (*.avi)')
            #if self.startEdit.isModified():
            fileNameVid = str(fileNameVid)
            #if fileNameVid.endswith('.avi') == False:
            #	fileNameVid = fileNameVid + '.avi'
            frame = int(self.startEdit.text())
            #if self.stopEdit.isModified():
            editLastFrame = int(self.stopEdit.text())
            fourcc = cv2.cv.CV_FOURCC(*'XVID')
            if fileNameVid != "":
                try:
                    out = cv2.VideoWriter(fileNameVid, fourcc, 9.0, (640, 480),
                                          True)
                    for i in range(frame, editLastFrame):
                        frameForVid = self.grabDataFrame()
                        out.write(frameForVid)
                        if frame <= editLastFrame:
                            frame += framerate
                        else:
                            print('You are at Last Frame')
                    out.release()
                    print('Saved Video As ' + str(fileNameVid))
                    self.history.insertPlainText('SUCCESS: Saved Video\n')
                    self.history.moveCursor(QTextCursor.End)
                except:
                    self.history.insertPlainText(
                        'No AVI Video Generated\n Did Not Specify Proper FileName\n'
                    )
                    self.history.moveCursor(QTextCursor.End)
                    print('Did Not Specify Proper FileName')
                    print('No AVI Video Generated')
            else:
                self.history.insertPlainText(
                    'No AVI Video Generated\n Did Not Specify Proper FileName\n'
                )
                self.history.moveCursor(QTextCursor.End)
                print('Did Not Specify Proper FileName')
                print('No AVI Video Generated')

    def saveCvImage(self):
        global fileSelected
        global videoState
        videoState = 'pause'
        if fileSelected != "":
            dlg = QFileDialog()
            #dlg.setNameFilter('PNG files (*.png)')
            dlg.setDefaultSuffix('.png')
            fileNameImage = dlg.getSaveFileName(
                self.w,
                'Navigate to Directory and Choose a File Name to Save To',
                'untitled.png', 'PNG Image (*.png)')
            if fileNameImage != "":
                try:
                    print(fileNameImage)
                    cv2.imwrite(str(fileNameImage), self.grabDataFrame())
                    print('Saved frame ' + str(frame) + ' as .png')
                    self.history.insertPlainText('SUCCESS: Saved Frame: ' +
                                                 str(frame) + ' as PNG\n')
                    self.history.moveCursor(QTextCursor.End)
                except:
                    self.history.insertPlainText(
                        'No PNG Image Generated\n Did Not Specify Proper FileName\n'
                    )
                    self.history.moveCursor(QTextCursor.End)
                    print('Did Not Specify Proper FileName')
                    print('No PNG Image Generated')
            else:
                self.history.insertPlainText(
                    'No PNG Image Generated\n Did Not Specify Proper FileName\n'
                )
                self.history.moveCursor(QTextCursor.End)
                print('Did Not Specify Proper FileName')
                print('No PNG Image Generated')

    def makeTiff2(self):
        global lastFrame
        global fileSelected
        global videoState
        videoState = 'pause'
        if fileSelected != "":
            dlgTiff = QFileDialog()
            #dlg.setNameFilter('PNG files (*.png)')
            dlgTiff.setDefaultSuffix('.tiff')
            fileNameTiff = dlgTiff.getSaveFileName(
                self.w,
                'Navigate to Directory and Choose a File Name to Save To',
                'untitled.tiff', 'TIFF File (*.tiff)')
            print(fileNameTiff)
            if fileNameTiff != "":
                self.history.insertPlainText('File Name Selected\n')
                self.history.moveCursor(QTextCursor.End)
                print('Collecting Data Frames...')
                self.history.insertPlainText('Collecting Data Frames...\n')
                self.history.moveCursor(QTextCursor.End)
                for i in range(1, lastFrame):
                    data = self.f_read[('image' + str(i))][:]
                    if i == 1:
                        dataCollection = data
                    else:
                        dataCollection = np.dstack((dataCollection, data))
                    i += 1
                    if i == lastFrame / 2:
                        print('Half Way Through File...')
                        self.history.insertPlainText(
                            'Half Way Through File...\n')
                        self.history.moveCursor(QTextCursor.End)
                print('Completed Collecting All Data Frames')
                self.history.insertPlainText(
                    'Completed Collecting All Data Frames\n')
                self.history.moveCursor(QTextCursor.End)
                try:
                    imsave((str(fileNameTiff)), dataCollection)
                    print('Saved Tiff As ' + str(fileNameTiff))
                    self.history.insertPlainText(' Saved Tiff\n')
                    self.history.moveCursor(QTextCursor.End)
                except:
                    self.history.insertPlainText(
                        'No Tiff File Generated\n Did Not Specify Proper FileName\n'
                    )
                    self.history.moveCursor(QTextCursor.End)
                    print('Did Not Specify Proper FileName')
                    print('No Tiff File Generated')
            else:
                self.history.insertPlainText(
                    'No Tiff File Generated\n Did Not Specify Proper FileName\n'
                )
                self.history.moveCursor(QTextCursor.End)
                print('Did Not Specify Proper FileName')
                print('No Tiff File Generated')

    def grabTempValue(self):
        global frame
        global lastFrame
        global fileSelected
        global xMouse
        global yMouse
        data = self.f_read[('image' + str(frame))][:]
        data = cv2.resize(data[:, :], (640, 480))
        return data[yMouse, xMouse]

    def on_press(self, event):
        global xMouse
        global yMouse
        global cursorVal
        #print('you pressed', event.button, event.xdata, event.ydata)
        xMouse = event.xdata
        yMouse = event.ydata
        cursorVal = self.grabTempValue()
        self.cursorTempLabel.setText('Cursor Temp: ' +
                                     readTemp(toggleUnitState, 'none'))

    def hover(self, event):
        global xMouse
        global yMouse
        global cursorVal
        #print('you pressed', event.button, event.xdata, event.ydata)
        if event.xdata != None:
            xMouse = int(round(event.xdata))
            yMouse = int(round(event.ydata))
            cursorVal = int(round(self.grabTempValue()))
            #if xMouse > 1 and xMouse < 640 and yMouse > 0 and yMouse < 480:
            self.cursorTempLabel.setText('Cursor Temp: ' +
                                         readTemp(toggleUnitState, 'none'))
            #else:
            #self.cursorTempLabel.setText('Cursor Temp: MOVE CURSOR OVER IMAGE')
        else:
            #print('MOVE CURSOR OVER IMAGE')
            self.cursorTempLabel.setText('Cursor Temp: MOVE CURSOR OVER IMAGE')

    def displayTempValues(self):
        global fileSelected
        global toggleUnitState
        if fileSelected != "":
            self.maxTempLabel.setText('Current Max Temp: ' +
                                      readTemp(toggleUnitState, 'max'))
            self.maxTempLocLabel.setText('Max Temp Loc: ' + str(maxLoc))
            self.minTempLabel.setText('Current Min Temp: ' +
                                      readTemp(toggleUnitState, 'min'))
            self.minTempLocLabel.setText('Min Temp Loc: ' + str(minLoc))

    def grabDataFrame(self):
        global frame
        global lastFrame
        global fileSelected
        #print('Display Image at Frame: ' + str(frame))
        data = self.f_read[('image' + str(frame))][:]
        data = cv2.resize(data[:, :], (640, 480))
        img = cv2.LUT(raw_to_8bit(data), generate_colour_map())
        img2 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        rgbImage = cv2.cvtColor(img2, cv2.COLOR_BGR2RGB)
        return (rgbImage)

    def play(self):
        global frame
        global editLastFrame
        global fileSelected
        global videoState
        self.history.insertPlainText('Play Video\n')
        self.history.moveCursor(QTextCursor.End)
        #print(self.startEdit.text())
        if self.startEdit.isModified():
            frame = int(self.startEdit.text())
            print('Starting at Frame: ' + self.startEdit.text())
        if self.stopEdit.isModified():
            editLastFrame = int(self.stopEdit.text())
        if fileSelected != "":
            self.timer.start()
            videoState = 'play'

    def pauseVideo(self):
        global videoState
        self.history.insertPlainText('Paused Video\n')
        self.history.moveCursor(QTextCursor.End)
        videoState = 'pause'

    def playVid5(self):
        global videoState
        global frame
        global lastFrame
        global editLastFrame
        if videoState == 'play':
            if editLastFrame <= lastFrame:
                if frame <= editLastFrame:
                    self.sl.setValue(frame)
                    if frame != lastFrame:
                        frame += 1
                    #print('playing video')
                else:
                    print('You are at Stop Frame')
                    videoState = 'pause'
            else:
                print('You are at Last Frame')
                videoState = 'pause'

    def dispNextImg(self):
        global frame
        global lastFrame
        global framerate
        global fileSelected
        global videoState
        videoState = 'pause'
        self.history.insertPlainText('Next Frame: ' + str(frame) + '\n')
        self.history.moveCursor(QTextCursor.End)
        if fileSelected != "":
            if lastFrame > frame:
                frame += framerate
            else:
                print('You are at Last Frame')
            #self.dispImg()
            #self.canvas.draw()
            self.sl.setValue(frame)

    def dispPrevImg(self):
        global frame
        global fileSelected
        global videoState
        self.history.insertPlainText('Previous Frame: ' + str(frame) + '\n')
        self.history.moveCursor(QTextCursor.End)
        videoState = 'pause'
        if fileSelected != "":
            if frame > 1:
                frame -= 1
            else:
                print('You are at First Frame')
            #self.dispImg()
            #self.canvas.draw()
            self.sl.setValue(frame)

    def dispImg(self):
        global frame
        global lastFrame
        global fileSelected
        global maxVal
        global minVal
        global maxLoc
        global minLoc
        #if frame > 1:
        #self.cb.remove()
        #print('Display Image at Frame: ' + str(frame))
        self.currentFrameDisp.setText('Current Frame: ' + str(frame))
        data = self.f_read[('image' + str(frame))][:]
        data = cv2.resize(data[:, :], (640, 480))
        minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(data)
        img = cv2.LUT(raw_to_8bit(data), generate_colour_map())
        rgbImage = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
        self.ax = self.figure.add_subplot(111)
        self.ax.clear()
        #cmap = mpl.cm.cool
        #norm = mpl.colors.Normalize(vmin=5, vmax=10)
        #print('Ran dispImg')
        #print(frame)
        if frame == 1:
            self.figure.tight_layout()
        #colorVals = cm.get_clim(rgbImage)
        #print(colorVals)
        #cax = self.figure.add_axes([0.2, 0.08, 0.6, 0.04])
        #self.figure.colorbar(rgbImage, cax, orientation='horizontal')
        self.cax = self.ax.imshow(rgbImage)
        #self.cb = self.figure.colorbar(self.cax)
        lastFrame = len(self.f_read)
        self.sl.setValue(frame)
        self.displayTempValues()
        self.currentTimeLabel.setText('Current Time: ' +
                                      str(round(((frame - 1) / 9.00), 2)))
        cid = self.canvas.mpl_connect('motion_notify_event', self.hover)

    def enableThings(self):
        self.playVidBut.setEnabled(True)
        self.pauseVidBut.setEnabled(True)
        self.nextFrame.setEnabled(True)
        self.prevFrame.setEnabled(True)
        self.startEdit.setEnabled(True)
        self.stopEdit.setEnabled(True)
        self.saveAsVideoSS.setEnabled(True)
        self.saveCvImageBut.setEnabled(True)
        self.makeTiffBut.setEnabled(True)
        self.displayC.setEnabled(True)
        self.displayF.setEnabled(True)

    def getFile(self):
        global frame
        global fileSelected
        global editLastFrame
        global lastFrame
        #self.pauseVideo()
        fileSelected = ""
        fileSelected = QFileDialog.getOpenFileName(self.w, 'Open File', '/')
        print(fileSelected)
        #fileTypes = ['hdf5','HDF5','HD5F','hd5f']
        if fileSelected != "":
            #if any(x in fileSelected for x in fileTypes):
            try:
                self.dispSelectedFile.setText(fileSelected)
                self.f_read = h5py.File(str(fileSelected), 'r')
                self.dispImg()
                self.enableThings()
                self.setSlider()
                editLastFrame = lastFrame
                self.startEdit.setText(str(frame))
                self.stopEdit.setText(str(lastFrame))
                self.history.insertPlainText(
                    'Selected File and Displayed First Frame\n')
                self.history.moveCursor(QTextCursor.End)
                print('Selected File and Displayed First Frame')
                self.canvas.draw()
            #else:
            except:
                self.history.insertPlainText(
                    'ERROR: Incorrect File Type Selected\n Please select .HDF5 File\n'
                )
                self.history.moveCursor(QTextCursor.End)
                print(
                    'Incorrect File Type Selected. Please select .HDF5 File.')
        else:
            self.history.insertPlainText(
                'ERROR: Incorrect File Type Selected\n Please select .HDF5 File\n'
            )
            self.history.moveCursor(QTextCursor.End)
            print('Incorrect File Type Selected. Please select .HDF5 File.')
Example #41
0
class RunDialog(QDialog):
    def __init__(self, run_model, parent):
        QDialog.__init__(self, parent)
        self.setWindowFlags(Qt.Window)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setModal(True)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, BaseRunModel)
        self._run_model = run_model

        ert = None
        if isinstance(run_model, BaseRunModel):
            ert = run_model.ert()

        self.simulations_tracker = SimulationsTracker()
        states = self.simulations_tracker.getStates()
        self.state_colors = {state.name: state.color for state in states}
        self.state_colors['Success'] = self.state_colors["Finished"]
        self.state_colors['Failure'] = self.state_colors["Failed"]

        self.total_progress = SimpleProgress()

        status_layout = QHBoxLayout()
        status_layout.addStretch()
        self.__status_label = QLabel()
        status_layout.addWidget(self.__status_label)
        status_layout.addStretch()
        status_widget_container = QWidget()
        status_widget_container.setLayout(status_layout)

        self.progress = Progress()
        self.progress.setIndeterminateColor(self.total_progress.color)
        for state in states:
            self.progress.addState(state.state, QColor(*state.color),
                                   100.0 * state.count / state.total_count)

        legend_layout = QHBoxLayout()
        self.legends = {}
        for state in states:
            self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color))
            self.legends[state].updateLegend(state.name, 0, 0)
            legend_layout.addWidget(self.legends[state])

        legend_widget_container = QWidget()
        legend_widget_container.setLayout(legend_layout)

        self.running_time = QLabel("")

        self.plot_tool = PlotTool()
        self.plot_tool.setParent(None)
        self.plot_button = QPushButton(self.plot_tool.getName())
        self.plot_button.clicked.connect(self.plot_tool.trigger)
        self.plot_button.setEnabled(ert is not None)

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)
        self.restart_button = QPushButton("Restart")
        self.restart_button.setHidden(True)
        self.show_details_button = QPushButton("Details")
        self.show_details_button.setCheckable(True)

        size = 20
        spin_movie = resourceMovie("ide/loading.gif")
        spin_movie.setSpeed(60)
        spin_movie.setScaledSize(QSize(size, size))
        spin_movie.start()

        self.processing_animation = QLabel()
        self.processing_animation.setMaximumSize(QSize(size, size))
        self.processing_animation.setMinimumSize(QSize(size, size))
        self.processing_animation.setMovie(spin_movie)

        button_layout = QHBoxLayout()
        button_layout.addWidget(self.processing_animation)
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.show_details_button)
        button_layout.addWidget(self.plot_button)
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)
        button_layout.addWidget(self.restart_button)
        button_widget_container = QWidget()
        button_widget_container.setLayout(button_layout)

        self.detailed_progress = DetailedProgressWidget(
            self, self.state_colors)
        self.detailed_progress.setVisible(False)
        self.dummy_widget_container = QWidget(
        )  #Used to keep the other widgets from stretching

        layout = QVBoxLayout()
        layout.addWidget(self.total_progress)
        layout.addWidget(status_widget_container)
        layout.addWidget(self.progress)
        layout.addWidget(legend_widget_container)
        layout.addWidget(self.detailed_progress)
        layout.addWidget(self.dummy_widget_container)
        layout.addWidget(button_widget_container)

        layout.setStretch(0, 0)
        layout.setStretch(1, 0)
        layout.setStretch(2, 0)
        layout.setStretch(3, 0)
        layout.setStretch(4, 1)
        layout.setStretch(5, 1)
        layout.setStretch(6, 0)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)
        self.restart_button.clicked.connect(self.restart_failed_realizations)
        self.show_details_button.clicked.connect(self.toggle_detailed_progress)

        self.__updating = False
        self.__update_queued = False
        self.__simulation_started = False

        self.__update_timer = QTimer(self)
        self.__update_timer.setInterval(500)
        self.__update_timer.timeout.connect(self.updateRunStatus)
        self._simulations_argments = {}

    def closeEvent(self, QCloseEvent):
        if not self.checkIfRunFinished():
            #Kill jobs if dialog is closed
            if self.killJobs() != QMessageBox.Yes:
                QCloseEvent.ignore()

    def startSimulation(self, arguments):

        self._simulations_argments = arguments
        self._run_model.reset()

        def run():
            self._run_model.startSimulations(self._simulations_argments)

        simulation_thread = Thread(name="ert_gui_simulation_thread")
        simulation_thread.setDaemon(True)
        simulation_thread.run = run
        simulation_thread.start()

        self.__update_timer.start()

    def checkIfRunFinished(self):
        if self._run_model.isFinished():
            self.hideKillAndShowDone()

            if self._run_model.hasRunFailed():
                error = self._run_model.getFailMessage()
                QMessageBox.critical(
                    self, "Simulations failed!",
                    "The simulation failed with the following error:\n\n%s" %
                    error)

            return True
        return False

    def updateProgress(self):

        total_count = self._run_model.getQueueSize()
        queue_status = self._run_model.getQueueStatus()
        states = self.simulations_tracker.getStates()

        for state in states:
            state.count = 0
            state.total_count = total_count

        for state in states:
            for queue_state in queue_status:
                if queue_state in state.state:
                    state.count += queue_status[queue_state]

            self.progress.updateState(state.state,
                                      100.0 * state.count / state.total_count)
            self.legends[state].updateLegend(state.name, state.count,
                                             state.total_count)

    def updateRunStatus(self):
        self.__status_label.setText(self._run_model.getPhaseName())

        if self.checkIfRunFinished():
            self.total_progress.setProgress(self._run_model.getProgress())
            self.detailed_progress.set_progress(
                *self._run_model.getDetailedProgress())
            self.updateProgress()
            return

        self.total_progress.setProgress(self._run_model.getProgress())

        if self._run_model.isIndeterminate():
            self.progress.setIndeterminate(True)
            states = self.simulations_tracker.getStates()
            for state in states:
                self.legends[state].updateLegend(state.name, 0, 0)

        else:
            if self.detailed_progress and self.detailed_progress.isVisible():
                self.detailed_progress.set_progress(
                    *self._run_model.getDetailedProgress())
            else:
                self._run_model.updateDetailedProgress(
                )  #update information without rendering

            self.progress.setIndeterminate(False)
            self.updateProgress()

        self.setRunningTime()

    def setRunningTime(self):
        days = 0
        hours = 0
        minutes = 0
        seconds = self._run_model.getRunningTime()

        if seconds >= 60:
            minutes, seconds = divmod(seconds, 60)

        if minutes >= 60:
            hours, minutes = divmod(minutes, 60)

        if hours >= 24:
            days, hours = divmod(hours, 24)

        if days > 0:
            self.running_time.setText(
                "Running time: %d days %d hours %d minutes %d seconds" %
                (days, hours, minutes, seconds))
        elif hours > 0:
            self.running_time.setText(
                "Running time: %d hours %d minutes %d seconds" %
                (hours, minutes, seconds))
        elif minutes > 0:
            self.running_time.setText("Running time: %d minutes %d seconds" %
                                      (minutes, seconds))
        else:
            self.running_time.setText("Running time: %d seconds" % seconds)

    def killJobs(self):

        msg = "Are you sure you want to kill the currently running simulations?"
        if self._run_model.getQueueStatus().get(
                JobStatusType.JOB_QUEUE_UNKNOWN, 0) > 0:
            msg += "\n\nKilling a simulation with unknown status will not kill the realizations already submitted!"
        kill_job = QMessageBox.question(self, "Kill simulations?", msg,
                                        QMessageBox.Yes | QMessageBox.No)

        if kill_job == QMessageBox.Yes:
            if self._run_model.killAllSimulations():
                self.reject()
        return kill_job

    def hideKillAndShowDone(self):
        self.__update_timer.stop()
        self.processing_animation.hide()
        self.kill_button.setHidden(True)
        self.done_button.setHidden(False)
        self.detailed_progress.set_progress(
            *self._run_model.getDetailedProgress())
        self.restart_button.setVisible(self.has_failed_realizations())
        self.restart_button.setEnabled(self._run_model.support_restart)

    def has_failed_realizations(self):
        completed = self._run_model.completed_realizations_mask
        initial = self._run_model.initial_realizations_mask
        for (index, successful) in enumerate(completed):
            if initial[index] and not successful:
                return True
        return False

    def count_successful_realizations(self):
        """
        Counts the realizations completed in the prevoius ensemble run
        :return:
        """
        completed = self._run_model.completed_realizations_mask
        return completed.count(True)

    def create_mask_from_failed_realizations(self):
        """
        Creates a BoolVector mask representing the failed realizations
        :return: Type BoolVector
        """
        completed = self._run_model.completed_realizations_mask
        initial = self._run_model.initial_realizations_mask
        inverted_mask = BoolVector(default_value=False)
        for (index, successful) in enumerate(completed):
            inverted_mask[index] = initial[index] and not successful
        return inverted_mask

    def restart_failed_realizations(self):

        msg = QMessageBox(self)
        msg.setIcon(QMessageBox.Information)
        msg.setText(
            "Note that workflows will only be executed on the restarted realizations and that this might have unexpected consequences."
        )
        msg.setWindowTitle("Restart Failed Realizations")
        msg.setStandardButtons(QMessageBox.Ok | QMessageBox.Cancel)
        result = msg.exec_()

        if result == QMessageBox.Ok:
            self.restart_button.setVisible(False)
            self.kill_button.setVisible(True)
            self.done_button.setVisible(False)
            active_realizations = self.create_mask_from_failed_realizations()
            self._simulations_argments[
                'active_realizations'] = active_realizations
            self._simulations_argments[
                'prev_successful_realizations'] = self._simulations_argments.get(
                    'prev_successful_realizations', 0)
            self._simulations_argments[
                'prev_successful_realizations'] += self.count_successful_realizations(
                )
            self.startSimulation(self._simulations_argments)

    def toggle_detailed_progress(self):

        self.detailed_progress.setVisible(not (
            self.detailed_progress.isVisible()))
        self.dummy_widget_container.setVisible(not (
            self.detailed_progress.isVisible()))
        self.adjustSize()
Example #42
0
class PositionIndicator(QToolButton):
    """Indicator, which shows text "Line: yy Column: xx"
    """
    def __init__(self, parent):
        QToolButton.__init__(self, parent)
        self.setToolTip(self.tr("Cursor position"))
        self.setEnabled(False)
        self._setCursorPosition(-1, -1)
        minWidth = QFontMetrics(self.font()).width("Line: xxxxx Column: xxx")
        minWidth += 30  # for the button borders
        self.setMinimumWidth(
            minWidth)  # Avoid flickering when text width changed
        core.workspace().currentDocumentChanged.connect(
            self._onCurrentDocumentChanged)

        core.workspace().cursorPositionChanged.connect(
            self._onCursorPositionChanged)

        self._timer = QTimer()
        self._timer.setInterval(200)
        self._timer.setSingleShot(True)
        self._timer.timeout.connect(self._onUpdatePositionTimer)
        self._passedUpdate = False

    def __del__(self):
        if self._timer.isActive():
            self._timer.stop()

    def _onUpdatePositionTimer(self):
        """Update text on GUI according to current position
        """
        if self._passedUpdate:
            document = core.workspace().currentDocument()
            self._setCursorPosition(*document.qutepart.cursorPosition)
            self._passedUpdate = False

    def _onCursorPositionChanged(self, document):
        """Cursor position changed.
        Update it now or schedule update later
        """
        if self._timer.isActive():
            self._passedUpdate = True
        else:
            self._setCursorPosition(*document.qutepart.cursorPosition)
            self._timer.start()  # one more update after timeout.

    def _onCurrentDocumentChanged(self, oldDocument, currentDocument):
        """Current document has been changed
        """
        if self._timer.isActive():
            self._timer.stop()

        # Update connections
        if oldDocument is not None:
            self.clicked.disconnect(oldDocument.invokeGoTo)
        if currentDocument is not None:
            self.clicked.connect(currentDocument.invokeGoTo)

        # Update info
        if currentDocument is not None:
            self._setCursorPosition(*currentDocument.qutepart.cursorPosition)
            self.setEnabled(True)
        else:
            self._setCursorPosition(-1, -1)
            self.setEnabled(False)

    def _setCursorPosition(self, line, col):
        """Update cursor position on GUI.
        """
        template = self.tr("Line: %s Column: %s")
        if line != -1 and col != -1:
            line = str(line + 1)
            col = str(col)
        else:
            line = '-'
            col = '-'
        self.setText(template % (line, col))
Example #43
0
class GLPlotWidget(QGLWidget):
    # default window size
    width, height = 256, 256

    def __init__(self, parent):
        #print "GLPlotWidget.__init__"
        QGLWidget.__init__(self, parent)
        self.setMinimumSize(self.width, self.height)
        self.frameCount = 0
        # Set up a timer to call updateGL() every 0 ms
        self.timer = QTimer()
        self.timer.setInterval(10)
        #self.timer.timeout.connect(self.updateWidget)
        self.timer.timeout.connect(self.updateGL)
        #timer.timeout.connect( self.widget.update)
        #self.timer.start()

    def updateShader(self):
        #print "GLPlotWidget.updateShader"
        try:
            gl.glDeleteShader(self.shader)
        except:
            pass
        self.vertex_code = glu.DEFAULT_VERTEX_SHADER
        vs = glu.compile_vertex_shader(
            self.vertex_code)  # compile the vertex shader
        fs = glu.compile_fragment_shader(
            self.fragment_code)  # compile the fragment shader
        self.shader = glu.link_shader_program(vs,
                                              fs)  # compile the vertex shader
        gl.glUseProgram(self.shader)
        self.UNIFORM_LOCATIONS = {
            'iResolution': gl.glGetUniformLocation(self.shader, 'iResolution'),
            'iTime': gl.glGetUniformLocation(self.shader, 'iTime'),
            'iTimeDelta': gl.glGetUniformLocation(self.shader, 'iTimeDelta'),
            'iFrame': gl.glGetUniformLocation(self.shader, 'iFrame'),
            'iMouse': gl.glGetUniformLocation(self.shader, 'iMouse'),
            'iDate': gl.glGetUniformLocation(self.shader, 'iDate'),
            'iSampleRate': gl.glGetUniformLocation(self.shader, 'iSampleRate'),
        }
        #print self.UNIFORM_LOCATIONS
        gl.glUniform3f(self.UNIFORM_LOCATIONS['iResolution'], 1.0 * self.width,
                       1.0 * self.height, 1.0)
        self.update()

    def initializeGL(self):
        #print "GLPlotWidget.initializeGL"
        self.points = np.array([[-1.0, -1.0], [1.0, -1.0], [-1.0, 1.0],
                                [1.0, 1.0], [1.0, -1.0], [-1.0, 1.0]],
                               dtype=np.float32)
        self.vbo = glvbo.VBO(
            self.points
        )  # create a Vertex Buffer Object with the specified data
        self.updateShader()
        #gl.glClearColor(0, 0, 0, 0)          # background color
        self.frameCount = 0

    def paintGL(self):
        #print "GLPlotWidget.paintGL"
        #print "self.frameCount = ", self.frameCount
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)  # clear the buffer
        self.vbo.bind()  # bind the VBO
        gl.glEnableVertexAttribArray(0)
        gl.glVertexAttribPointer(
            0, 2, gl.GL_FLOAT, gl.GL_FALSE, 0,
            None)  # these vertices contain 2 single precision coordinates
        gl.glUseProgram(self.shader)
        mousePos = self.mapFromGlobal(QtGui.QCursor.pos())
        gl.glUniform1f(self.UNIFORM_LOCATIONS['iTime'], 0.01 * self.frameCount)
        gl.glUniform4f(self.UNIFORM_LOCATIONS['iMouse'], 0.1 * mousePos.x(),
                       0.1 * mousePos.y(), 0.0, 0.0)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0,
                        len(self.points))  # draw "count" points from the VBO
        self.frameCount += 1

    def resizeGL(self, width, height):
        #print "GLPlotWidget.resizeGL"
        self.width, self.height = width, height  # update the window size
        gl.glViewport(0, 0, width, height)  # paint within the whole window
        gl.glUniform3f(self.UNIFORM_LOCATIONS['iResolution'], 1.0 * self.width,
                       1.0 * self.height, 1.0)
Example #44
0
 def create_timer(self, timeout, callback):
     timer = QTimer(self)
     timer.setInterval(timeout)
     timer.setSingleShot(True)
     timer.timeout.connect(callback)
     return timer
Example #45
0
class PTCV2(COMCUPluginBase):
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletPTCV2, *args)

        self.ptc = self.device

        self.str_connected = 'Sensor is <font color="green">connected</font>'
        self.str_not_connected = 'Sensor is <font color="red">not connected</font>'

        self.cbe_temperature = CallbackEmulator(self.ptc.get_temperature,
                                                self.cb_temperature,
                                                self.increase_error_count)

        self.wire_label = QLabel('Wire Type:')
        self.wire_combo = QComboBox()
        self.wire_combo.addItem('2-Wire')
        self.wire_combo.addItem('3-Wire')
        self.wire_combo.addItem('4-Wire')

        self.noise_label = QLabel('Noise Rejection Filter:')
        self.noise_combo = QComboBox()
        self.noise_combo.addItem('50 Hz')
        self.noise_combo.addItem('60 Hz')

        self.connected_label = QLabel(self.str_connected)

        self.current_temperature = None # float, °C

        self.wire_combo.currentIndexChanged.connect(self.wire_combo_index_changed)
        self.noise_combo.currentIndexChanged.connect(self.noise_combo_index_changed)

        plots = [('Temperature', Qt.red, lambda: self.current_temperature, u'{} °C'.format)]
        self.plot_widget = PlotWidget(u'Temperature [°C]', plots, extra_key_widgets=[self.connected_label])

        hlayout = QHBoxLayout()
        hlayout.addWidget(self.wire_label)
        hlayout.addWidget(self.wire_combo)
        hlayout.addStretch()
        hlayout.addWidget(self.noise_label)
        hlayout.addWidget(self.noise_combo)

        line = QFrame()
        line.setFrameShape(QFrame.HLine)
        line.setFrameShadow(QFrame.Sunken)

        layout = QVBoxLayout(self)
        layout.addWidget(self.plot_widget)
        layout.addWidget(line)
        layout.addLayout(hlayout)

        self.connected_timer = QTimer()
        self.connected_timer.timeout.connect(self.update_connected)
        self.connected_timer.setInterval(1000)

    def start(self):
        async_call(self.ptc.get_temperature, None, self.cb_temperature, self.increase_error_count)
        self.cbe_temperature.set_period(100)

        async_call(self.ptc.is_sensor_connected, None, self.is_sensor_connected_async, self.increase_error_count)
        async_call(self.ptc.get_noise_rejection_filter, None, self.get_noise_rejection_filter_async, self.increase_error_count)
        async_call(self.ptc.get_wire_mode, None, self.get_wire_mode_async, self.increase_error_count)

        self.connected_timer.start()
        self.plot_widget.stop = False

    def stop(self):
        self.cbe_temperature.set_period(0)

        self.connected_timer.stop()
        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletPTCV2.DEVICE_IDENTIFIER

    def update_connected(self):
        async_call(self.ptc.is_sensor_connected, None, self.is_sensor_connected_async, self.increase_error_count)

    def wire_combo_index_changed(self, index):
        async_call(self.ptc.set_wire_mode, index+2, None, self.increase_error_count)

    def noise_combo_index_changed(self, index):
        async_call(self.ptc.set_noise_rejection_filter, index, None, self.increase_error_count)

    def is_sensor_connected_async(self, connected):
        if connected:
            self.connected_label.setText(self.str_connected)
        else:
            self.connected_label.setText(self.str_not_connected)

    def get_noise_rejection_filter_async(self, filter_option):
        self.noise_combo.setCurrentIndex(filter_option)

    def get_wire_mode_async(self, mode):
        self.wire_combo.setCurrentIndex(mode-2)

    def cb_temperature(self, temperature):
        self.current_temperature = temperature / 100.0

    def cb_resistance(self, resistance):
        resistance_str = str(round(resistance * 3900.0 / (1 << 15), 1))
        self.resistance_label.setText(resistance_str)
Example #46
0
class MinMaxSource(QObject):
    """
    A datasource that serves as a normalizing decorator for other datasources.
    """
    isDirty = pyqtSignal(object)
    boundsChanged = pyqtSignal(
        object
    )  # When a new min/max is discovered in the result of a request, this signal is fired with the new (dmin, dmax)
    numberOfChannelsChanged = pyqtSignal(int)

    _delayedBoundsChange = pyqtSignal(
    )  # Internal use only.  Allows non-main threads to start the delayedDirtySignal timer.

    def __init__(self, rawSource, parent=None):
        """
        rawSource: The original datasource whose data will be normalized
        """
        super(MinMaxSource, self).__init__(parent)

        self._rawSource = rawSource
        self._rawSource.isDirty.connect(self.isDirty)
        self._rawSource.numberOfChannelsChanged.connect(
            self.numberOfChannelsChanged)
        self._bounds = [1e9, -1e9]

        self._delayedDirtySignal = QTimer()
        self._delayedDirtySignal.setSingleShot(True)
        self._delayedDirtySignal.setInterval(10)
        self._delayedDirtySignal.timeout.connect(
            partial(self.setDirty, sl[:, :, :, :, :]))
        self._delayedBoundsChange.connect(self._delayedDirtySignal.start)

    @property
    def numberOfChannels(self):
        return self._rawSource.numberOfChannels

    def clean_up(self):
        self._rawSource.clean_up()

    @property
    def dataSlot(self):
        if hasattr(self._rawSource, "_orig_outslot"):
            return self._rawSource._orig_outslot
        else:
            return None

    def dtype(self):
        return self._rawSource.dtype()

    def request(self, slicing):
        rawRequest = self._rawSource.request(slicing)
        return MinMaxUpdateRequest(rawRequest, self._getMinMax)

    def setDirty(self, slicing):
        self.isDirty.emit(slicing)

    def __eq__(self, other):
        equal = True
        if other is None:
            return False
        equal &= isinstance(other, MinMaxSource)
        equal &= (self._rawSource == other._rawSource)
        return equal

    def __ne__(self, other):
        return not (self == other)

    def _getMinMax(self, data):
        dmin = np.min(data)
        dmax = np.max(data)
        dmin = min(self._bounds[0], dmin)
        dmax = max(self._bounds[1], dmax)
        dirty = False
        if (self._bounds[0] - dmin) > 1e-2:
            dirty = True
        if (dmax - self._bounds[1]) > 1e-2:
            dirty = True

        if dirty:
            self._bounds[0] = dmin
            self._bounds[1] = dmax
            self.boundsChanged.emit(self._bounds)

            # Our min/max have changed, which means we must force the TileProvider to re-request all tiles.
            # If we simply mark everything dirty now, then nothing changes for the tile we just rendered.
            # (It was already dirty.  That's why we are rendering it right now.)
            # And when this data gets back to the TileProvider that requested it, the TileProvider will mark this tile clean again.
            # To ENSURE that the current tile is marked dirty AFTER the TileProvider has stored this data (and marked the tile clean),
            #  we'll use a timer to set everything dirty.
            # This fixes ilastik issue #418

            # Finally, note that before this timer was added, the problem described above occurred at random due to a race condition:
            # Sometimes the 'dirty' signal was processed BEFORE the data (bad) and sometimes it was processed after the data (good),
            # due to the fact that the Qt signals are always delivered in the main thread.
            # Perhaps a better way to fix this would be to store a timestamp in the TileProvider for dirty notifications, which
            # could be compared with the request timestamp before clearing the dirty state for each tile.

            # Signal everything dirty with a timer, as described above.
            self._delayedBoundsChange.emit()

            # Now, that said, we can still give a slightly more snappy response to the OTHER tiles (not this one)
            # if we immediately tell the TileProvider we are dirty.  This duplicates some requests, but that shouldn't be a big deal.
            self.setDirty(sl[:, :, :, :, :])
Example #47
0
class RunDialog(QDialog):
    def __init__(self, run_model, run_arguments, parent):
        QDialog.__init__(self, parent)
        self.setWindowFlags(self.windowFlags()
                            & ~Qt.WindowContextHelpButtonHint)
        self.setWindowFlags(self.windowFlags() & ~Qt.WindowCloseButtonHint)
        self.setModal(True)
        self.setWindowModality(Qt.WindowModal)
        self.setWindowTitle("Simulations")

        assert isinstance(run_model, BaseRunModel)
        self._run_model = run_model
        self._run_arguments = run_arguments

        layout = QVBoxLayout()
        layout.setSizeConstraint(QLayout.SetFixedSize)

        self.simulations_tracker = SimulationsTracker()
        states = self.simulations_tracker.getStates()

        self.total_progress = SimpleProgress()
        layout.addWidget(self.total_progress)

        status_layout = QHBoxLayout()
        status_layout.addStretch()
        self.__status_label = QLabel()
        status_layout.addWidget(self.__status_label)
        status_layout.addStretch()
        layout.addLayout(status_layout)

        self.progress = Progress()
        self.progress.setIndeterminateColor(self.total_progress.color)
        for state in states:
            self.progress.addState(state.state, QColor(*state.color),
                                   100.0 * state.count / state.total_count)

        layout.addWidget(self.progress)

        legend_layout = QHBoxLayout()
        self.legends = {}
        for state in states:
            self.legends[state] = Legend("%s (%d/%d)", QColor(*state.color))
            self.legends[state].updateLegend(state.name, 0, 0)
            legend_layout.addWidget(self.legends[state])

        layout.addLayout(legend_layout)

        self.running_time = QLabel("")

        ert = None
        if isinstance(run_model, BaseRunModel):
            ert = run_model.ert()

        self.plot_tool = PlotTool()
        self.plot_tool.setParent(None)
        self.plot_button = QPushButton(self.plot_tool.getName())
        self.plot_button.clicked.connect(self.plot_tool.trigger)
        self.plot_button.setEnabled(ert is not None)

        self.kill_button = QPushButton("Kill simulations")
        self.done_button = QPushButton("Done")
        self.done_button.setHidden(True)

        button_layout = QHBoxLayout()

        size = 20
        spin_movie = resourceMovie("ide/loading.gif")
        spin_movie.setSpeed(60)
        spin_movie.setScaledSize(QSize(size, size))
        spin_movie.start()

        self.processing_animation = QLabel()
        self.processing_animation.setMaximumSize(QSize(size, size))
        self.processing_animation.setMinimumSize(QSize(size, size))
        self.processing_animation.setMovie(spin_movie)

        button_layout.addWidget(self.processing_animation)
        button_layout.addWidget(self.running_time)
        button_layout.addStretch()
        button_layout.addWidget(self.plot_button)
        button_layout.addWidget(self.kill_button)
        button_layout.addWidget(self.done_button)

        layout.addStretch()
        layout.addLayout(button_layout)

        self.setLayout(layout)

        self.kill_button.clicked.connect(self.killJobs)
        self.done_button.clicked.connect(self.accept)

        self.__updating = False
        self.__update_queued = False
        self.__simulation_started = False

        self.__update_timer = QTimer(self)
        self.__update_timer.setInterval(500)
        self.__update_timer.timeout.connect(self.updateRunStatus)

    def startSimulation(self):
        self._run_model.reset()

        def run():
            self._run_model.startSimulations(self._run_arguments)

        simulation_thread = Thread(name="ert_gui_simulation_thread")
        simulation_thread.setDaemon(True)
        simulation_thread.run = run
        simulation_thread.start()

        self.__update_timer.start()

    def checkIfRunFinished(self):
        if self._run_model.isFinished():
            self.hideKillAndShowDone()

            if self._run_model.hasRunFailed():
                error = self._run_model.getFailMessage()
                QMessageBox.critical(
                    self, "Simulations failed!",
                    "The simulation failed with the following error:\n\n%s" %
                    error)
                self.reject()

    def updateRunStatus(self):
        self.checkIfRunFinished()

        self.total_progress.setProgress(self._run_model.getProgress())

        self.__status_label.setText(self._run_model.getPhaseName())

        states = self.simulations_tracker.getStates()

        if self._run_model.isIndeterminate():
            self.progress.setIndeterminate(True)

            for state in states:
                self.legends[state].updateLegend(state.name, 0, 0)

        else:
            self.progress.setIndeterminate(False)
            total_count = self._run_model.getQueueSize()
            queue_status = self._run_model.getQueueStatus()

            for state in states:
                state.count = 0
                state.total_count = total_count

            for state in states:
                for queue_state in queue_status:
                    if queue_state in state.state:
                        state.count += queue_status[queue_state]

                self.progress.updateState(
                    state.state, 100.0 * state.count / state.total_count)
                self.legends[state].updateLegend(state.name, state.count,
                                                 state.total_count)

        self.setRunningTime()

    def setRunningTime(self):
        days = 0
        hours = 0
        minutes = 0
        seconds = self._run_model.getRunningTime()

        if seconds >= 60:
            minutes, seconds = divmod(seconds, 60)

        if minutes >= 60:
            hours, minutes = divmod(minutes, 60)

        if hours >= 24:
            days, hours = divmod(hours, 24)

        if days > 0:
            self.running_time.setText(
                "Running time: %d days %d hours %d minutes %d seconds" %
                (days, hours, minutes, seconds))
        elif hours > 0:
            self.running_time.setText(
                "Running time: %d hours %d minutes %d seconds" %
                (hours, minutes, seconds))
        elif minutes > 0:
            self.running_time.setText("Running time: %d minutes %d seconds" %
                                      (minutes, seconds))
        else:
            self.running_time.setText("Running time: %d seconds" % seconds)

    def killJobs(self):
        kill_job = QMessageBox.question(
            self, "Kill simulations?",
            "Are you sure you want to kill the currently running simulations?",
            QMessageBox.Yes | QMessageBox.No)

        if kill_job == QMessageBox.Yes:
            if self._run_model.killAllSimulations():
                self.reject()

    def hideKillAndShowDone(self):
        self.__update_timer.stop()
        self.processing_animation.hide()
        self.kill_button.setHidden(True)
        self.done_button.setHidden(False)
Example #48
0
class Progress(QFrame):
    def __init__(self):
        QFrame.__init__(self)
        self.setLineWidth(1)
        self.setFrameStyle(QFrame.Panel | QFrame.Plain)

        self.__color = QColor(255, 255, 255)

        self.setMinimumHeight(30)
        self.__state_order = []
        """@type: list of State"""

        self.__states = {}
        """@type: dict of (object, State)"""

        self.__shiny = False
        self.__count = 0

        self.__indeterminate = False
        self.__indeterminate_color = QColor(128, 128, 128)
        self.__indeterminate_state = 0.5
        self.__indeterminate_step_size = 0.05
        self.__timer = QTimer(self)
        self.__timer.setInterval(100)
        self.__timer.timeout.connect(self.update)

    def addState(self, state, state_color, progress=0.0):
        state_tracker = StateTracker(state, state_color, progress)
        self.__state_order.append(state_tracker)
        self.__states[state] = state_tracker

    def updateState(self, state, progress):
        self.__count += 1
        self.__states[state].setProgress(progress)
        self.update()

    def setIndeterminate(self, indeterminate):
        self.__indeterminate = indeterminate
        if indeterminate:
            self.__timer.start()
        else:
            self.__timer.stop()

    def setIndeterminateColor(self, color):
        self.__indeterminate_color = color

    def paintEvent(self, paint_event):
        QFrame.paintEvent(self, paint_event)
        painter = QPainter(self)
        painter.setRenderHint(QPainter.Antialiasing, True)
        painter.setRenderHint(QPainter.SmoothPixmapTransform, True)

        rect = self.contentsRect()
        """@type: QRect"""

        painter.fillRect(rect, self.__color)

        x = rect.x()
        y = rect.y()
        width = rect.width()
        height = rect.height()

        if not self.__indeterminate:
            count = len(self.__state_order)
            for index in range(count):
                state = self.__state_order[index]
                state_width = floor(width * (state.progress / 100.0))

                if index == count - 1:
                    state_width = width - x + 1

                painter.fillRect(x, y, state_width, height, state.color)

                x += state_width
        else:
            painter.fillRect(rect, self.__indeterminate_color)

            p = self.__indeterminate_state
            s = self.__indeterminate_step_size

            gradient = QLinearGradient(0,
                                       rect.height() / 2, rect.width(),
                                       rect.height() / 2)
            gradient.setColorAt(p - s, QColor(255, 255, 255, 0))
            gradient.setColorAt(p, QColor(255, 255, 255, 200))
            gradient.setColorAt(p + s, QColor(255, 255, 255, 0))
            painter.fillRect(rect, gradient)

            self.__indeterminate_state += s

            if self.__indeterminate_state + s >= 1.0 or self.__indeterminate_state + s <= 0.0:
                self.__indeterminate_step_size *= -1
                self.__indeterminate_state = round(
                    self.__indeterminate_state
                ) + self.__indeterminate_step_size

        if self.__shiny:
            #Shiny overlay!
            gradient = QLinearGradient(rect.width() / 2, 0,
                                       rect.width() / 2, rect.height())
            gradient.setColorAt(0, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.2, QColor(255, 255, 255, 200))
            gradient.setColorAt(0.4, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.85, QColor(255, 255, 255, 0))
            gradient.setColorAt(0.85, QColor(0, 0, 0, 0))
            gradient.setColorAt(1, QColor(0, 0, 0, 127))
            painter.fillRect(rect, gradient)
Example #49
0
class QtReactor(posixbase.PosixReactorBase):
    implements(IReactorFDSet)

    def __init__(self):
        self._reads = {}
        self._writes = {}
        self._notifiers = {}
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        QObject.connect(self._timer, SIGNAL("timeout()"), self.iterate)

        if QCoreApplication.instance() is None:
            # Application Object has not been started yet
            self.qApp = QCoreApplication([])
            self._ownApp = True
        else:
            self.qApp = QCoreApplication.instance()
            self._ownApp = False
        self._blockApp = None
        posixbase.PosixReactorBase.__init__(self)

    def _add(self, xer, primary, type):
        """
        Private method for adding a descriptor from the event loop.

        It takes care of adding it if  new or modifying it if already added
        for another state (read -> read/write for example).
        """
        if xer not in primary:
            primary[xer] = TwistedSocketNotifier(None, self, xer, type)

    def addReader(self, reader):
        """
        Add a FileDescriptor for notification of data available to read.
        """
        self._add(reader, self._reads, QSocketNotifier.Read)

    def addWriter(self, writer):
        """
        Add a FileDescriptor for notification of data available to write.
        """
        self._add(writer, self._writes, QSocketNotifier.Write)

    def _remove(self, xer, primary):
        """
        Private method for removing a descriptor from the event loop.

        It does the inverse job of _add, and also add a check in case of the fd
        has gone away.
        """
        if xer in primary:
            notifier = primary.pop(xer)
            notifier.shutdown()

    def removeReader(self, reader):
        """
        Remove a Selectable for notification of data available to read.
        """
        self._remove(reader, self._reads)

    def removeWriter(self, writer):
        """
        Remove a Selectable for notification of data available to write.
        """
        self._remove(writer, self._writes)

    def removeAll(self):
        """
        Remove all selectables, and return a list of them.
        """
        rv = self._removeAll(self._reads, self._writes)
        return rv

    def getReaders(self):
        return self._reads.keys()

    def getWriters(self):
        return self._writes.keys()

    def callLater(self, howlong, *args, **kargs):
        rval = super(QtReactor, self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval

    def reactorInvocation(self):
        self._timer.stop()
        self._timer.setInterval(0)
        self._timer.start()

    def _iterate(self, delay=None, fromqt=False):
        """See twisted.internet.interfaces.IReactorCore.iterate.
        """
        self.runUntilCurrent()
        self.doIteration(delay, fromqt)

    iterate = _iterate

    def doIteration(self, delay=None, fromqt=False):
        'This method is called by a Qt timer or by network activity on a file descriptor'

        if not self.running and self._blockApp:
            self._blockApp.quit()
        self._timer.stop()
        delay = max(delay, 1)
        if not fromqt:
            self.qApp.processEvents(QEventLoop.AllEvents, delay * 1000)
        if self.timeout() is None:
            timeout = 0.1
        elif self.timeout() == 0:
            timeout = 0
        else:
            timeout = self.timeout()
        self._timer.setInterval(timeout * 1000)
        self._timer.start()

    def runReturn(self, installSignalHandlers=True):
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self.reactorInvocation()

    def run(self, installSignalHandlers=True):
        if self._ownApp:
            self._blockApp = self.qApp
        else:
            self._blockApp = QEventLoop()
        self.runReturn()
        self._blockApp.exec_()
class PyQtPaint(QtGui.QWidget):
    """
    Canvas based painting ui w/ brush control, layers, undo functionality

    Attributes:
        color_dialog (QColorDialog): Color Picker
        file_dialog (QFileDialog): Filepath picker for saving img externally
        layers_tree (QTreeWidgetItem): Tree widget acting as a layers panel
        paint_scene (QGraphicsScene): graphics scene storing/maintaing stroke
                                      information
    Args:
        width (int): width of PyQtPaint
        height (int): height of PyQtPaint
    """
    def __init__(self, width, height, *args, **kwargs):
        super(PyQtPaint, self).__init__(*args, **kwargs)
        uic.loadUi('../ui/pyqtpaint.ui', self)

        self._paint_view = PaintView()
        self._paint_view.setRenderHints(QtGui.QPainter.HighQualityAntialiasing)

        self.paint_scene = PaintScene(0, 0, width, height, None)
        self._paint_view.setScene(self.paint_scene)

        # Numbers of layers
        self.num_layers = 0
        self.old_layers = -1

        # Timer to save images
        self.timer = QTimer()
        self.timer.setInterval(1000)
        self.timer.start()

        # Path to save imgs
        self.tmpFilepath = "../img/tmp/tmp.png"

        # Timer to predict shapes
        self.timer_predict = QTimer()
        self.timer_predict.setInterval(1000)
        self.timer_predict.start()

        # The app is not working on predict shapes
        self.working = False

        # Thread to run in background of paint
        self.threadpool = QThreadPool()

        # Setup all UI, and make the connctions between Signals & Slots
        self._setup_ui()
        self._create_actions()
        self._make_connections()

    def __del__(self):
        self.threadpool.deleteLater()

    def _setup_ui(self):
        self.viewport_widget.layout().addWidget(self._paint_view)
        self.layers_tree = LayerPanel(dragToggleColumns=[0], columns=['', ''])
        self.layers_tree.setItemDelegate(TreeDelegate())
        self.layers_widget.layout().addWidget(self.layers_tree)

        self.file_dialog = QtGui.QFileDialog(self)
        self.color_dialog = QtGui.QColorDialog()

        self._update_brush_ui()

    def _create_actions(self):
        self.undo_action = QtGui.QAction('Undo', self)
        self.undo_action.setShortcut('Ctrl+Z')
        self.addAction(self.undo_action)

        self.redo_action = QtGui.QAction('Redo', self)
        self.redo_action.setShortcut('Shift+Ctrl+Z')
        self.addAction(self.redo_action)

        self.delete_action = QtGui.QAction('Delete', self)
        self.delete_action.setShortcut('Backspace')
        self.addAction(self.delete_action)

        self.group_action = QtGui.QAction('Group', self)
        self.group_action.setShortcut('Ctrl+G')
        self.addAction(self.group_action)

        self.save_action = QtGui.QAction('Save', self)
        self.save_action.setShortcut('Ctrl+S')
        self.addAction(self.save_action)

        self.increase_size_action = QtGui.QAction('Increase Size', self)
        self.increase_size_action.setShortcut(']')
        self.addAction(self.increase_size_action)

        self.decrease_size_action = QtGui.QAction('Decrease Size', self)
        self.decrease_size_action.setShortcut('[')
        self.addAction(self.decrease_size_action)

###        self.brush_softer_action = QtGui.QAction('Brush Softer', self)
###        self.brush_softer_action.setShortcut('{')
###        self.addAction(self.brush_softer_action)

###        self.brush_harder_action = QtGui.QAction('Brush Harder', self)
###        self.brush_harder_action.setShortcut('}')
###        self.addAction(self.brush_harder_action)

    def _make_connections(self):
        self.paint_scene.strokeAdded.connect(self.create_layer_item)
        self.paint_scene.strokeRemoved.connect(self.remove_layer_item)

        self.paint_scene.brushChanged.connect(self._update_brush_ui)
        self.size_SLD.valueChanged.connect(
            lambda: self.set_pen_size(self.size_SLD.value()))
        ###        self.blur_SLD.valueChanged.connect(lambda: self.set_pen_blur(self.blur_SLD.value()))

        self.increase_size_action.triggered.connect(
            lambda: self.paint_scene.increment_pen_size(10))
        self.decrease_size_action.triggered.connect(
            lambda: self.paint_scene.increment_pen_size(-10))
        ###        self.brush_softer_action.triggered.connect(lambda: self.paint_scene.increment_pen_blur(1))
        ###        self.brush_harder_action.triggered.connect(lambda: self.paint_scene.increment_pen_blur(-1))

        self.redo_action.triggered.connect(self.paint_scene.undo_stack.redo)
        self.undo_action.triggered.connect(self.paint_scene.undo_stack.undo)

        self.delete_action.triggered.connect(self.delete_layer)
        self.group_action.triggered.connect(self.group_layers)

        self.save_action.triggered.connect(self.save_img)

        self.layers_tree.itemChanged.connect(self.layer_change)
        self.layers_tree.layerOrderChanged.connect(self.update_layer_index)

        self.color_BTN.clicked.connect(self.update_pen_color)

        self.timer.timeout.connect(self.on_timer)
        self.timer_predict.timeout.connect(self.predict)

        self.connect(self, QtCore.SIGNAL('triggered'), self.closeEvent)

    def _update_brush_ui(self):
        self.size_SLD.setValue(self.paint_scene.pen_size)
        ###        self.blur_SLD.setValue(self.paint_scene.pen_blur)

        style = QString("QPushButton { border-style: none; \
                                              border-radius: 10px; \
                                              min-width: 3em; \
                                              height: 3em; \
                                              background-color: " +
                        self.paint_scene.pen_color.name() + "}")
        self.color_BTN.setStyleSheet(style)

    def create_layer_item(self, stroke_id, layer_name):
        """
        Creates layer item in layer panel using stroke data

        Args:
            stroke_id (int): unique index of stroke
            layer_name (str): name of stroke layer

        """
        stroke_info = ['', layer_name]
        layer = Layer(stroke_info, stroke_index=stroke_id)

        self.num_layers += 1
        highest_group = None
        if self.layers_tree.selectedItems():
            iterator = QtGui.QTreeWidgetItemIterator(self.layers_tree)
            while iterator.value():
                item = iterator.value()
                if isinstance(
                        item,
                        Folder) and item in self.layers_tree.selectedItems():
                    highest_group = item
                    break
                iterator += 1
        if highest_group:
            highest_group.insertChild(0, layer)
        else:
            self.layers_tree.insertTopLevelItem(0, layer)
        self.update_layer_index()

    def remove_layer_item(self, stroke_id):
        """
        deletes layer item in layer panel

        Args:
            stroke_id (int): unique index of stroke to be removed

        """
        iterator = QtGui.QTreeWidgetItemIterator(self.layers_tree)
        self.num_layers -= 1

        while iterator.value():
            item = iterator.value()
            if isinstance(item, Layer):
                layer_data = item.data(1, Qt.UserRole).toPyObject()[0]
                if layer_data['stroke_index'] == stroke_id:
                    parent = item.parent()
                    if parent:
                        idx = parent.indexOfChild(item)
                        parent.takeChild(idx)
                    else:
                        idx = self.layers_tree.indexOfTopLevelItem(item)
                        self.layers_tree.takeTopLevelItem(idx)
            if isinstance(item, Folder):
                layer_data = item.data(1, Qt.UserRole).toPyObject()[0]

                if item.group_index == stroke_id:
                    parent = item.parent()
                    if parent:
                        idx = parent.indexOfChild(item)
                        parent.takeChild(idx)
                    else:
                        idx = self.layers_tree.indexOfTopLevelItem(item)
                        self.layers_tree.takeTopLevelItem(idx)
            iterator += 1

    def layer_change(self, item, column):
        """
        updates stroke information, used when updating visibility or layer name

        Args:
            item (QTreeWidgetItem): item associated with stroke
            column (int): column to change
        """
        if column == 0:
            if isinstance(item, Layer):
                self.paint_scene.toggle_layer_visibility(
                    item.stroke_index, item.visible)

            elif isinstance(item, Folder):
                for i in range(item.childCount()):
                    if item.visible is True:
                        item.child(i).setFlags(Qt.ItemIsSelectable
                                               | Qt.ItemIsEditable
                                               | Qt.ItemIsEnabled
                                               | Qt.ItemIsDragEnabled)
                    else:
                        item.child(i).setFlags(Qt.NoItemFlags)
                    self.paint_scene.toggle_layer_visibility(
                        item.child(i).stroke_index, item.visible)

        elif column == 1:
            if isinstance(item, Layer):
                self.paint_scene.update_layer_name(item.stroke_index,
                                                   item.text(1))

    def delete_layer(self):
        """
        Deletes selected layers
        """
        for item in self.layers_tree.selectedItems():
            # remove item.stroke_index
            if isinstance(item, Layer):
                if item.parent():
                    command = DeleteStroke(self, item, group=item.parent())
                    self.paint_scene.undo_stack.push(command)
                else:
                    command = DeleteStroke(self, item)
                    self.paint_scene.undo_stack.push(command)

            if isinstance(item, Folder):
                command = DeleteGroup(self, item)
                self.paint_scene.undo_stack.push(command)

    def group_layers(self):
        """
        groups seleted layers

        """
        if self.layers_tree.selectedItems():
            grab_items = []
            for item in self.layers_tree.selectedItems():
                if isinstance(item, Layer):
                    grab_items.append(item.stroke_index)

            command = GroupStrokes(self, grab_items)
            self.paint_scene.undo_stack.push(command)

    def update_layer_index(self):
        """
        iterates through layer panel & updates stacking order of strokes

        """
        iterator = QtGui.QTreeWidgetItemIterator(self.layers_tree)
        while iterator.value():
            item = iterator.value()
            target_index = self.layers_tree.indexFromItem(item).row()
            try:
                new_indx = len(self.paint_scene.strokes) - target_index
                self.paint_scene.set_stroke_zindex(item._stroke_index,
                                                   new_indx)
            except AttributeError:
                pass

            if isinstance(item, Layer):
                layer_data = item.data(1, Qt.UserRole).toPyObject()[0]
                parent = item.parent()
                if not parent:
                    layer_data['layerType'] = 0
                else:
                    layer_data['layerType'] = 2

                varient = QVariant((layer_data, ))
                item.setData(1, Qt.UserRole, varient)

            elif isinstance(item, Folder):
                for i in range(item.childCount()):
                    if item.visible is True:
                        item.child(i).setFlags(Qt.ItemIsSelectable
                                               | Qt.ItemIsEditable
                                               | Qt.ItemIsEnabled
                                               | Qt.ItemIsDragEnabled)
                    else:
                        item.child(i).setFlags(Qt.NoItemFlags)
                    self.paint_scene.toggle_layer_visibility(
                        item.child(i).stroke_index, item.visible)
            iterator += 1

    def set_pen_size(self, size):
        """
        Sets pen size from slider input

        Args:
            size (int): diameter of pen
        """
        self.paint_scene.set_pen_size(size)
        self._update_brush_ui()

    def set_pen_blur(self, blur):
        """
        Sets pen blur

        Args:
            blur (int): level of blur
        """
        self.paint_scene.set_pen_blur(blur)
        self._update_brush_ui()

    def set_pen_color(self, color):
        """
        sets pen color

        Args:
            color (QColor): color to set
        """
        self.paint_scene.set_pen_color(color)
        self._update_brush_ui()

    def update_pen_color(self):
        """
        updates pen color from color picker
        """
        color = self.color_dialog.getColor(self.paint_scene.pen_color, self,
                                           QString('Color'),
                                           QtGui.QColorDialog.ShowAlphaChannel)
        self.paint_scene.set_pen_color(color)

        style = QString("QPushButton { border-style: none; \
                                              border-radius: 10px; \
                                              min-width: 3em; \
                                              height: 3em; \
                                              background-color: " +
                        color.name() + "}")
        self.color_BTN.setStyleSheet(style)

    def on_timer(self):
        """
        saves image to temporary file
        
        if self.num_layers != self.old_layers :
            self.old_layers = self.num_layers
            """
        img = self.get_img()
        img.save(self.tmpFilepath)

    def save_img(self):
        """
        saves image to file
        """
        filepath = self.file_dialog.getSaveFileName(self, "Save Canvas",
                                                    "Render",
                                                    "Images (*.png *.jpg)")
        if filepath:
            img = self.get_img()
            img.save(filepath)

    def get_img(self):
        """
        gets image from PyQtPaint

        Returns:
            img: returns QImage data from canvas
        """
        img = QtGui.QImage(self.paint_scene.width, self.paint_scene.height,
                           QtGui.QImage.Format_RGB32)
        paint = QtGui.QPainter(img)
        paint.setRenderHint(QtGui.QPainter.Antialiasing)
        self.paint_scene.render(paint)
        paint.end()
        return img

    """
    HFNet function by Hebb rule
    """

    def predict(self):
        if not self.working:
            self.working = True
            predict = Predict(_predict.predict)
            predict.signals.result.connect(self.print_output)
            predict.signals.finished.connect(self.thread_complete)

            # Execute
            self.threadpool.start(predict)

    def thread_complete(self):
        self.working = False
        print("THREAD COMPLETE!")

    def print_output(self, s):
        ##self.resulted = int(s)
        if s == 0:
            self.results.setText(u"É um retângulo.")
        elif s == 1:
            self.results.setText(u"Catetos, catetos, catetos...")
        elif s == 2:
            self.results.setText(u"Catetos, catetos, catetos...")
        elif s == 3:
            self.results.setText(u"Catetos, catetos, catetos...")
        elif s == 4:
            self.results.setText(u"É círculo")
        else:
            self.results.setText(u"Sei lá")
        ##print(s)

    def progress_fn(self, n):
        print("%d%% done" % n)
Example #51
0
class MainDialog(QDialog,soundmeterGUI.Ui_Dialog):
    def __init__(self,parent=None):
            super(MainDialog,self).__init__(parent)
            self.setupUi(self)
            self.mesure = False
            self.timer = QTimer(self)
            self.timer.timeout.connect(self.acquerirMesures)
            self.timer.setInterval(200)
            
            self.graph.setTitle("Sound Level")
            self.graph.setAxisTitle(0 ,"Sound Level (dBA)")
            self.graph.setAxisTitle(2 ,"Time (x10ms)")
            self.graph.setAxisScale(2,0,21,0)
            self.graph.setAxisScale(0,0,160,0)
            self.graph.setCanvasBackground(Qt.Qt.white)
            self.curveR = Qwt.QwtPlotCurve("Data Moving Right")
            self.curveR.attach(self.graph)
            pen = Qt.QPen(Qt.Qt.green)
            pen.setWidth(5)
            self.curveR.setPen(pen)
            self.x = range(0,21)
            self.y = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
            self.seuil = 60.0
            self.filename = "sound"+str(1)+".csv"
            self.t = 0
             

            
    def demarrerMesure(self):
        self.pbArreter.setEnabled(True)
        self.pbDemarrer.setEnabled(False)        
        self.timer.start()
        self.file = open(self.filename,"w") 
        self.t = 0
        
        
    def arreterMesure(self):
        self.pbDemarrer.setEnabled(True)
        self.pbArreter.setDisabled(True)
        self.timer.stop()
        self.file.close()
        
    def modifierSeuil(self):
        self.seuil = float(self.leSeuil.text())
        self.jauge.setAlarmLevel(self.seuil)
        
    def acquerirMesures(self):  
        i=0  
        max = 0.0
        self.ser = serial.Serial('COM23', 9600)
        self.mesure = True
        
        while i<21:
            lecture = self.ser.read()
            lecture = ord(lecture)
            
            if (lecture == 165):
                lecture = self.ser.read()
                lecture = ord(lecture)
            #        print(lecture) #on affiche la reponse
                if (lecture == 27):
                    self.lblUnite.setText("dbA")
                    self.graph.setAxisTitle(0 ,"Sound Level (dBA)")
                if (lecture == 28):
                    self.lblUnite.setText("dbC")
                    self.graph.setAxisTitle(0 ,"Sound Level (dBC)")
                if (lecture == 13):
                    dat = self.ser.read(2)
                    dat = map(ord, dat)
                    sound = dat[0]*10+dat[1]*0.1
                    self.jauge.setValue(sound)
                    #print (sound)
                    for j in range(len(self.y)-2,-1,-1):
                        self.y[j+1]=self.y[j]
                                
                    self.y[0] = sound
                    if sound>self.seuil:
                        pen = Qt.QPen(Qt.Qt.red)
                        pen.setWidth(5)
                        self.curveR.setPen(pen)
                    else:
                        pen = Qt.QPen(Qt.Qt.green)
                        pen.setWidth(5)
                        self.curveR.setPen(pen)
                    print self.y
                    self.file.write(str(self.t*20+i)+";"+str(sound)+"\n")
                    print "\n"
                    self.curveR.setData(self.x, self.y)
                    self.graph.replot()
                    if sound > max:
                        max=sound
                    i=i+1
                    
        self.ser.close()  
        self.lcdNumber.display(max)
        self.t=self.t+1
Example #52
0
class ParticulateMatter(COMCUPluginBase):
    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletParticulateMatter, *args)

        self.pm = self.device

        self.cbe_pm_concentration = CallbackEmulator(
            self.pm.get_pm_concentration, self.cb_pm_concentration,
            self.increase_error_count)

        self.cbe_pm_count = CallbackEmulator(self.pm.get_pm_count,
                                             self.cb_pm_count,
                                             self.increase_error_count)

        self.current_pm_concentration_pm10 = None
        self.current_pm_concentration_pm25 = None
        self.current_pm_concentration_pm100 = None

        plots = [
            ('PM1.0', Qt.red, lambda: self.current_pm_concentration_pm10,
             u'{} µg/m³'.format),
            ('PM2.5', Qt.darkGreen, lambda: self.current_pm_concentration_pm25,
             u'{} µg/m³'.format),
            ('PM10.0', Qt.blue, lambda: self.current_pm_concentration_pm100,
             u'{} µg/m³'.format)
        ]
        self.plot_widget = PlotWidget(u'PM Concentration [µg/m³]', plots)

        self.label_count = QLabel(
            u'PM Count > 0.3, 0.5, 1.0, 2.5, 5.0, 10.0 µm:')
        self.label_count_value = QLabel('0, 0, 0, 0, 0, 0')

        self.check_enable_sensor = QCheckBox('Enable Sensor')
        self.check_enable_sensor.stateChanged.connect(
            self.enable_sensor_changed)

        self.label_sensor_version = QLabel('Sensor Version:')
        self.label_sensor_version_value = QLabel('0')

        self.label_last_error_code = QLabel('Last Error Code:')
        self.label_last_error_code_value = QLabel('0')

        self.label_framing_errors = QLabel('Framing Errors:')
        self.label_framing_errors_value = QLabel('0')

        self.label_checksum_errors = QLabel('Checksum Errors:')
        self.label_checksum_errors_value = QLabel('0')

        layout_sub1 = QHBoxLayout()
        layout_sub1.addWidget(self.label_count)
        layout_sub1.addWidget(self.label_count_value)
        layout_sub1.addStretch()
        layout_sub1.addWidget(self.check_enable_sensor)

        layout_sub2 = QHBoxLayout()
        layout_sub2.addWidget(self.label_sensor_version)
        layout_sub2.addWidget(self.label_sensor_version_value)
        layout_sub2.addStretch()
        layout_sub2.addWidget(self.label_last_error_code)
        layout_sub2.addWidget(self.label_last_error_code_value)
        layout_sub2.addStretch()
        layout_sub2.addWidget(self.label_framing_errors)
        layout_sub2.addWidget(self.label_framing_errors_value)
        layout_sub2.addStretch()
        layout_sub2.addWidget(self.label_checksum_errors)
        layout_sub2.addWidget(self.label_checksum_errors_value)

        layout_main = QVBoxLayout(self)
        layout_main.addWidget(self.plot_widget)
        layout_main.addLayout(layout_sub1)
        layout_main.addLayout(layout_sub2)

        self.sensor_info_timer = QTimer(self)
        self.sensor_info_timer.timeout.connect(self.update_sensor_info)
        self.sensor_info_timer.setInterval(1000)

    def enable_sensor_changed(self, state):
        self.pm.set_enable(state == Qt.Checked)

    def start(self):
        async_call(self.pm.get_pm_concentration, None,
                   self.cb_pm_concentration, self.increase_error_count)
        async_call(self.pm.get_pm_count, None, self.cb_pm_count,
                   self.increase_error_count)
        async_call(self.pm.get_enable, None, self.get_enable_async,
                   self.increase_error_count)

        self.cbe_pm_concentration.set_period(100)
        self.cbe_pm_count.set_period(100)

        self.plot_widget.stop = False

        self.update_sensor_info()
        self.sensor_info_timer.start()

    def stop(self):
        self.sensor_info_timer.stop()

        self.cbe_pm_concentration.set_period(0)
        self.cbe_pm_count.set_period(0)

        self.plot_widget.stop = True

    def destroy(self):
        pass

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletParticulateMatter.DEVICE_IDENTIFIER

    def cb_pm_concentration(self, pm_concentration):
        self.current_pm_concentration_pm10 = pm_concentration.pm10
        self.current_pm_concentration_pm25 = pm_concentration.pm25
        self.current_pm_concentration_pm100 = pm_concentration.pm100

    def cb_pm_count(self, pm_count):
        self.label_count_value.setText(', '.join(map(str, pm_count)))

    def get_enable_async(self, enable):
        self.check_enable_sensor.setChecked(enable)

    def update_sensor_info(self):
        async_call(self.pm.get_sensor_info, None, self.get_sensor_info_async,
                   self.increase_error_count)

    def get_sensor_info_async(self, info):
        self.label_sensor_version_value.setText(str(info.sensor_version))
        self.label_last_error_code_value.setText(str(info.last_error_code))
        self.label_framing_errors_value.setText(str(info.framing_error_count))
        self.label_checksum_errors_value.setText(str(
            info.checksum_error_count))
class QTReactor(PosixReactorBase):
    """
    Qt based reactor.
    """
    implements(IReactorFDSet)

    _timer = None

    def __init__(self):
        self._reads = {}
        self._writes = {}
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        if QCoreApplication.startingUp():
            self.qApp = QCoreApplication([])
            self._ownApp = True
        else:
            self.qApp = QCoreApplication.instance()
            self._ownApp = False
        self._blockApp = None
        self._readWriteQ = []
        """ some debugging instrumentation """
        self._doSomethingCount = 0

        PosixReactorBase.__init__(self)

    def addReader(self, reader):
        if not reader in self._reads:
            self._reads[reader] = TwistedSocketNotifier(
                self, reader, QSocketNotifier.Read)

    def addWriter(self, writer):
        if not writer in self._writes:
            self._writes[writer] = TwistedSocketNotifier(
                self, writer, QSocketNotifier.Write)

    def removeReader(self, reader):
        if reader in self._reads:
            #self._reads[reader].shutdown()
            #del self._reads[reader]
            self._reads.pop(reader).shutdown()

    def removeWriter(self, writer):
        if writer in self._writes:
            self._writes[writer].shutdown()
            #del self._writes[writer]
            self._writes.pop(writer)

    def removeAll(self):
        return self._removeAll(self._reads, self._writes)

    def getReaders(self):
        return self._reads.keys()

    def getWriters(self):
        return self._writes.keys()

    def callLater(self, howlong, *args, **kargs):
        rval = super(QTReactor, self).callLater(howlong, *args, **kargs)
        self.reactorInvocation()
        return rval

    def crash(self):
        super(QTReactor, self).crash()

    def iterate(self, delay=0.0):
        t = self.running  # not sure I entirely get the state of running
        self.running = True
        self._timer.stop()  # in case its not (rare?)
        try:
            if delay == 0.0:
                self.reactorInvokePrivate()
                self._timer.stop()  # supports multiple invocations
            else:
                endTime = delay + time.time()
                self.reactorInvokePrivate()
                while True:
                    t = endTime - time.time()
                    if t <= 0.0: return
                    self.qApp.processEvents(
                        QEventLoop.AllEvents | QEventLoop.WaitForMoreEvents,
                        t * 1010)
        finally:
            self.running = t

    def addReadWrite(self, t):
        self._readWriteQ.append(t)

    def runReturn(self, installSignalHandlers=True):
        QObject.connect(self._timer, SIGNAL("timeout()"),
                        self.reactorInvokePrivate)
        self.startRunning(installSignalHandlers=installSignalHandlers)
        self._timer.start(0)

    def run(self, installSignalHandlers=True):
        try:
            if self._ownApp:
                self._blockApp = self.qApp
            else:
                self._blockApp = fakeApplication()
            self.runReturn(installSignalHandlers)
            self._blockApp.exec_()
        finally:
            self._timer.stop()  # should already be stopped

    def reactorInvocation(self):
        self._timer.setInterval(0)

    def reactorInvokePrivate(self):
        if not self.running:
            self._blockApp.quit()
        self._doSomethingCount += 1
        self.runUntilCurrent()
        t = self.timeout()
        if t is None: t = 0.1
        else: t = min(t, 0.1)
        self._timer.setInterval(t * 1010)
        self.qApp.processEvents()  # could change interval
        self._timer.start()

    def doIteration(self):
        assert False, "doiteration is invalid call"
Example #54
0
class MainWindow(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, arena, parent=None):
        """
        Constructor
        """
        QMainWindow.__init__(self, parent)
        self.arena = arena
        self.setupUi(self)
        self.countBattle = 0
        self.timer = QTimer()
        self.tableWidget.horizontalHeader().setResizeMode(
            QtGui.QHeaderView.Stretch)
        self.tableWidget.hide()

    @pyqtSignature("")
    def on_pushButton_clicked(self):
        """
        Start the last battle
        """

        with open(os.getcwd() + "/.datas/" + self.arena, 'rb') as file:
            unpickler = pickle.Unpickler(file)
            dico = unpickler.load()
        file.close()

        self.setUpBattle(dico["width"], dico["height"], dico["botList"])

    def setArenaName(arenaName, self):
        self.arena = arenaName

    def setUpBattle(self, width, height, botList):
        self.tableWidget.clearContents()
        self.tableWidget.hide()
        self.graphicsView.show()
        self.width = width
        self.height = height
        self.botList = botList
        self.statisticDico = {}
        for bot in botList:
            self.statisticDico[self.repres(bot)] = statistic()
        self.startBattle()

    def startBattle(self):

        try:
            self.disconnect(self.timer, SIGNAL("timeout()"),
                            self.scene.advance)
            del self.timer
            del self.scene
            del self.sceneMenu
        except:
            pass

        self.timer = QTimer()
        self.countBattle += 1
        self.sceneMenu = QGraphicsScene()
        self.graphicsView_2.setScene(self.sceneMenu)
        self.scene = Graph(self, self.width, self.height)
        self.graphicsView.setScene(self.scene)
        self.scene.AddRobots(self.botList)
        self.connect(self.timer, SIGNAL("timeout()"), self.scene.advance)
        self.timer.start((self.horizontalSlider.value()**2) / 100.0)
        self.resizeEvent()

    @pyqtSignature("int")
    def on_horizontalSlider_valueChanged(self, value):
        """
        Slot documentation goes here.
        """
        self.timer.setInterval((value**2) / 100.0)

    @pyqtSignature("")
    def on_actionNew_activated(self):
        """
        Battle Menu
        """
        self.battleMenu = Battle(self, arena)
        self.battleMenu.show()

    @pyqtSignature("")
    def on_actionNew_2_activated(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        print "Not Implemented Yet"

    @pyqtSignature("")
    def on_actionOpen_activated(self):
        """
        Slot documentation goes here.
        """
        # TODO: not implemented yet
        print "Not Implemented Yet"

    def resizeEvent(self, evt=None):
        try:
            self.graphicsView.fitInView(self.scene.sceneRect(), 4)
        except:
            pass

    def addRobotInfo(self, robot):
        self.sceneMenu.setSceneRect(0, 0, 170, 800)
        rb = RobotInfo()
        rb.pushButton.setText(str(robot))
        rb.progressBar.setValue(100)
        rb.robot = robot
        robot.info = rb
        robot.progressBar = rb.progressBar
        robot.icon = rb.toolButton
        robot.icon2 = rb.toolButton_2
        p = self.sceneMenu.addWidget(rb)
        l = (len(self.scene.aliveBots))
        self.sceneMenu.setSceneRect(0, 0, 170, l * 80)
        p.setPos(0, (l - 1) * 80)

    def chooseAction(self):
        if self.countBattle >= self.spinBox.value():
            "Menu Statistic"
            self.graphicsView.hide()
            self.tableWidget.show()
            self.tableWidget.setRowCount(len(self.statisticDico))
            i = 0
            for key, value in self.statisticDico.items():
                self.tableWidget.setItem(i, 0, QtGui.QTableWidgetItem(key))
                self.tableWidget.setItem(
                    i, 1, QtGui.QTableWidgetItem(str(value.first)))
                self.tableWidget.setItem(
                    i, 2, QtGui.QTableWidgetItem(str(value.second)))
                self.tableWidget.setItem(
                    i, 3, QtGui.QTableWidgetItem(str(value.third)))
                self.tableWidget.setItem(
                    i, 4, QtGui.QTableWidgetItem(str(value.points)))

                i += 1

            self.countBattle = 0
            self.timer.stop()
        else:
            self.startBattle()

    def repres(self, bot):
        repres = repr(bot).split(".")
        return repres[1].replace("'>", "")
Example #55
0
class Panel(QWidget):
    def __init__(self,
                 parent=None,
                 instr=None,
                 lock=None,
                 title='Instrument Panel'):
        # This class derivates from a Qt Widget so we have to call
        # the class builder ".__init__()"
        QWidget.__init__(self)
        # "self" is now a Qt Widget, then we load the user interface
        # generated with QtDesigner and call it self.ui
        self.ui = Keithley6221_Ui.Ui_Panel()
        # Now we have to feed the GUI building method of this object (self.ui)
        # with the current Qt Widget 'self', but the widgets from the design will actually be built as children
        # of the object self.ui
        self.ui.setupUi(self)
        self.setWindowTitle(title)
        self.reserved_access_to_instr = lock
        self.instr = instr
        self.monitor_timer = QTimer()
        #The timer would not wait for the completion of the task otherwise
        self.monitor_timer.setSingleShot(True)
        self.monitor_timer.timeout.connect(self.monitor)
        self.firsttime = 0
        #bug: if the box is checked in the .ui file, the system freezes
        #if self.ui.monitor.isChecked():self.monitor()

    def monitor(self, state=1):
        if state != 1:
            self.monitor_timer.stop()
        elif state and not (self.monitor_timer.isActive()):
            with self.reserved_access_to_instr:
                I = self.instr.query_current_source_amplitude()
                Vcomp = self.instr.query_voltage_compliance()
                outstate = self.instr.query_output_ON()
            self.ui.I_disp.setText(str(I * 1e6) + u' ÎĽA')
            self.ui.V_disp.setText(str(Vcomp) + ' V')
            self.ui.outputON.setChecked(outstate)
            self.monitor_timer.start(self.ui.refresh_rate.value() * 1000)

    def update_timer_timeout(self, secs):
        #The value must be converted to milliseconds
        self.monitor_timer.setInterval(secs * 1000)

    def change_I(self, value=0):
        with self.reserved_access_to_instr:
            self.instr.set_current_source_amplitude(value * 1e6)

    def change_V_comp(self, value=0):
        with self.reserved_access_to_instr:
            self.instr.set_voltage_compliance(value)

    def switch_output(self, value=False):
        if value:
            with self.reserved_access_to_instr:
                self.instr.output_ON()
        else:
            with self.reserved_access_to_instr:
                self.instr.output_OFF()

    def reset_inst(self):
        with self.reserved_access_to_instr:
            self.instr.reset()
Example #56
0
class XDockToolbar(QWidget):
    Position = enum('North', 'South', 'East', 'West')

    actionTriggered = Signal(object)
    actionMiddleTriggered = Signal(object)
    actionMenuRequested = Signal(object, QPoint)
    currentActionChanged = Signal(object)
    actionHovered = Signal(object)

    def __init__(self, parent=None):
        super(XDockToolbar, self).__init__(parent)

        # defines the position for this widget
        self._currentAction = -1
        self._selectedAction = None
        self._padding = 8
        self._position = XDockToolbar.Position.South
        self._minimumPixmapSize = QSize(16, 16)
        self._maximumPixmapSize = QSize(48, 48)
        self._hoverTimer = QTimer()
        self._hoverTimer.setSingleShot(True)
        self._hoverTimer.setInterval(1000)
        self._actionHeld = False
        self._easingCurve = QEasingCurve(QEasingCurve.InOutQuad)
        self._duration = 200
        self._animating = False

        # install an event filter to update the location for this toolbar
        layout = QBoxLayout(QBoxLayout.LeftToRight)
        layout.setContentsMargins(2, 2, 2, 2)
        layout.setSpacing(0)
        layout.addStretch(1)
        layout.addStretch(1)

        self.setLayout(layout)
        self.setContentsMargins(2, 2, 2, 2)
        self.setMouseTracking(True)
        parent.window().installEventFilter(self)
        parent.window().statusBar().installEventFilter(self)

        self._hoverTimer.timeout.connect(self.emitActionHovered)

    def __markAnimatingFinished(self):
        self._animating = False

    def actionAt(self, pos):
        """
        Returns the action at the given position.
        
        :param      pos | <QPoint>
        
        :return     <QAction> || None
        """
        child = self.childAt(pos)
        if child:
            return child.action()
        return None

    def actionHeld(self):
        """
        Returns whether or not the action will be held instead of closed on
        leaving.
        
        :return     <bool>
        """
        return self._actionHeld

    def actionLabels(self):
        """
        Returns the labels for this widget.
        
        :return     <XDockActionLabel>
        """
        l = self.layout()
        return [l.itemAt(i).widget() for i in range(1, l.count() - 1)]

    def addAction(self, action):
        """
        Adds the inputed action to this toolbar.
        
        :param      action | <QAction>
        """
        super(XDockToolbar, self).addAction(action)

        label = XDockActionLabel(action, self.minimumPixmapSize(), self)
        label.setPosition(self.position())

        layout = self.layout()
        layout.insertWidget(layout.count() - 1, label)

    def clear(self):
        """
        Clears out all the actions and items from this toolbar.
        """
        # clear the actions from this widget
        for act in self.actions():
            act.setParent(None)
            act.deleteLater()

        # clear the labels from this widget
        for lbl in self.actionLabels():
            lbl.close()
            lbl.deleteLater()

    def currentAction(self):
        """
        Returns the currently hovered/active action.
        
        :return     <QAction> || None
        """
        return self._currentAction

    def duration(self):
        """
        Returns the duration value for the animation of the icons.
        
        :return     <int>
        """
        return self._duration

    def easingCurve(self):
        """
        Returns the easing curve that will be used for the animation of
        animated icons for this dock bar.
        
        :return     <QEasingCurve>
        """
        return self._easingCurve

    def emitActionHovered(self):
        """
        Emits a signal when an action is hovered.
        """
        if not self.signalsBlocked():
            self.actionHovered.emit(self.currentAction())

    def eventFilter(self, object, event):
        """
        Filters the parent objects events to rebuild this toolbar when
        the widget resizes.
        
        :param      object | <QObject>
                    event | <QEvent>
        """
        if event.type() in (event.Move, event.Resize):
            if self.isVisible():
                self.rebuild()
            elif object.isVisible():
                self.setVisible(True)

        return False

    def holdAction(self):
        """
        Returns whether or not the action should be held instead of clearing
        on leave.
        
        :return     <bool>
        """
        self._actionHeld = True

    def labelForAction(self, action):
        """
        Returns the label that contains the inputed action.
        
        :return     <XDockActionLabel> || None
        """
        for label in self.actionLabels():
            if label.action() == action:
                return label
        return None

    def leaveEvent(self, event):
        """
        Clears the current action for this widget.
        
        :param      event | <QEvent>
        """
        super(XDockToolbar, self).leaveEvent(event)

        if not self.actionHeld():
            self.setCurrentAction(None)

    def maximumPixmapSize(self):
        """
        Returns the maximum pixmap size for this toolbar.
        
        :return     <int>
        """
        return self._maximumPixmapSize

    def minimumPixmapSize(self):
        """
        Returns the minimum pixmap size that will be displayed to the user
        for the dock widget.
        
        :return     <int>
        """
        return self._minimumPixmapSize

    def mouseMoveEvent(self, event):
        """
        Updates the labels for this dock toolbar.
        
        :param      event | <XDockToolbar>
        """
        # update the current label
        self.setCurrentAction(self.actionAt(event.pos()))

    def padding(self):
        """
        Returns the padding value for this toolbar.
        
        :return     <int>
        """
        return self._padding

    def paintEvent(self, event):
        """
        Paints the background for the dock toolbar.
        
        :param      event | <QPaintEvent>
        """
        x = 1
        y = 1
        w = self.width()
        h = self.height()

        clr_a = QColor(220, 220, 220)
        clr_b = QColor(190, 190, 190)

        grad = QLinearGradient()
        grad.setColorAt(0.0, clr_a)
        grad.setColorAt(0.6, clr_a)
        grad.setColorAt(1.0, clr_b)

        # adjust the coloring for the horizontal toolbar
        if self.position() & (self.Position.North | self.Position.South):
            h = self.minimumPixmapSize().height() + 6

            if self.position() == self.Position.South:
                y = self.height() - h
                grad.setStart(0, y)
                grad.setFinalStop(0, self.height())
            else:
                grad.setStart(0, 0)
                grad.setFinalStart(0, h)

        # adjust the coloring for the vertical toolbar
        if self.position() & (self.Position.East | self.Position.West):
            w = self.minimumPixmapSize().width() + 6

            if self.position() == self.Position.West:
                x = self.width() - w
                grad.setStart(x, 0)
                grad.setFinalStop(self.width(), 0)
            else:
                grad.setStart(0, 0)
                grad.setFinalStop(w, 0)

        painter = QPainter(self)
        painter.fillRect(x, y, w, h, grad)

        # show the active action
        action = self.selectedAction()
        if action is not None and \
           not self.currentAction() and \
           not self._animating:
            for lbl in self.actionLabels():
                if lbl.action() != action:
                    continue

                geom = lbl.geometry()
                size = lbl.pixmapSize()

                if self.position() == self.Position.North:
                    x = geom.left()
                    y = 0
                    w = geom.width()
                    h = size.height() + geom.top() + 2

                elif self.position() == self.Position.East:
                    x = 0
                    y = geom.top()
                    w = size.width() + geom.left() + 2
                    h = geom.height()

                painter.setPen(QColor(140, 140, 40))
                painter.setBrush(QColor(160, 160, 160))
                painter.drawRect(x, y, w, h)
                break

    def position(self):
        """
        Returns the position for this docktoolbar.
        
        :return     <XDockToolbar.Position>
        """
        return self._position

    def rebuild(self):
        """
        Rebuilds the widget based on the position and current size/location
        of its parent.
        """
        if not self.isVisible():
            return

        self.raise_()

        max_size = self.maximumPixmapSize()
        min_size = self.minimumPixmapSize()
        widget = self.window()
        rect = widget.rect()
        rect.setBottom(rect.bottom() - widget.statusBar().height())
        rect.setTop(widget.menuBar().height())
        offset = self.padding()

        # align this widget to the north
        if self.position() == XDockToolbar.Position.North:
            self.move(rect.left(), rect.top())
            self.resize(rect.width(), min_size.height() + offset)

        # align this widget to the east
        elif self.position() == XDockToolbar.Position.East:
            self.move(rect.left(), rect.top())
            self.resize(min_size.width() + offset, rect.height())

        # align this widget to the south
        elif self.position() == XDockToolbar.Position.South:
            self.move(rect.left(), rect.top() - min_size.height() - offset)
            self.resize(rect.width(), min_size.height() + offset)

        # align this widget to the west
        else:
            self.move(rect.right() - min_size.width() - offset, rect.top())
            self.resize(min_size.width() + offset, rect.height())

    def resizeToMinimum(self):
        """
        Resizes the dock toolbar to the minimum sizes.
        """
        offset = self.padding()
        min_size = self.minimumPixmapSize()

        if self.position() in (XDockToolbar.Position.East,
                               XDockToolbar.Position.West):
            self.resize(min_size.width() + offset, self.height())

        elif self.position() in (XDockToolbar.Position.North,
                                 XDockToolbar.Position.South):
            self.resize(self.width(), min_size.height() + offset)

    def selectedAction(self):
        """
        Returns the action that was last selected.
        
        :return     <QAction>
        """
        return self._selectedAction

    def setActionHeld(self, state):
        """
        Sets whether or not this action should be held before clearing on
        leaving.
        
        :param      state | <bool>
        """
        self._actionHeld = state

    def setCurrentAction(self, action):
        """
        Sets the current action for this widget that highlights the size
        for this toolbar.
        
        :param      action | <QAction>
        """
        if action == self._currentAction:
            return

        self._currentAction = action
        self.currentActionChanged.emit(action)

        labels = self.actionLabels()
        anim_grp = QParallelAnimationGroup(self)
        max_size = self.maximumPixmapSize()
        min_size = self.minimumPixmapSize()

        if action:
            label = self.labelForAction(action)
            index = labels.index(label)

            # create the highlight effect
            palette = self.palette()
            effect = QGraphicsDropShadowEffect(label)
            effect.setXOffset(0)
            effect.setYOffset(0)
            effect.setBlurRadius(20)
            effect.setColor(QColor(40, 40, 40))
            label.setGraphicsEffect(effect)

            offset = self.padding()
            if self.position() in (XDockToolbar.Position.East,
                                   XDockToolbar.Position.West):
                self.resize(max_size.width() + offset, self.height())

            elif self.position() in (XDockToolbar.Position.North,
                                     XDockToolbar.Position.South):
                self.resize(self.width(), max_size.height() + offset)

            w = max_size.width()
            h = max_size.height()
            dw = (max_size.width() - min_size.width()) / 3
            dh = (max_size.height() - min_size.height()) / 3

            for i in range(4):
                before = index - i
                after = index + i

                if 0 <= before and before < len(labels):
                    anim = XObjectAnimation(labels[before], 'setPixmapSize',
                                            anim_grp)

                    anim.setEasingCurve(self.easingCurve())
                    anim.setStartValue(labels[before].pixmapSize())
                    anim.setEndValue(QSize(w, h))
                    anim.setDuration(self.duration())
                    anim_grp.addAnimation(anim)

                    if i:
                        labels[before].setGraphicsEffect(None)

                if after != before and 0 <= after and after < len(labels):
                    anim = XObjectAnimation(labels[after], 'setPixmapSize',
                                            anim_grp)

                    anim.setEasingCurve(self.easingCurve())
                    anim.setStartValue(labels[after].pixmapSize())
                    anim.setEndValue(QSize(w, h))
                    anim.setDuration(self.duration())
                    anim_grp.addAnimation(anim)

                    if i:
                        labels[after].setGraphicsEffect(None)

                w -= dw
                h -= dh
        else:
            offset = self.padding()
            for label in self.actionLabels():
                # clear the graphics effect
                label.setGraphicsEffect(None)

                # create the animation
                anim = XObjectAnimation(label, 'setPixmapSize', self)
                anim.setEasingCurve(self.easingCurve())
                anim.setStartValue(label.pixmapSize())
                anim.setEndValue(min_size)
                anim.setDuration(self.duration())
                anim_grp.addAnimation(anim)

            anim_grp.finished.connect(self.resizeToMinimum)

        anim_grp.start()
        self._animating = True
        anim_grp.finished.connect(anim_grp.deleteLater)
        anim_grp.finished.connect(self.__markAnimatingFinished)

        if self._currentAction:
            self._hoverTimer.start()
        else:
            self._hoverTimer.stop()

    def setDuration(self, duration):
        """
        Sets the duration value for the animation of the icon.
        
        :param      duration | <int>
        """
        self._duration = duration

    def setEasingCurve(self, curve):
        """
        Sets the easing curve for this toolbar to the inputed curve.
        
        :param      curve | <QEasingCurve>
        """
        self._easingCurve = QEasingCurve(curve)

    def setMaximumPixmapSize(self, size):
        """
        Sets the maximum pixmap size for this toolbar.
        
        :param     size | <int>
        """
        self._maximumPixmapSize = size
        position = self.position()
        self._position = None
        self.setPosition(position)

    def setMinimumPixmapSize(self, size):
        """
        Sets the minimum pixmap size that will be displayed to the user
        for the dock widget.
        
        :param     size | <int>
        """
        self._minimumPixmapSize = size
        position = self.position()
        self._position = None
        self.setPosition(position)

    def setPadding(self, padding):
        """
        Sets the padding amount for this toolbar.
        
        :param      padding | <int>
        """
        self._padding = padding

    def setPosition(self, position):
        """
        Sets the position for this widget and its parent.
        
        :param      position | <XDockToolbar.Position>
        """
        if position == self._position:
            return

        self._position = position

        widget = self.window()
        layout = self.layout()
        offset = self.padding()
        min_size = self.minimumPixmapSize()

        # set the layout to north
        if position == XDockToolbar.Position.North:
            self.move(0, 0)
            widget.setContentsMargins(0, min_size.height() + offset, 0, 0)
            layout.setDirection(QBoxLayout.LeftToRight)

        # set the layout to east
        elif position == XDockToolbar.Position.East:
            self.move(0, 0)
            widget.setContentsMargins(min_size.width() + offset, 0, 0, 0)
            layout.setDirection(QBoxLayout.TopToBottom)

        # set the layout to the south
        elif position == XDockToolbar.Position.South:
            widget.setContentsMargins(0, 0, 0, min_size.height() + offset)
            layout.setDirection(QBoxLayout.LeftToRight)

        # set the layout to the west
        else:
            widget.setContentsMargins(0, 0, min_size.width() + offset, 0)
            layout.setDirection(QBoxLayout.TopToBottom)

        # update the label alignments
        for label in self.actionLabels():
            label.setPosition(position)

        # rebuilds the widget
        self.rebuild()
        self.update()

    def setSelectedAction(self, action):
        """
        Sets the selected action instance for this toolbar.
        
        :param      action | <QAction>
        """
        self._hoverTimer.stop()
        self._selectedAction = action

    def setVisible(self, state):
        """
        Sets whether or not this toolbar is visible.  If shown, it will rebuild.
        
        :param      state | <bool>
        """
        super(XDockToolbar, self).setVisible(state)

        if state:
            self.rebuild()
            self.setCurrentAction(None)

    def unholdAction(self):
        """
        Unholds the action from being blocked on the leave event.
        """
        self._actionHeld = False

        point = self.mapFromGlobal(QCursor.pos())
        self.setCurrentAction(self.actionAt(point))

    def visualRect(self, action):
        """
        Returns the visual rect for the inputed action, or a blank QRect if
        no matching action was found.
        
        :param      action | <QAction>
        
        :return     <QRect>
        """
        for widget in self.actionLabels():
            if widget.action() == action:
                return widget.geometry()
        return QRect()
Example #57
0
class padeInterface(QMainWindow):
    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)

        #Setup interface
        self.ui = uic.loadUi('interface.ui')
        self.channels = padeUi.channels(self)
        self.chLst = self.channels.activeChannels()

        self.connect(self.ui.connectBtn, QtCore.SIGNAL('clicked()'),
                     self.netConnect)

        self.connect(self.ui.regBtn, QtCore.SIGNAL('clicked()'),
                     self.readAllRegisters)

        self.connect(self.ui.channelBtn, QtCore.SIGNAL('clicked()'),
                     self.showChBox)

        self.connect(self.ui.chSpinBox, QtCore.SIGNAL('valueChanged(int)'),
                     self.readCh)

        self.regFile = 'superpaderegs.xml'

        self.registers = padeCommon.readRegisters(self.regFile)
        self.regEntryHash = {}
        rTbl = self.ui.registerTbl
        i = 0
        for r in self.registers.keys():
            rTbl.insertRow(i)
            name = QTableWidgetItem(r)
            value = QTableWidgetItem(0)
            self.regEntryHash[r] = (name, value)
            rTbl.setItem(i, 0, name)
            rTbl.setItem(i, 1, value)
            i += 1
        rTbl.setSortingEnabled(True)
        #Sort in Ascending Order
        rTbl.sortByColumn(0, QtCore.Qt.AscendingOrder)

        self.ui.show()

    def showChBox(self):
        self.channels.ui.show()

    def connected(self):
        self.ui.connectBtn.setText("Disconnect")
        self.ui.statlbl.setText('Connected')
        self.connect(self.ui.connectBtn, QtCore.SIGNAL('clicked()'),
                     self.netDisconnect)
        self.client = self.f.client

    def netConnect(self):
        print 'Connect Button!'
        print 'I read {0} as the host.'.format(self.ui.hostBox.text())
        host = str(self.ui.hostBox.text())

        try:
            self.f = padeFactory(self.regFile)
            self.f.verifyCb = self.connected
            self.reactor = reactor.connectTCP(host, 5001, self.f)
        except Exception as e:
            print e

    def netDisconnect(self):
        print 'Disconnecting'
        if self.f and self.client:
            self.client.transport.loseConnection()

    def refreshRegisterList(self, name):
        #        print 'Refreshing Register List: {0}'.format(name)
        print '{0} : {1}'.format(name, self.f.registers[name].Status)
        value = self.regEntryHash[name][1]
        value.setText(hex(self.f.registers[name].Status))
        if self.regCBs:
            self.regCBs.popleft().callback(int(self.ui.fpgaBox.value()))

    def readAllRegisters(self):
        print 'Reading all registers'
        self.regCBs = deque()

        for r in self.registers.keys():
            d = defer.Deferred()
            cb = functools.partial(self.refreshRegisterList, r)
            fn = functools.partial(self.f.readRegister, r, cb)

            d.addCallback(fn)
            self.regCBs.append(d)

        l = self.regCBs.popleft()
        l.callback(int(self.ui.fpgaBox.value()))

    def readCh(self, ch):
        #Lock the widget until we get a response
        self.ui.chSpinBox.enabled = False

        #Time out incase we don't get a response
        self.chTimer = QTimer()
        self.chTimer.setSingleShot(True)
        self.chTimer.setInterval(1000)
        self.connect(self.chTimer, QtCore.SIGNAL('timeout()'),
                     functools.partial(self.timeout, 'chSpinBox'))
        self.chTimer.start()
        print 'Reading Channel: {0}'.format(ch)
        #        print 'Delim: {0}'.format(repr(self.f.client.delimiter))
        cb = functools.partial(self.readChUpdate, int(ch))
        self.f.readA0(ch, cb, int(self.ui.fpgaBox.value()))

    def readChUpdate(self, ch, chVal):
        self.ui.chSpinBox.enabled = True
        self.chTimer.stop()
        self.chTimer = None

        print('Channel: {0}, Current: {1}'.format(ch,
                                                  padeCommon.parseA0(chVal)))

    def timeout(self, kind):
        if kind == 'chSpinBox':
            print 'Timed out reading channel voltage and current'
            self.ui.chSpinBox.enabled = True
Example #58
0
class RemoteSwitchV2(COMCUPluginBase, Ui_RemoteSwitchV2):
    qtcb_switching_done = pyqtSignal()

    def __init__(self, *args):
        COMCUPluginBase.__init__(self, BrickletRemoteSwitchV2, *args)

        self.setupUi(self)

        self.rs2 = self.device

        self.qtcb_switching_done.connect(self.cb_switching_done)
        self.rs2.register_callback(self.rs2.CALLBACK_SWITCHING_DONE,
                                   self.qtcb_switching_done.emit)

        self.h_check = (self.h_check_a, self.h_check_b, self.h_check_c,
                        self.h_check_d, self.h_check_e)

        self.r_check = (self.r_check_a, self.r_check_b, self.r_check_c,
                        self.r_check_d, self.r_check_e)

        for h in self.h_check:
            h.stateChanged.connect(self.h_check_state_changed)

        for r in self.r_check:
            r.stateChanged.connect(self.r_check_state_changed)

        self.checkbox_switchall.stateChanged.connect(
            self.switchall_state_changed)
        self.spinbox_house.valueChanged.connect(self.house_value_changed)
        self.spinbox_receiver.valueChanged.connect(self.receiver_value_changed)
        self.combo_type.currentIndexChanged.connect(self.type_index_changed)

        self.spinbox_dim_value.valueChanged.connect(
            self.spinbox_dim_value_changed)
        self.slider_dim_value.valueChanged.connect(
            self.slider_dim_value_changed)

        self.button_switch_on.clicked.connect(lambda: self.button_clicked(1))
        self.button_switch_off.clicked.connect(lambda: self.button_clicked(0))
        self.button_dim.clicked.connect(self.dim_clicked)

        self.combo_remote_type.currentIndexChanged.connect(
            self.remote_type_changed)
        self.button_remote_input_clear.clicked.connect(
            self.plaintextedit_remote_input.clear)

        self.current_remote_type = None
        self.timer_get_remote_input = QTimer()
        self.timer_get_remote_input.timeout.connect(
            self.timeout_get_remote_input)
        self.timer_get_remote_input.setInterval(50)

        self.last_remote_input = {
            'a': {
                'house_code': None,
                'receiver_code': None,
                'switch_to': None,
                'repeats': None
            },
            'b': {
                'address': None,
                'unit': None,
                'switch_to': None,
                'dim_value': None,
                'repeats': None
            },
            'c': {
                'system_code': None,
                'device_code': None,
                'switch_to': None,
                'repeats': None
            },
        }

        self.type_a_widgets = [
            self.label_house_code, self.h_check_a, self.h_check_b,
            self.h_check_c, self.h_check_d, self.h_check_e, self.spinbox_house,
            self.label_receiver_code, self.r_check_a, self.r_check_b,
            self.r_check_c, self.r_check_d, self.r_check_e,
            self.spinbox_receiver, self.button_switch_on,
            self.button_switch_off
        ]

        self.type_b_widgets = [
            self.label_address, self.spinbox_address, self.label_unit,
            self.spinbox_unit, self.checkbox_switchall, self.button_switch_on,
            self.button_switch_off
        ]

        self.type_b_dim_widgets = [
            self.label_address, self.spinbox_address, self.label_unit,
            self.spinbox_unit, self.checkbox_switchall, self.label_dim,
            self.spinbox_dim_value, self.slider_dim_value, self.button_dim
        ]

        self.type_c_widgets = [
            self.label_system_code, self.combo_system_code,
            self.label_device_code, self.spinbox_device_code,
            self.button_switch_on, self.button_switch_off
        ]

        self.type_widgets = (self.type_a_widgets, self.type_b_widgets,
                             self.type_b_dim_widgets, self.type_c_widgets)

        self.type_index_changed(0)

    def spinbox_dim_value_changed(self, value):
        self.slider_dim_value.setValue(value)

    def slider_dim_value_changed(self, value):
        self.spinbox_dim_value.setValue(value)

    def type_index_changed(self, index):
        for i in range(len(self.type_widgets)):
            if i != index:
                for w in self.type_widgets[i]:
                    w.setVisible(False)

        for w in self.type_widgets[index]:
            w.setVisible(True)

    def house_value_changed(self, state):
        for i in range(5):
            if state & (1 << i):
                self.h_check[i].setChecked(True)
            else:
                self.h_check[i].setChecked(False)

    def receiver_value_changed(self, state):
        for i in range(5):
            if state & (1 << i):
                self.r_check[i].setChecked(True)
            else:
                self.r_check[i].setChecked(False)

    def switchall_state_changed(self, state):
        if self.checkbox_switchall.isChecked():
            self.spinbox_address.setEnabled(False)
            self.spinbox_unit.setEnabled(False)
        else:
            self.spinbox_address.setEnabled(True)
            self.spinbox_unit.setEnabled(True)

    def h_check_state_changed(self, state):
        house_code = 0
        for i in range(5):
            if self.h_check[i].isChecked():
                house_code |= (1 << i)

        self.spinbox_house.setValue(house_code)

    def r_check_state_changed(self, state):
        receiver_code = 0
        for i in range(5):
            if self.r_check[i].isChecked():
                receiver_code |= (1 << i)

        self.spinbox_receiver.setValue(receiver_code)

    def get_remote_configuration_async(self, remote_config):
        self.current_remote_type = remote_config.remote_type

        self.spinbox_remote_minimum_repeats.setValue(
            remote_config.minimum_repeats)

        if remote_config.remote_type == self.rs2.REMOTE_TYPE_A:
            self.combo_remote_type.setCurrentIndex(self.rs2.REMOTE_TYPE_A)
        elif remote_config.remote_type == self.rs2.REMOTE_TYPE_B:
            self.combo_remote_type.setCurrentIndex(self.rs2.REMOTE_TYPE_B)
        elif remote_config.remote_type == self.rs2.REMOTE_TYPE_C:
            self.combo_remote_type.setCurrentIndex(self.rs2.REMOTE_TYPE_C)

    def start(self):
        self.timer_get_remote_input.start()
        async_call(self.rs2.get_remote_configuration, None,
                   self.get_remote_configuration_async,
                   self.increase_error_count)

    def stop(self):
        pass
        self.timer_get_remote_input.stop()

    def destroy(self):
        pass

    def dim_clicked(self):
        self.button_dim.setEnabled(False)
        self.button_dim.setText("Dimming...")

        repeats = self.spinbox_repeats.value()
        self.rs2.set_repeats(repeats)

        if self.combo_type.currentIndex() == 2:
            address = self.spinbox_address.value()
            unit = self.spinbox_unit.value()
            if self.checkbox_switchall.isChecked():
                address = 0
                unit = 255

            dim_value = self.spinbox_dim_value.value()

            self.rs2.dim_socket_b(address, unit, dim_value)

    def remote_type_changed(self, index):
        self.current_remote_type = index
        remote_config = self.rs2.get_remote_configuration()

        self.rs2.set_remote_configuration(index, remote_config.minimum_repeats,
                                          remote_config.callback_enabled)

        remote_config = self.rs2.get_remote_configuration()

    def get_remote_status_a_async(self, remote_config):
        if remote_config.repeats <= self.spinbox_remote_minimum_repeats.value(
        ):
            return

        if self.last_remote_input['a']['house_code'] == remote_config.house_code and \
           self.last_remote_input['a']['receiver_code'] == remote_config.receiver_code and \
           self.last_remote_input['a']['switch_to'] == remote_config.switch_to and \
           self.last_remote_input['a']['repeats'] == remote_config.repeats:
            return

        if self.last_remote_input['a']['house_code'] == None and \
           self.last_remote_input['a']['receiver_code'] == None and \
           self.last_remote_input['a']['switch_to'] == None and \
           self.last_remote_input['a']['repeats'] == None:
            self.last_remote_input['a'][
                'house_code'] = remote_config.house_code
            self.last_remote_input['a'][
                'receiver_code'] = remote_config.receiver_code
            self.last_remote_input['a']['switch_to'] = remote_config.switch_to
            self.last_remote_input['a']['repeats'] = remote_config.repeats

            return

        self.last_remote_input['a']['house_code'] = remote_config.house_code
        self.last_remote_input['a'][
            'receiver_code'] = remote_config.receiver_code
        self.last_remote_input['a']['switch_to'] = remote_config.switch_to
        self.last_remote_input['a']['repeats'] = remote_config.repeats

        remote_input = '''Remote Type - A:
House code = {house_code}
Receiver code = {receiver_code}
Switch to = {switch_to}
Reapeats = {repeats}

'''.format(house_code=remote_config.house_code,
           receiver_code=remote_config.receiver_code,
           switch_to=remote_config.switch_to,
           repeats=remote_config.repeats)

        self.plaintextedit_remote_input.appendPlainText(remote_input)
        self.plaintextedit_remote_input.moveCursor(QTextCursor.End)

    def get_remote_status_b_async(self, remote_config):
        if remote_config.repeats <= self.spinbox_remote_minimum_repeats.value(
        ):
            return

        if self.last_remote_input['b']['address'] == remote_config.address and \
           self.last_remote_input['b']['unit'] == remote_config.unit and \
           self.last_remote_input['b']['switch_to'] == remote_config.switch_to and \
           self.last_remote_input['b']['dim_value'] == remote_config.dim_value and \
           self.last_remote_input['b']['repeats'] == remote_config.repeats:
            return

        if self.last_remote_input['b']['address'] == None and \
           self.last_remote_input['b']['unit'] == None and \
           self.last_remote_input['b']['switch_to'] == None and \
           self.last_remote_input['b']['dim_value'] == None and \
           self.last_remote_input['b']['repeats'] == None:
            self.last_remote_input['b']['address'] = remote_config.address
            self.last_remote_input['b']['unit'] = remote_config.unit
            self.last_remote_input['b']['switch_to'] = remote_config.switch_to
            self.last_remote_input['b']['dim_value'] = remote_config.dim_value
            self.last_remote_input['b']['repeats'] = remote_config.repeats

            return

        self.last_remote_input['b']['address'] = remote_config.address
        self.last_remote_input['b']['unit'] = remote_config.unit
        self.last_remote_input['b']['switch_to'] = remote_config.switch_to
        self.last_remote_input['b']['dim_value'] = remote_config.dim_value
        self.last_remote_input['b']['repeats'] = remote_config.repeats

        remote_input = '''Remote Type - B:
Address = {address}
Unit = {unit}_async
Switch to = {switch_to}
Dim value = {dim_value}
Repeats = {repeats}

'''.format(address=remote_config.address,
           unit=remote_config.unit,
           switch_to=remote_config.switch_to,
           dim_value=remote_config.dim_value,
           repeats=remote_config.repeats)

        self.plaintextedit_remote_input.appendPlainText(remote_input)
        self.plaintextedit_remote_input.moveCursor(QTextCursor.End)

    def get_remote_status_c_async(self, remote_config):
        if remote_config.repeats <= self.spinbox_remote_minimum_repeats.value(
        ):
            return

        if self.last_remote_input['c']['system_code'] == remote_config.system_code and \
           self.last_remote_input['c']['device_code'] == remote_config.device_code and \
           self.last_remote_input['c']['switch_to'] == remote_config.switch_to and \
           self.last_remote_input['c']['repeats'] == remote_config.repeats:
            return

        if self.last_remote_input['c']['system_code'] == None and \
           self.last_remote_input['c']['device_code'] == None and \
           self.last_remote_input['c']['switch_to'] == None and \
           self.last_remote_input['c']['repeats'] == None:
            self.last_remote_input['c'][
                'system_code'] = remote_config.system_code
            self.last_remote_input['c'][
                'device_code'] = remote_config.device_code
            self.last_remote_input['c']['switch_to'] = remote_config.switch_to
            self.last_remote_input['c']['repeats'] = remote_config.repeats

            return

        self.last_remote_input['c']['system_code'] = remote_config.system_code
        self.last_remote_input['c']['device_code'] = remote_config.device_code
        self.last_remote_input['c']['switch_to'] = remote_config.switch_to
        self.last_remote_input['c']['repeats'] = remote_config.repeats

        remote_input = '''Remote Type - C:
System code = {system_code}
Device code = {device_code}
Switch to = {switch_to}
Reapeats = {repeats}

'''.format(system_code=remote_config.system_code,
           device_code=remote_config.device_code,
           switch_to=remote_config.switch_to,
           repeats=remote_config.repeats)

        self.plaintextedit_remote_input.appendPlainText(remote_input)
        self.plaintextedit_remote_input.moveCursor(QTextCursor.End)

    def timeout_get_remote_input(self):
        if self.current_remote_type == self.rs2.REMOTE_TYPE_A:
            async_call(self.rs2.get_remote_status_a, None,
                       self.get_remote_status_a_async,
                       self.increase_error_count)
        elif self.current_remote_type == self.rs2.REMOTE_TYPE_B:
            async_call(self.rs2.get_remote_status_b, None,
                       self.get_remote_status_b_async,
                       self.increase_error_count)
        elif self.current_remote_type == self.rs2.REMOTE_TYPE_C:
            async_call(self.rs2.get_remote_status_c, None,
                       self.get_remote_status_c_async,
                       self.increase_error_count)

    def button_clicked(self, switch_to):
        self.button_switch_on.setEnabled(False)
        self.button_switch_on.setText("Switching...")
        self.button_switch_off.setEnabled(False)
        self.button_switch_off.setText("Switching...")

        repeats = self.spinbox_repeats.value()
        self.rs2.set_repeats(repeats)

        if self.combo_type.currentText() == 'A Switch':
            house_code = self.spinbox_house.value()
            receiver_code = self.spinbox_receiver.value()
            self.rs2.switch_socket_a(house_code, receiver_code, switch_to)
        elif self.combo_type.currentText() == 'B Switch':
            address = self.spinbox_address.value()
            unit = self.spinbox_unit.value()

            if self.checkbox_switchall.isChecked():
                address = 0
                unit = 255

            self.rs2.switch_socket_b(address, unit, switch_to)
        elif self.combo_type.currentText() == 'C Switch':
            system_code = self.combo_system_code.currentText()[0]
            device_code = self.spinbox_device_code.value()
            self.rs2.switch_socket_c(system_code, device_code, switch_to)

    def cb_switching_done(self):
        self.button_switch_on.setEnabled(True)
        self.button_switch_on.setText("Switch On")
        self.button_switch_off.setEnabled(True)
        self.button_switch_off.setText("Switch Off")
        self.button_dim.setEnabled(True)
        self.button_dim.setText("Dim")

    @staticmethod
    def has_device_identifier(device_identifier):
        return device_identifier == BrickletRemoteSwitchV2.DEVICE_IDENTIFIER
class RemoteGA(IRemote, QObject):
    end_of_time = pyqtSignal()

    def __init__(self, le2mclt):
        IRemote.__init__(self, le2mclt)
        QObject.__init__(self)

    def _init_vars(self):
        self.current_instant = 0
        self.extractions = PlotData()
        self.extractions_group = PlotData()
        self.payoff_instant = PlotData()
        self.payoff_part = PlotData()
        self.resource = PlotData()
        self.text_infos = u""
        self.decision_screen = None
        self.simulation_extraction = 1  # 0 = myope, 1 = optimum social, 2 = feedback, 3 = aléatoire

    def remote_configure(self, params, server_part):
        logger.info(u"{} configure".format(self.le2mclt))
        self.server_part = server_part
        for k, v in params.items():
            setattr(pms, k, v)
        self._init_vars()

    def remote_set_initial_extraction(self):
        if self.le2mclt.simulation:
            if self.simulation_extraction == 0:
                extraction = pms.get_extraction_my(self.current_instant)
            elif self.simulation_extraction == 1:
                extraction = pms.get_extraction_os(self.current_instant)
            elif self.simulation_extraction == 2:
                extraction = pms.get_extraction_feed(self.current_instant)
            else:
                extraction = pms.get_extraction_aleatoire(self.current_instant)
            logger.info(u"{} Send {}".format(self.le2mclt, extraction))
            return extraction
        else:
            defered = defer.Deferred()
            screen = GuiInitialExtraction(self, defered)
            screen.show()
            return defered

    @defer.inlineCallbacks
    def send_simulation(self):
        if self.simulation_extraction == 0:
            extraction = pms.get_extraction_my(self.current_instant)
        elif self.simulation_extraction == 1:
            extraction = pms.get_extraction_os(self.current_instant)
        elif self.simulation_extraction == 2:
            extraction = pms.get_extraction_feed(self.current_instant)
        else:
            extraction = pms.get_extraction_aleatoire(self.current_instant)
        logger.info(u"{} Send {}".format(self._le2mclt.uid, extraction))
        yield (self.server_part.callRemote("new_extraction", extraction))

    def remote_display_decision(self, the_n):
        self.current_instant = the_n
        # simulation ---------------------------------------------------------------------------------------------------
        if self._le2mclt.simulation:
            # continuous
            if pms.DYNAMIC_TYPE == pms.CONTINUOUS:
                self.continuous_simulation_defered = defer.Deferred()
                self.continuous_simulation_timer = QTimer()
                self.continuous_simulation_timer.setInterval(1000)
                self.continuous_simulation_timer.timeout.connect(
                    self.send_simulation)
                self.continuous_simulation_timer.start()
                return self.continuous_simulation_defered

            # discrete
            elif pms.DYNAMIC_TYPE == pms.DISCRETE:
                if self.simulation_extraction == 0:
                    extraction = pms.get_extraction_my(self.current_instant)
                elif self.simulation_extraction == 1:
                    extraction = pms.get_extraction_os(self.current_instant)
                elif self.simulation_extraction == 2:
                    extraction = pms.get_extraction_feed(self.current_instant)
                else:
                    extraction = pms.get_extraction_aleatoire(
                        self.current_instant)
                logger.info(u"{} Send {}".format(self.le2mclt, extraction))
                return extraction

        # manual or auto -----------------------------------------------------------------------------------------------
        else:
            defered = defer.Deferred()
            if self.decision_screen is None:
                self.decision_screen = GuiDecision(self, defered)
                self.decision_screen.showFullScreen()
            else:
                self.decision_screen.defered = defered
                self.decision_screen.update_data_and_graphs()
            return defered

    def remote_update_data(self, player_instant, group_instant):
        logger.debug("player_instant: {}".format(player_instant))
        logger.debug("group_instant: {}".format(group_instant))
        self.current_instant = player_instant["GA_instant"]
        # extraction
        self.extractions.add_x(self.current_instant)
        self.extractions.add_y(player_instant["GA_extraction"])
        # group extraction
        self.extractions_group.add_x(self.current_instant)
        self.extractions_group.add_y(group_instant["GA_extraction"])
        # resource
        self.resource.add_x(self.current_instant)
        self.resource.add_y(player_instant["GA_resource"])
        # instant payoff
        self.payoff_instant.add_x(self.current_instant)
        self.payoff_instant.add_y(player_instant["GA_instant_payoff"])
        # part payoff
        self.payoff_part.add_x(self.current_instant)
        self.payoff_part.add_y(player_instant["GA_part_payoff"])

        # update curves
        try:
            self.extractions.update_curve()
            self.extractions_group.update_curve()
            self.resource.update_curve()
            self.payoff_part.update_curve()
        except AttributeError as e:  # if period==0
            logger.warning(e.message)

        # text information
        old = self.text_infos
        the_time_str = texts_GA.trans_GA(u"Second") if \
            pms.DYNAMIC_TYPE == pms.CONTINUOUS else \
            texts_GA.trans_GA(u"Period")
        the_time_payoff_str = texts_GA.trans_GA(u"Instant payoff") if pms.DYNAMIC_TYPE == pms.CONTINUOUS else \
            texts_GA.trans_GA(u"Period payoff")
        self.text_infos = the_time_str + u": {}".format(self.current_instant) + \
                          u"<br>" + texts_GA.trans_GA(u"Extraction") + \
                          u": {:.2f}".format(self.extractions.ydata[-1]) + \
                          u"<br>" + texts_GA.trans_GA(u"Group extraction") + \
                          u": {:.2f}".format(self.extractions_group.ydata[-1]) + \
                          u"<br>" + texts_GA.trans_GA(u"Available resource") + \
                          u": {:.2f}".format(self.resource.ydata[-1]) + \
                          u"<br>" + the_time_payoff_str + \
                          u": {:.2f}".format(self.payoff_instant.ydata[-1]) + \
                          u"<br>" + texts_GA.trans_GA(u"Part payoff") + \
                          u": {:.2f}".format(self.payoff_part.ydata[-1])
        self.text_infos += u"<br>{}<br>{}".format(20 * "-", old)

        # log
        logger.debug(
            "curves : instant {} - extraction {:.2f} - extraction_group: {:.2f} - resource: {:.2f} - payoff: {:.2f}"
            .format(self.current_instant, self.extractions.ydata[-1],
                    self.extractions_group.ydata[-1], self.resource.ydata[-1],
                    self.payoff_part.ydata[-1]))

    def remote_end_update_data(self):
        logger.debug("{}: call of remote_end_data".format(self.le2mclt))
        if self.le2mclt.simulation and pms.DYNAMIC_TYPE == pms.CONTINUOUS:
            self.continuous_simulation_timer.stop()
            self.continuous_simulation_defered.callback(None)
        self.end_of_time.emit()

    def remote_display_summary(self, period_content):
        logger.info(u"{} Summary".format(self._le2mclt.uid))
        if self._le2mclt.simulation:
            curves = {
                "extractions": self.extractions.get_curve(),
                "payoffs": self.payoff_part.get_curve(),
                "resource": self.resource.get_curve()
            }
            logger.info("{} send curves ({})".format(self.le2mclt,
                                                     curves.keys()))
            return curves
        else:
            defered = defer.Deferred()
            summary_screen = GuiSummary(
                self, defered,
                texts_GA.get_text_summary(self.payoff_part.ydata[-1]))
            summary_screen.showFullScreen()
            return defered
Example #60
0
class SR830_Widget(Ui.Ui_Form, QWidget):
    def __init__(self, parent=None):
        super(SR830_Widget, self).__init__(parent)
        self.setupUi(self)
        self.setWindowTitle('SR830 lock-in')
        self.timer = None

        self.selectFilePb.clicked.connect(self.selectFile)
        self.loggingEnableCb.toggled.connect(self.toggleLogging)
        self.loggingEnableCb.setEnabled(False)

        axis = pg.DateAxisItem(orientation='bottom')
        self.plot = pg.PlotWidget(axisItems={'bottom': axis})
        self.plot.addLegend()
        self.verticalLayout.addWidget(self.plot)
        self.curve1 = pg.PlotCurveItem(name='X', symbol='o', pen='b')
        self.curve2 = pg.PlotCurveItem(name='Y', symbol='o', pen='r')
        self.curve3 = pg.PlotCurveItem(name='R', symbol='o', pen='g')
        self.plot.addItem(self.curve1)
        self.plot.addItem(self.curve2)
        self.plot.addItem(self.curve3)
        self.clearData()
        self.restoreSettings()

        self.logFileName = None
        self.sr830 = None
        self.controlPb.clicked.connect(self.control)
        #self.auxIn1Indicator.setUnit('V')
        #self.auxIn2Indicator.setUnit('V')
        #self.auxIn3Indicator.setUnit('V')
        #self.auxIn4Indicator.setUnit('V')
        self.rIndicator.setUnit('V')
        self.rIndicator.setPrecision(4)
        self.xIndicator.setUnit('V')
        self.xIndicator.setPrecision(4)
        self.yIndicator.setUnit('V')
        self.yIndicator.setPrecision(4)
        self.fIndicator.setUnit('Hz')
        self.clearPb.clicked.connect(self.clearData)


#        self.publisher = ZmqPublisher('SR830', port=5789, parent=self)

    def selectFile(self):
        fileName = QFileDialog.getSaveFileName(
            parent=self,
            caption='Select a file to write to',
            directory=self.fileNameLe.text(),
            filter='*.dat;*.txt')
        self.fileNameLe.setText(fileName)
        validFile = len(fileName) > 0
        self.loggingEnableCb.setEnabled(validFile)

    def toggleLogging(self, enable):
        if enable:
            fileName = self.fileNameLe.text()
            with open(fileName, 'a') as of:
                of.write("#SR830_GUI\n")
                of.write("#Model:%s\n" % self.sr830.model)
                of.write("#Serial:%s\n" % self.sr830.serial)
                of.write("#VISA:%s\n" % self.visaAddress)
                of.write("#Comment:%s\n" % self.commentLe.text())
                of.write('#Date=%s\n' % time.strftime('%Y%m%d-%H%M%S'))
                settings = self.sr830.allSettingValues()
                for key in settings:
                    of.write('#SR830/%s=%s\n' % (key, settings[key]))
                of.write('#t\tf\tX\tY\n')

                self.logFileName = fileName
            self.commentLe.setReadOnly(True)
            self.fileNameLe.setReadOnly(True)
            self.selectFilePb.setEnabled(False)
        else:
            self.logFileName = None
            self.commentLe.setReadOnly(False)
            self.fileNameLe.setReadOnly(False)
            self.selectFilePb.setEnabled(True)

    def closeEvent(self, event):
        if self.timer:
            self.timer.stop()

        self.saveSettings()

    def restoreSettings(self):
        s = QSettings()
        visa = s.value('visa', QString(), type=QString)
        i = self.visaCombo.findText(visa)
        self.visaCombo.setCurrentIndex(i)
        self.auxInGroupBox.setChecked(s.value('auxIn', True, type=bool))

    def saveSettings(self):
        s = QSettings()
        visa = self.visaCombo.currentText()
        s.setValue('visa', visa)
        s.setValue('auxIn', self.auxInGroupBox.isChecked())

    def control(self):
        if self.sr830 is not None:
            self.stop()
        else:
            self.start()

    def stop(self):
        self.timer.stop()
        self.timer = None
        self.sr830 = None
        self.controlPb.setText('Start')

    def start(self):
        self.visaAddress = str(self.visaCombo.currentText())
        self.sr830 = SR830(self.visaAddress)
        self.sr830.debug = False
        self.auxIn = 0

        #Input
        self.sr830.inputSource.bindToEnumComboBox(self.inputSourceCombo)
        self.sr830.inputCoupling.bindToEnumComboBox(self.inputCouplingCombo)
        self.sr830.inputGrounding.bindToEnumComboBox(
            self.inputShieldGroundCombo)
        self.sr830.inputFilters.bindToEnumComboBox(self.inputFiltersCombo)
        self.sr830.sensitivity.bindToEnumComboBox(self.sensitivityCombo)
        self.sr830.inputOverloadRead.connect(self.inputOverloadLed.setValue)

        #Filter
        self.sr830.filterSlope.bindToEnumComboBox(self.filterRolloffCombo)
        self.sr830.filterTc.bindToEnumComboBox(self.filterTcCombo)
        self.sr830.syncDemodulator.bindToCheckBox(self.syncCb)
        self.sr830.filterOverloadRead.connect(self.filterOverloadLed.setValue)

        #Reference
        self.sr830.referenceSource.bindToEnumComboBox(self.referenceCombo)
        self.sr830.referenceFrequency.bindToSpinBox(self.frequencySb)
        self.frequencySb.setKeyboardTracking(False)
        self.sr830.sineOut.bindToSpinBox(self.amplitudeSb)
        self.amplitudeSb.setKeyboardTracking(False)
        #@todo Phase goes here
        self.sr830.harmonic.bindToSpinBox(self.harmonicSb)
        self.harmonicSb.setKeyboardTracking(False)
        self.sr830.referenceTrigger.bindToEnumComboBox(
            self.referenceTriggerCombo)

        # AUX out
        aout = {
            0: self.auxOut1Sb,
            1: self.auxOut2Sb,
            2: self.auxOut3Sb,
            3: self.auxOut4Sb
        }
        for i in range(4):
            self.sr830.auxOut[i].bindToSpinBox(aout[i])

        self.visaId = self.sr830.visaId()

        self.setWindowTitle(
            '%s %s (%s)' %
            (self.sr830.model, self.visaAddress, self.sr830.serial))

        self.sr830.readAll()

        self.sr830.readingAvailable.connect(self.collectReading)
        self.sr830.auxInRead.connect(self.collectAuxIn)
        self.controlPb.setText('Stop')
        self.timer = QTimer()
        self.timer.setInterval(int(1E3 * self.intervalSb.value()))
        self.intervalSb.valueChanged.connect(
            lambda x: self.timer.setInterval(int(1E3 * x)))
        self.timer.timeout.connect(self.snapSignal)
        self.timer.start()

    def snapSignal(self):
        if self.auxInGroupBox.isChecked():
            self.sr830.snapSignal(self.auxIn)
            self.auxIn += 1
            self.auxIn %= 4
        else:
            self.sr830.snapSignal()
        self.sr830.checkStatus()

    def clearData(self):
        self.ts = []
        self.xs = []
        self.ys = []
        self.Rs = []
        self.fs = []
        self.updatePlot()

    def updatePlot(self):
        self.curve1.setData(self.ts, self.xs)
        self.curve2.setData(self.ts, self.ys)
        self.curve3.setData(self.ts, self.Rs)

    def collectReading(self, X, Y, f):
        t = time.time()
        R = self.sr830.R
        self.xIndicator.setValue(X)
        self.yIndicator.setValue(Y)
        self.fIndicator.setValue(f)
        self.rIndicator.setValue(R)
        self.thetaIndicator.setValue(self.sr830.thetaDegree)
        self.ts.append(t)
        self.xs.append(X)
        self.ys.append(Y)
        self.Rs.append(R)
        self.fs.append(f)

        #self.publisher.publish(item='%s %s' % (self.sr830.serial, self.visaAddress), data={'X':X, 'Y':Y, 'f':f})
        if self.logFileName is not None:
            with open(self.logFileName, 'a') as of:
                of.write('%.3f\t%.7g\t%.7g\t%.7g\n' % (t, f, X, Y))
        self.updatePlot()

    def collectAuxIn(self, auxIn, voltage):
        auxMap = {
            0: self.auxIn1Indicator,
            1: self.auxIn2Indicator,
            2: self.auxIn3Indicator,
            3: self.auxIn4Indicator
        }
        auxMap[auxIn].setValue(voltage)