]> sigrok.org Git - sigrok-meter.git/blobdiff - datamodel.py
Minor cosmetics and typo fixes.
[sigrok-meter.git] / datamodel.py
index d6b1443f5e9962f2cb0811eebca3045d3a780d20..83d5ef60df7080c225215eb1cc299e87f311de7a 100644 (file)
 ## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 ##
 
-import collections
+import itertools
+import math
 import qtcompat
 import sigrok.core as sr
-import time
 import util
 
+try:
+    from itertools import izip
+except ImportError:
+    izip = zip
+
 QtCore = qtcompat.QtCore
 QtGui = qtcompat.QtGui
 
+class Trace(object):
+    '''Class to hold the measured samples.'''
+
+    def __init__(self):
+        self.samples = []
+        self.new = False
+
+    def append(self, sample):
+        self.samples.append(sample)
+        self.new = True
+
 class MeasurementDataModel(QtGui.QStandardItemModel):
     '''Model to hold the measured values.'''
 
@@ -36,8 +52,11 @@ class MeasurementDataModel(QtGui.QStandardItemModel):
     '''Role used to store the device vendor and model.'''
     descRole = QtCore.Qt.UserRole + 2
 
-    '''Role used to store past samples.'''
-    samplesRole = QtCore.Qt.UserRole + 3
+    '''Role used to store a dictionary with the traces.'''
+    tracesRole = QtCore.Qt.UserRole + 3
+
+    '''Role used to store the color to draw the graph of the channel.'''
+    colorRole = QtCore.Qt.UserRole + 4
 
     def __init__(self, parent):
         super(self.__class__, self).__init__(parent)
@@ -46,8 +65,31 @@ class MeasurementDataModel(QtGui.QStandardItemModel):
         # idRole holds tuples, and using them to sort doesn't work.
         self.setSortRole(MeasurementDataModel.descRole)
 
-        # Used in 'format_value()' to check against.
-        self.inf = float('inf')
+        # A generator for the colors of the channels.
+        self._colorgen = self._make_colorgen()
+
+    def _make_colorgen(self):
+        cols = [
+            QtGui.QColor(0x8F, 0x52, 0x02), # brown
+            QtGui.QColor(0x73, 0xD2, 0x16), # green
+            QtGui.QColor(0xCC, 0x00, 0x00), # red
+            QtGui.QColor(0x34, 0x65, 0xA4), # blue
+            QtGui.QColor(0xF5, 0x79, 0x00), # orange
+            QtGui.QColor(0xED, 0xD4, 0x00), # yellow
+            QtGui.QColor(0x75, 0x50, 0x7B)  # violet
+        ]
+
+        def myrepeat(g, n):
+            '''Repeats every element from 'g' 'n' times'.'''
+            for e in g:
+                for f in itertools.repeat(e, n):
+                    yield f
+
+        colorcycle = itertools.cycle(cols)
+        darkness = myrepeat(itertools.count(100, 10), len(cols))
+
+        for c, d in izip(colorcycle, darkness):
+            yield QtGui.QColor(c).darker(d)
 
     def format_mqflags(self, mqflags):
         if sr.QuantityFlag.AC in mqflags:
@@ -58,7 +100,7 @@ class MeasurementDataModel(QtGui.QStandardItemModel):
             return ''
 
     def format_value(self, mag):
-        if mag == self.inf:
+        if math.isinf(mag):
             return u'\u221E'
         return '{:f}'.format(mag)
 
@@ -91,13 +133,14 @@ class MeasurementDataModel(QtGui.QStandardItemModel):
         item = QtGui.QStandardItem()
         item.setData(uid, MeasurementDataModel.idRole)
         item.setData(desc, MeasurementDataModel.descRole)
-        item.setData(collections.defaultdict(list), MeasurementDataModel.samplesRole)
+        item.setData({}, MeasurementDataModel.tracesRole)
+        item.setData(next(self._colorgen), MeasurementDataModel.colorRole)
         self.appendRow(item)
         self.sort(0)
         return item
 
-    @QtCore.Slot(object, object, object)
-    def update(self, device, channel, data):
+    @QtCore.Slot(float, sr.classes.Device, sr.classes.Channel, tuple)
+    def update(self, timestamp, device, channel, data):
         '''Update the data for the device (+channel) with the most recent
         measurement from the given payload.'''
 
