]> sigrok.org Git - sigrok-meter.git/blame - datamodel.py
Fix a bug with color picking.
[sigrok-meter.git] / datamodel.py
CommitLineData
48723bbb
JS
1##
2## This file is part of the sigrok-meter project.
3##
4## Copyright (C) 2014 Jens Steinhauser <jens.steinhauser@gmail.com>
5##
6## This program is free software; you can redistribute it and/or modify
7## it under the terms of the GNU General Public License as published by
8## the Free Software Foundation; either version 2 of the License, or
9## (at your option) any later version.
10##
11## This program is distributed in the hope that it will be useful,
12## but WITHOUT ANY WARRANTY; without even the implied warranty of
13## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14## GNU General Public License for more details.
15##
16## You should have received a copy of the GNU General Public License
17## along with this program; if not, write to the Free Software
18## Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19##
20
3010b5a0 21import itertools
5baa1f4b 22import math
48723bbb
JS
23import qtcompat
24import sigrok.core as sr
f76b9df8 25import util
48723bbb 26
3010b5a0
JS
27try:
28 from itertools import izip
29except ImportError:
30 izip = zip
31
48723bbb
JS
32QtCore = qtcompat.QtCore
33QtGui = qtcompat.QtGui
34
d0aa45b4
JS
35class Trace(object):
36 '''Class to hold the measured samples.'''
37
38 def __init__(self):
39 self.samples = []
40 self.new = False
41
42 def append(self, sample):
43 self.samples.append(sample)
44 self.new = True
45
48723bbb
JS
46class MeasurementDataModel(QtGui.QStandardItemModel):
47 '''Model to hold the measured values.'''
48
49 '''Role used to identify and find the item.'''
f76b9df8 50 idRole = QtCore.Qt.UserRole + 1
48723bbb
JS
51
52 '''Role used to store the device vendor and model.'''
53 descRole = QtCore.Qt.UserRole + 2
54
d0aa45b4
JS
55 '''Role used to store a dictionary with the traces'''
56 tracesRole = QtCore.Qt.UserRole + 3
f76b9df8 57
3010b5a0
JS
58 '''Role used to store the color to draw the graph of the channel.'''
59 colorRole = QtCore.Qt.UserRole + 4
60
48723bbb
JS
61 def __init__(self, parent):
62 super(self.__class__, self).__init__(parent)
63
64 # Use the description text to sort the items for now, because the
f76b9df8 65 # idRole holds tuples, and using them to sort doesn't work.
48723bbb
JS
66 self.setSortRole(MeasurementDataModel.descRole)
67
3010b5a0
JS
68 # A generator for the colors of the channels.
69 self._colorgen = self._make_colorgen()
70
71 def _make_colorgen(self):
72 cols = [
73 QtGui.QColor(0x8F, 0x52, 0x02), # brown
86862cb4 74 QtGui.QColor(0x73, 0xD2, 0x16), # green
3010b5a0 75 QtGui.QColor(0xCC, 0x00, 0x00), # red
86862cb4 76 QtGui.QColor(0x34, 0x65, 0xA4), # blue
3010b5a0
JS
77 QtGui.QColor(0xF5, 0x79, 0x00), # orange
78 QtGui.QColor(0xED, 0xD4, 0x00), # yellow
3010b5a0
JS
79 QtGui.QColor(0x75, 0x50, 0x7B) # violet
80 ]
81
82 def myrepeat(g, n):
83 '''Repeats every element from 'g' 'n' times'.'''
84 for e in g:
85 for f in itertools.repeat(e, n):
86 yield f
87
88 colorcycle = itertools.cycle(cols)
89 darkness = myrepeat(itertools.count(100, 10), len(cols))
90
91 for c, d in izip(colorcycle, darkness):
92 yield QtGui.QColor(c).darker(d)
93
48723bbb
JS
94 def format_mqflags(self, mqflags):
95 if sr.QuantityFlag.AC in mqflags:
96 return 'AC'
97 elif sr.QuantityFlag.DC in mqflags:
98 return 'DC'
99 else:
100 return ''
101
102 def format_value(self, mag):
5baa1f4b 103 if math.isinf(mag):
48723bbb
JS
104 return u'\u221E'
105 return '{:f}'.format(mag)
106
107 def getItem(self, device, channel):
480cdb7b
UH
108 '''Return the item for the device + channel combination from the
109 model, or create a new item if no existing one matches.'''
48723bbb 110
480cdb7b
UH
111 # Unique identifier for the device + channel.
112 # TODO: Isn't there something better?
48723bbb
JS
113 uid = (
114 device.vendor,
115 device.model,
116 device.serial_number(),
117 device.connection_id(),
118 channel.index
119 )
120
480cdb7b 121 # Find the correct item in the model.
48723bbb
JS
122 for row in range(self.rowCount()):
123 item = self.item(row)
f76b9df8 124 rid = item.data(MeasurementDataModel.idRole)
480cdb7b 125 rid = tuple(rid) # PySide returns a list.
48723bbb
JS
126 if uid == rid:
127 return item
128
480cdb7b 129 # Nothing found, create a new item.
0e810ddf 130 desc = '{} {}, {}'.format(
48723bbb
JS
131 device.vendor, device.model, channel.name)
132
133 item = QtGui.QStandardItem()
f76b9df8 134 item.setData(uid, MeasurementDataModel.idRole)
48723bbb 135 item.setData(desc, MeasurementDataModel.descRole)
1879265a 136 item.setData({}, MeasurementDataModel.tracesRole)
3010b5a0 137 item.setData(next(self._colorgen), MeasurementDataModel.colorRole)
48723bbb
JS
138 self.appendRow(item)
139 self.sort(0)
140 return item
141
6c05c913
JS
142 @QtCore.Slot(float, sr.classes.Device, sr.classes.Channel, tuple)
143 def update(self, timestamp, device, channel, data):
480cdb7b 144 '''Update the data for the device (+channel) with the most recent
48723bbb
JS
145 measurement from the given payload.'''
146
147 item = self.getItem(device, channel)
148
149 value, unit, mqflags = data
150 value_str = self.format_value(value)
f76b9df8 151 unit_str = util.format_unit(unit)
48723bbb
JS
152 mqflags_str = self.format_mqflags(mqflags)
153
02862990
JS
154 # The display role is a tuple containing the value and the unit/flags.
155 disp = (value_str, ' '.join([unit_str, mqflags_str]))
48723bbb
JS
156 item.setData(disp, QtCore.Qt.DisplayRole)
157
f76b9df8
JS
158 # The samples role is a dictionary that contains the old samples for each unit.
159 # Should be trimmed periodically, otherwise it grows larger and larger.
5baa1f4b
JS
160 if not math.isinf(value) and not math.isnan(value):
161 sample = (timestamp, value)
162 traces = item.data(MeasurementDataModel.tracesRole)
1879265a
JS
163
164 # It's not possible to use 'collections.defaultdict' here, because
165 # PySide doesn't return the original type that was passed in.
166 if not (unit in traces):
167 traces[unit] = Trace()
5baa1f4b 168 traces[unit].append(sample)
f76b9df8 169
1879265a
JS
170 item.setData(traces, MeasurementDataModel.tracesRole)
171
48723bbb
JS
172class MultimeterDelegate(QtGui.QStyledItemDelegate):
173 '''Delegate to show the data items from a MeasurementDataModel.'''
174
175 def __init__(self, parent, font):
480cdb7b 176 '''Initialize the delegate.
48723bbb 177
32b16651 178 :param font: Font used for the text.
48723bbb
JS
179 '''
180
181 super(self.__class__, self).__init__(parent)
182
183 self._nfont = font
48723bbb
JS
184
185 fi = QtGui.QFontInfo(self._nfont)
186 self._nfontheight = fi.pixelSize()
187
32b16651 188 fm = QtGui.QFontMetrics(self._nfont)
48723bbb 189 r = fm.boundingRect('-XX.XXXXXX X XX')
02862990 190
32b16651
JS
191 w = 1.4 * r.width() + 2 * self._nfontheight
192 h = 2.6 * self._nfontheight
193 self._size = QtCore.QSize(w, h)
48723bbb
JS
194
195 def sizeHint(self, option=None, index=None):
196 return self._size
197
32b16651
JS
198 def _color_rect(self, outer):
199 '''Returns the dimensions of the clickable rectangle.'''
200 x1 = (outer.height() - self._nfontheight) / 2
201 r = QtCore.QRect(x1, x1, self._nfontheight, self._nfontheight)
202 r.translate(outer.topLeft())
203 return r
204
48723bbb 205 def paint(self, painter, options, index):
02862990 206 value, unit = index.data(QtCore.Qt.DisplayRole)
48723bbb 207 desc = index.data(MeasurementDataModel.descRole)
32b16651 208 color = index.data(MeasurementDataModel.colorRole)
48723bbb 209
48723bbb 210 painter.setFont(self._nfont)
32b16651
JS
211
212 # Draw the clickable rectangle.
213 painter.fillRect(self._color_rect(options.rect), color)
214
215 # Draw the text
216 h = options.rect.height()
48723bbb 217 p = options.rect.topLeft()
32b16651 218 p += QtCore.QPoint(h, (h + self._nfontheight) / 2 - 2)
0e810ddf 219 painter.drawText(p, desc + ': ' + value + ' ' + unit)
32b16651
JS
220
221 def editorEvent(self, event, model, options, index):
222 if type(event) is QtGui.QMouseEvent:
223 if event.type() == QtCore.QEvent.MouseButtonPress:
224 rect = self._color_rect(options.rect)
225 if rect.contains(event.x(), event.y()):
226 c = index.data(MeasurementDataModel.colorRole)
227 c = QtGui.QColorDialog.getColor(c, None,
228 'Choose new color for channel')
4452730c
AS
229 if c.isValid():
230 # False if cancel is pressed (resulting in a black
231 # color)
232 item = model.itemFromIndex(index)
233 item.setData(c, MeasurementDataModel.colorRole)
32b16651
JS
234
235 return True
236
237 return False