@@ -114,9 +157,24 @@ class MeasurementDataModel(QtGui.QStandardItemModel):
 
         # The samples role is a dictionary that contains the old samples for each unit.
         # Should be trimmed periodically, otherwise it grows larger and larger.
-        sample = (time.time(), value)
-        d = item.data(MeasurementDataModel.samplesRole)
-        d[unit].append(sample)
+        if not math.isinf(value) and not math.isnan(value):
+            sample = (timestamp, value)
+            traces = item.data(MeasurementDataModel.tracesRole)
+
+            # It's not possible to use 'collections.defaultdict' here, because
+            # PySide doesn't return the original type that was passed in.
+            if not (unit in traces):
+                traces[unit] = Trace()
+            traces[unit].append(sample)
+
+            item.setData(traces, MeasurementDataModel.tracesRole)
+
+    def clear_samples(self):
+        '''Removes all old samples from the model.'''
+        for row in range(self.rowCount()):
+            idx = self.index(row, 0)
+            self.setData(idx, {},
+                MeasurementDataModel.tracesRole)
 
 class MultimeterDelegate(QtGui.QStyledItemDelegate):
     '''Delegate to show the data items from a MeasurementDataModel.'''
@@ -124,41 +182,63 @@ class MultimeterDelegate(QtGui.QStyledItemDelegate):
     def __init__(self, parent, font):
         '''Initialize the delegate.
 
-        :param font: Font used for the description text, the value is drawn
-                     with a slightly bigger and bold variant of the font.
+        :param font: Font used for the text.
         '''
 
         super(self.__class__, self).__init__(parent)
 
         self._nfont = font
-        self._bfont = QtGui.QFont(self._nfont)
-
-        self._bfont.setBold(True)
-        if self._bfont.pixelSize() != -1:
-            self._bfont.setPixelSize(self._bfont.pixelSize() * 1.2)
-        else:
-            self._bfont.setPointSizeF(self._bfont.pointSizeF() * 1.2)
 
         fi = QtGui.QFontInfo(self._nfont)
         self._nfontheight = fi.pixelSize()
 
-        fm = QtGui.QFontMetrics(self._bfont)
+        fm = QtGui.QFontMetrics(self._nfont)
         r = fm.boundingRect('-XX.XXXXXX X XX')
-        self._size = QtCore.QSize(r.width() * 1.4, r.height() * 2.2)
 
-        # Values used to calculate the positions of the strings in the
-        # 'paint()' function.
-        self._space_width = fm.boundingRect('_').width()
-        self._value_width = fm.boundingRect('-XX.XXXXXX').width()
+        w = 1.4 * r.width() + 2 * self._nfontheight
+        h = 2.6 * self._nfontheight
+        self._size = QtCore.QSize(w, h)
 
     def sizeHint(self, option=None, index=None):
         return self._size
 
+    def _color_rect(self, outer):
+        '''Returns the dimensions of the clickable rectangle.'''
+        x1 = (outer.height() - self._nfontheight) / 2
+        r = QtCore.QRect(x1, x1, self._nfontheight, self._nfontheight)
+        r.translate(outer.topLeft())
+        return r
+
     def paint(self, painter, options, index):
         value, unit = index.data(QtCore.Qt.DisplayRole)
         desc = index.data(MeasurementDataModel.descRole)
+        color = index.data(MeasurementDataModel.colorRole)
 
         painter.setFont(self._nfont)
+
+        # Draw the clickable rectangle.
+        painter.fillRect(self._color_rect(options.rect), color)
+
+        # Draw the text
+        h = options.rect.height()
         p = options.rect.topLeft()
-        p += QtCore.QPoint(self._nfontheight, 2 * self._nfontheight)
+        p += QtCore.QPoint(h, (h + self._nfontheight) / 2 - 2)
         painter.drawText(p, desc + ': ' + value + ' ' + unit)
+
+    def editorEvent(self, event, model, options, index):
+        if type(event) is QtGui.QMouseEvent:
+            if event.type() == QtCore.QEvent.MouseButtonPress:
+                rect = self._color_rect(options.rect)
+                if rect.contains(event.x(), event.y()):
+                    c = index.data(MeasurementDataModel.colorRole)
+                    c = QtGui.QColorDialog.getColor(c, None,
+                        'Choose new color for channel')
+                    if c.isValid():
+                        # False if cancel is pressed (resulting in a black
+                        # color).
+                        item = model.itemFromIndex(index)
+                        item.setData(c, MeasurementDataModel.colorRole)
+
+                    return True
+
+        return False