Providing messages with asserts so if they are hit they are less confusing to a user
[gc-dialer] / src / util / qtpie.py
1 #!/usr/bin/env python
2
3 import math
4 import logging
5
6 from PyQt4 import QtGui
7 from PyQt4 import QtCore
8
9 try:
10         from util import misc as misc_utils
11 except ImportError:
12         class misc_utils(object):
13
14                 @staticmethod
15                 def log_exception(logger):
16
17                         def wrapper(func):
18                                 return func
19                         return wrapper
20
21
22 _moduleLogger = logging.getLogger(__name__)
23
24
25 _TWOPI = 2 * math.pi
26
27
28 def _radius_at(center, pos):
29         delta = pos - center
30         xDelta = delta.x()
31         yDelta = delta.y()
32
33         radius = math.sqrt(xDelta ** 2 + yDelta ** 2)
34         return radius
35
36
37 def _angle_at(center, pos):
38         delta = pos - center
39         xDelta = delta.x()
40         yDelta = delta.y()
41
42         radius = math.sqrt(xDelta ** 2 + yDelta ** 2)
43         angle = math.acos(xDelta / radius)
44         if 0 <= yDelta:
45                 angle = _TWOPI - angle
46
47         return angle
48
49
50 class QActionPieItem(object):
51
52         def __init__(self, action, weight = 1):
53                 self._action = action
54                 self._weight = weight
55
56         def action(self):
57                 return self._action
58
59         def setWeight(self, weight):
60                 self._weight = weight
61
62         def weight(self):
63                 return self._weight
64
65         def setEnabled(self, enabled = True):
66                 self._action.setEnabled(enabled)
67
68         def isEnabled(self):
69                 return self._action.isEnabled()
70
71
72 class PieFiling(object):
73
74         INNER_RADIUS_DEFAULT = 64
75         OUTER_RADIUS_DEFAULT = 192
76
77         SELECTION_CENTER = -1
78         SELECTION_NONE = -2
79
80         NULL_CENTER = QActionPieItem(QtGui.QAction(None))
81
82         def __init__(self):
83                 self._innerRadius = self.INNER_RADIUS_DEFAULT
84                 self._outerRadius = self.OUTER_RADIUS_DEFAULT
85                 self._children = []
86                 self._center = self.NULL_CENTER
87
88                 self._cacheIndexToAngle = {}
89                 self._cacheTotalWeight = 0
90
91         def insertItem(self, item, index = -1):
92                 self._children.insert(index, item)
93                 self._invalidate_cache()
94
95         def removeItemAt(self, index):
96                 item = self._children.pop(index)
97                 self._invalidate_cache()
98
99         def set_center(self, item):
100                 if item is None:
101                         item = self.NULL_CENTER
102                 self._center = item
103
104         def center(self):
105                 return self._center
106
107         def clear(self):
108                 del self._children[:]
109                 self._center = self.NULL_CENTER
110                 self._invalidate_cache()
111
112         def itemAt(self, index):
113                 return self._children[index]
114
115         def indexAt(self, center, point):
116                 return self._angle_to_index(_angle_at(center, point))
117
118         def innerRadius(self):
119                 return self._innerRadius
120
121         def setInnerRadius(self, radius):
122                 self._innerRadius = radius
123
124         def outerRadius(self):
125                 return self._outerRadius
126
127         def setOuterRadius(self, radius):
128                 self._outerRadius = radius
129
130         def __iter__(self):
131                 return iter(self._children)
132
133         def __len__(self):
134                 return len(self._children)
135
136         def __getitem__(self, index):
137                 return self._children[index]
138
139         def _invalidate_cache(self):
140                 self._cacheIndexToAngle.clear()
141                 self._cacheTotalWeight = sum(child.weight() for child in self._children)
142                 if self._cacheTotalWeight == 0:
143                         self._cacheTotalWeight = 1
144
145         def _index_to_angle(self, index, isShifted):
146                 key = index, isShifted
147                 if key in self._cacheIndexToAngle:
148                         return self._cacheIndexToAngle[key]
149                 index = index % len(self._children)
150
151                 baseAngle = _TWOPI / self._cacheTotalWeight
152
153                 angle = math.pi / 2
154                 if isShifted:
155                         if self._children:
156                                 angle -= (self._children[0].weight() * baseAngle) / 2
157                         else:
158                                 angle -= baseAngle / 2
159                 while angle < 0:
160                         angle += _TWOPI
161
162                 for i, child in enumerate(self._children):
163                         if index < i:
164                                 break
165                         angle += child.weight() * baseAngle
166                 while _TWOPI < angle:
167                         angle -= _TWOPI
168
169                 self._cacheIndexToAngle[key] = angle
170                 return angle
171
172         def _angle_to_index(self, angle):
173                 numChildren = len(self._children)
174                 if numChildren == 0:
175                         return self.SELECTION_CENTER
176
177                 baseAngle = _TWOPI / self._cacheTotalWeight
178
179                 iterAngle = math.pi / 2 - (self.itemAt(0).weight() * baseAngle) / 2
180                 while iterAngle < 0:
181                         iterAngle += _TWOPI
182
183                 oldIterAngle = iterAngle
184                 for index, child in enumerate(self._children):
185                         iterAngle += child.weight() * baseAngle
186                         if oldIterAngle < angle and angle <= iterAngle:
187                                 return index - 1 if index != 0 else numChildren - 1
188                         elif oldIterAngle < (angle + _TWOPI) and (angle + _TWOPI <= iterAngle):
189                                 return index - 1 if index != 0 else numChildren - 1
190                         oldIterAngle = iterAngle
191
192
193 class PieArtist(object):
194
195         ICON_SIZE_DEFAULT = 48
196
197         SHAPE_CIRCLE = "circle"
198         SHAPE_SQUARE = "square"
199         DEFAULT_SHAPE = SHAPE_SQUARE
200
201         def __init__(self, filing):
202                 self._filing = filing
203
204                 self._cachedOuterRadius = self._filing.outerRadius()
205                 self._cachedInnerRadius = self._filing.innerRadius()
206                 canvasSize = self._cachedOuterRadius * 2 + 1
207                 self._canvas = QtGui.QPixmap(canvasSize, canvasSize)
208                 self._mask = None
209                 self.palette = None
210
211         def pieSize(self):
212                 diameter = self._filing.outerRadius() * 2 + 1
213                 return QtCore.QSize(diameter, diameter)
214
215         def centerSize(self):
216                 painter = QtGui.QPainter(self._canvas)
217                 text = self._filing.center().action().text()
218                 fontMetrics = painter.fontMetrics()
219                 if text:
220                         textBoundingRect = fontMetrics.boundingRect(text)
221                 else:
222                         textBoundingRect = QtCore.QRect()
223                 textWidth = textBoundingRect.width()
224                 textHeight = textBoundingRect.height()
225
226                 return QtCore.QSize(
227                         textWidth + self.ICON_SIZE_DEFAULT,
228                         max(textHeight, self.ICON_SIZE_DEFAULT),
229                 )
230
231         def show(self, palette):
232                 self.palette = palette
233
234                 if (
235                         self._cachedOuterRadius != self._filing.outerRadius() or
236                         self._cachedInnerRadius != self._filing.innerRadius()
237                 ):
238                         self._cachedOuterRadius = self._filing.outerRadius()
239                         self._cachedInnerRadius = self._filing.innerRadius()
240                         self._canvas = self._canvas.scaled(self.pieSize())
241
242                 if self._mask is None:
243                         self._mask = QtGui.QBitmap(self._canvas.size())
244                         self._mask.fill(QtCore.Qt.color0)
245                         self._generate_mask(self._mask)
246                         self._canvas.setMask(self._mask)
247                 return self._mask
248
249         def hide(self):
250                 self.palette = None
251
252         def paint(self, selectionIndex):
253                 painter = QtGui.QPainter(self._canvas)
254                 painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
255
256                 adjustmentRect = self._canvas.rect().adjusted(0, 0, -1, -1)
257
258                 numChildren = len(self._filing)
259                 if numChildren == 0:
260                         if selectionIndex == PieFiling.SELECTION_CENTER and self._filing.center().isEnabled():
261                                 painter.setBrush(self.palette.highlight())
262                         else:
263                                 painter.setBrush(self.palette.window())
264                         painter.setPen(self.palette.mid().color())
265
266                         painter.drawRect(self._canvas.rect())
267                         self._paint_center_foreground(painter, selectionIndex)
268                         return self._canvas
269                 elif numChildren == 1:
270                         if selectionIndex == 0 and self._filing[0].isEnabled():
271                                 painter.setBrush(self.palette.highlight())
272                         else:
273                                 painter.setBrush(self.palette.window())
274
275                         painter.fillRect(self._canvas.rect(), painter.brush())
276                 else:
277                         for i in xrange(len(self._filing)):
278                                 self._paint_slice_background(painter, adjustmentRect, i, selectionIndex)
279
280                 self._paint_center_background(painter, adjustmentRect, selectionIndex)
281                 self._paint_center_foreground(painter, selectionIndex)
282
283                 for i in xrange(len(self._filing)):
284                         self._paint_slice_foreground(painter, i, selectionIndex)
285
286                 return self._canvas
287
288         def _generate_mask(self, mask):
289                 """
290                 Specifies on the mask the shape of the pie menu
291                 """
292                 painter = QtGui.QPainter(mask)
293                 painter.setPen(QtCore.Qt.color1)
294                 painter.setBrush(QtCore.Qt.color1)
295                 if self.DEFAULT_SHAPE == self.SHAPE_SQUARE:
296                         painter.drawRect(mask.rect())
297                 elif self.DEFAULT_SHAPE == self.SHAPE_CIRCLE:
298                         painter.drawEllipse(mask.rect().adjusted(0, 0, -1, -1))
299                 else:
300                         raise NotImplementedError(self.DEFAULT_SHAPE)
301
302         def _paint_slice_background(self, painter, adjustmentRect, i, selectionIndex):
303                 if self.DEFAULT_SHAPE == self.SHAPE_SQUARE:
304                         currentWidth = adjustmentRect.width()
305                         newWidth = math.sqrt(2) * currentWidth
306                         dx = (newWidth - currentWidth) / 2
307                         adjustmentRect = adjustmentRect.adjusted(-dx, -dx, dx, dx)
308                 elif self.DEFAULT_SHAPE == self.SHAPE_CIRCLE:
309                         pass
310                 else:
311                         raise NotImplementedError(self.DEFAULT_SHAPE)
312
313                 if i == selectionIndex and self._filing[i].isEnabled():
314                         painter.setBrush(self.palette.highlight())
315                 else:
316                         painter.setBrush(self.palette.window())
317                 painter.setPen(self.palette.mid().color())
318
319                 a = self._filing._index_to_angle(i, True)
320                 b = self._filing._index_to_angle(i + 1, True)
321                 if b < a:
322                         b += _TWOPI
323                 size = b - a
324                 if size < 0:
325                         size += _TWOPI
326
327                 startAngleInDeg = (a * 360 * 16) / _TWOPI
328                 sizeInDeg = (size * 360 * 16) / _TWOPI
329                 painter.drawPie(adjustmentRect, int(startAngleInDeg), int(sizeInDeg))
330
331         def _paint_slice_foreground(self, painter, i, selectionIndex):
332                 child = self._filing[i]
333
334                 a = self._filing._index_to_angle(i, True)
335                 b = self._filing._index_to_angle(i + 1, True)
336                 if b < a:
337                         b += _TWOPI
338                 middleAngle = (a + b) / 2
339                 averageRadius = (self._cachedInnerRadius + self._cachedOuterRadius) / 2
340
341                 sliceX = averageRadius * math.cos(middleAngle)
342                 sliceY = - averageRadius * math.sin(middleAngle)
343
344                 piePos = self._canvas.rect().center()
345                 pieX = piePos.x()
346                 pieY = piePos.y()
347                 self._paint_label(
348                         painter, child.action(), i == selectionIndex, pieX+sliceX, pieY+sliceY
349                 )
350
351         def _paint_label(self, painter, action, isSelected, x, y):
352                 text = action.text()
353                 fontMetrics = painter.fontMetrics()
354                 if text:
355                         textBoundingRect = fontMetrics.boundingRect(text)
356                 else:
357                         textBoundingRect = QtCore.QRect()
358                 textWidth = textBoundingRect.width()
359                 textHeight = textBoundingRect.height()
360
361                 icon = action.icon().pixmap(
362                         QtCore.QSize(self.ICON_SIZE_DEFAULT, self.ICON_SIZE_DEFAULT),
363                         QtGui.QIcon.Normal,
364                         QtGui.QIcon.On,
365                 )
366                 iconWidth = icon.width()
367                 iconHeight = icon.width()
368                 averageWidth = (iconWidth + textWidth)/2
369                 if not icon.isNull():
370                         iconRect = QtCore.QRect(
371                                 x - averageWidth,
372                                 y - iconHeight/2,
373                                 iconWidth,
374                                 iconHeight,
375                         )
376
377                         painter.drawPixmap(iconRect, icon)
378
379                 if text:
380                         if isSelected:
381                                 if action.isEnabled():
382                                         pen = self.palette.highlightedText()
383                                         brush = self.palette.highlight()
384                                 else:
385                                         pen = self.palette.mid()
386                                         brush = self.palette.window()
387                         else:
388                                 if action.isEnabled():
389                                         pen = self.palette.windowText()
390                                 else:
391                                         pen = self.palette.mid()
392                                 brush = self.palette.window()
393
394                         leftX = x - averageWidth + iconWidth
395                         topY = y + textHeight/2
396                         painter.setPen(pen.color())
397                         painter.setBrush(brush)
398                         painter.drawText(leftX, topY, text)
399
400         def _paint_center_background(self, painter, adjustmentRect, selectionIndex):
401                 dark = self.palette.mid().color()
402                 light = self.palette.light().color()
403                 if selectionIndex == PieFiling.SELECTION_CENTER and self._filing.center().isEnabled():
404                         background = self.palette.highlight().color()
405                 else:
406                         background = self.palette.window().color()
407
408                 innerRadius = self._cachedInnerRadius
409                 adjustmentCenterPos = adjustmentRect.center()
410                 innerRect = QtCore.QRect(
411                         adjustmentCenterPos.x() - innerRadius,
412                         adjustmentCenterPos.y() - innerRadius,
413                         innerRadius * 2 + 1,
414                         innerRadius * 2 + 1,
415                 )
416
417                 painter.setPen(QtCore.Qt.NoPen)
418                 painter.setBrush(background)
419                 painter.drawPie(innerRect, 0, 360 * 16)
420
421                 painter.setPen(QtGui.QPen(dark, 1))
422                 painter.setBrush(QtCore.Qt.NoBrush)
423                 painter.drawEllipse(innerRect)
424
425                 if self.DEFAULT_SHAPE == self.SHAPE_SQUARE:
426                         pass
427                 elif self.DEFAULT_SHAPE == self.SHAPE_CIRCLE:
428                         painter.setPen(QtGui.QPen(dark, 1))
429                         painter.setBrush(QtCore.Qt.NoBrush)
430                         painter.drawEllipse(adjustmentRect)
431                 else:
432                         raise NotImplementedError(self.DEFAULT_SHAPE)
433
434         def _paint_center_foreground(self, painter, selectionIndex):
435                 centerPos = self._canvas.rect().center()
436                 pieX = centerPos.x()
437                 pieY = centerPos.y()
438
439                 x = pieX
440                 y = pieY
441
442                 self._paint_label(
443                         painter,
444                         self._filing.center().action(),
445                         selectionIndex == PieFiling.SELECTION_CENTER,
446                         x, y
447                 )
448
449
450 class QPieDisplay(QtGui.QWidget):
451
452         def __init__(self, filing, parent = None, flags = QtCore.Qt.Window):
453                 QtGui.QWidget.__init__(self, parent, flags)
454                 self._filing = filing
455                 self._artist = PieArtist(self._filing)
456                 self._selectionIndex = PieFiling.SELECTION_NONE
457
458         def popup(self, pos):
459                 self._update_selection(pos)
460                 self.show()
461
462         def sizeHint(self):
463                 return self._artist.pieSize()
464
465         @misc_utils.log_exception(_moduleLogger)
466         def showEvent(self, showEvent):
467                 mask = self._artist.show(self.palette())
468                 self.setMask(mask)
469
470                 QtGui.QWidget.showEvent(self, showEvent)
471
472         @misc_utils.log_exception(_moduleLogger)
473         def hideEvent(self, hideEvent):
474                 self._artist.hide()
475                 self._selectionIndex = PieFiling.SELECTION_NONE
476                 QtGui.QWidget.hideEvent(self, hideEvent)
477
478         @misc_utils.log_exception(_moduleLogger)
479         def paintEvent(self, paintEvent):
480                 canvas = self._artist.paint(self._selectionIndex)
481
482                 screen = QtGui.QPainter(self)
483                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
484
485                 QtGui.QWidget.paintEvent(self, paintEvent)
486
487         def selectAt(self, index):
488                 oldIndex = self._selectionIndex
489                 self._selectionIndex = index
490                 if self.isVisible():
491                         self.update()
492
493
494 class QPieButton(QtGui.QWidget):
495
496         activated = QtCore.pyqtSignal(int)
497         highlighted = QtCore.pyqtSignal(int)
498         canceled = QtCore.pyqtSignal()
499         aboutToShow = QtCore.pyqtSignal()
500         aboutToHide = QtCore.pyqtSignal()
501
502         BUTTON_RADIUS = 24
503         DELAY = 250
504
505         def __init__(self, buttonSlice, parent = None, buttonSlices = None):
506                 # @bug Artifacts on Maemo 5 due to window 3D effects, find way to disable them for just these?
507                 # @bug The pie's are being pushed back on screen on Maemo, leading to coordinate issues
508                 QtGui.QWidget.__init__(self, parent)
509                 self._cachedCenterPosition = self.rect().center()
510
511                 self._filing = PieFiling()
512                 self._display = QPieDisplay(self._filing, None, QtCore.Qt.SplashScreen)
513                 self._selectionIndex = PieFiling.SELECTION_NONE
514
515                 self._buttonFiling = PieFiling()
516                 self._buttonFiling.set_center(buttonSlice)
517                 if buttonSlices is not None:
518                         for slice in buttonSlices:
519                                 self._buttonFiling.insertItem(slice)
520                 self._buttonFiling.setOuterRadius(self.BUTTON_RADIUS)
521                 self._buttonArtist = PieArtist(self._buttonFiling)
522                 self._poppedUp = False
523
524                 self._delayPopupTimer = QtCore.QTimer()
525                 self._delayPopupTimer.setInterval(self.DELAY)
526                 self._delayPopupTimer.setSingleShot(True)
527                 self._delayPopupTimer.timeout.connect(self._on_delayed_popup)
528                 self._popupLocation = None
529
530                 self._mousePosition = None
531                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
532                 self.setSizePolicy(
533                         QtGui.QSizePolicy(
534                                 QtGui.QSizePolicy.MinimumExpanding,
535                                 QtGui.QSizePolicy.MinimumExpanding,
536                         )
537                 )
538
539         def insertItem(self, item, index = -1):
540                 self._filing.insertItem(item, index)
541
542         def removeItemAt(self, index):
543                 self._filing.removeItemAt(index)
544
545         def set_center(self, item):
546                 self._filing.set_center(item)
547
548         def set_button(self, item):
549                 self.update()
550
551         def clear(self):
552                 self._filing.clear()
553
554         def itemAt(self, index):
555                 return self._filing.itemAt(index)
556
557         def indexAt(self, point):
558                 return self._filing.indexAt(self._cachedCenterPosition, point)
559
560         def innerRadius(self):
561                 return self._filing.innerRadius()
562
563         def setInnerRadius(self, radius):
564                 self._filing.setInnerRadius(radius)
565
566         def outerRadius(self):
567                 return self._filing.outerRadius()
568
569         def setOuterRadius(self, radius):
570                 self._filing.setOuterRadius(radius)
571
572         def buttonRadius(self):
573                 return self._buttonFiling.outerRadius()
574
575         def setButtonRadius(self, radius):
576                 self._buttonFiling.setOuterRadius(radius)
577                 self._buttonFiling.setInnerRadius(radius / 2)
578                 self._buttonArtist.show(self.palette())
579
580         def sizeHint(self):
581                 return self._buttonArtist.pieSize()
582
583         def minimumSizeHint(self):
584                 return self._buttonArtist.centerSize()
585
586         @misc_utils.log_exception(_moduleLogger)
587         def mousePressEvent(self, mouseEvent):
588                 lastSelection = self._selectionIndex
589
590                 lastMousePos = mouseEvent.pos()
591                 self._mousePosition = lastMousePos
592                 self._update_selection(self._cachedCenterPosition)
593
594                 self.highlighted.emit(self._selectionIndex)
595
596                 self._display.selectAt(self._selectionIndex)
597                 self._popupLocation = mouseEvent.globalPos()
598                 self._delayPopupTimer.start()
599
600         @QtCore.pyqtSlot()
601         @misc_utils.log_exception(_moduleLogger)
602         def _on_delayed_popup(self):
603                 assert self._popupLocation is not None, "Widget location abuse"
604                 self._popup_child(self._popupLocation)
605
606         @misc_utils.log_exception(_moduleLogger)
607         def mouseMoveEvent(self, mouseEvent):
608                 lastSelection = self._selectionIndex
609
610                 lastMousePos = mouseEvent.pos()
611                 if self._mousePosition is None:
612                         # Absolute
613                         self._update_selection(lastMousePos)
614                 else:
615                         # Relative
616                         self._update_selection(
617                                 self._cachedCenterPosition + (lastMousePos - self._mousePosition),
618                                 ignoreOuter = True,
619                         )
620
621                 if lastSelection != self._selectionIndex:
622                         self.highlighted.emit(self._selectionIndex)
623                         self._display.selectAt(self._selectionIndex)
624
625                 if self._selectionIndex != PieFiling.SELECTION_CENTER and self._delayPopupTimer.isActive():
626                         self._on_delayed_popup()
627
628         @misc_utils.log_exception(_moduleLogger)
629         def mouseReleaseEvent(self, mouseEvent):
630                 self._delayPopupTimer.stop()
631                 self._popupLocation = None
632
633                 lastSelection = self._selectionIndex
634
635                 lastMousePos = mouseEvent.pos()
636                 if self._mousePosition is None:
637                         # Absolute
638                         self._update_selection(lastMousePos)
639                 else:
640                         # Relative
641                         self._update_selection(
642                                 self._cachedCenterPosition + (lastMousePos - self._mousePosition),
643                                 ignoreOuter = True,
644                         )
645                 self._mousePosition = None
646
647                 self._activate_at(self._selectionIndex)
648                 self._hide_child()
649
650         @misc_utils.log_exception(_moduleLogger)
651         def keyPressEvent(self, keyEvent):
652                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
653                         self._popup_child(QtGui.QCursor.pos())
654                         if self._selectionIndex != len(self._filing) - 1:
655                                 nextSelection = self._selectionIndex + 1
656                         else:
657                                 nextSelection = 0
658                         self._select_at(nextSelection)
659                         self._display.selectAt(self._selectionIndex)
660                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
661                         self._popup_child(QtGui.QCursor.pos())
662                         if 0 < self._selectionIndex:
663                                 nextSelection = self._selectionIndex - 1
664                         else:
665                                 nextSelection = len(self._filing) - 1
666                         self._select_at(nextSelection)
667                         self._display.selectAt(self._selectionIndex)
668                 elif keyEvent.key() in [QtCore.Qt.Key_Space]:
669                         self._popup_child(QtGui.QCursor.pos())
670                         self._select_at(PieFiling.SELECTION_CENTER)
671                         self._display.selectAt(self._selectionIndex)
672                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
673                         self._delayPopupTimer.stop()
674                         self._popupLocation = None
675                         self._activate_at(self._selectionIndex)
676                         self._hide_child()
677                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
678                         self._delayPopupTimer.stop()
679                         self._popupLocation = None
680                         self._activate_at(PieFiling.SELECTION_NONE)
681                         self._hide_child()
682                 else:
683                         QtGui.QWidget.keyPressEvent(self, keyEvent)
684
685         @misc_utils.log_exception(_moduleLogger)
686         def resizeEvent(self, resizeEvent):
687                 self.setButtonRadius(min(resizeEvent.size().width(), resizeEvent.size().height()) / 2 - 1)
688                 QtGui.QWidget.resizeEvent(self, resizeEvent)
689
690         @misc_utils.log_exception(_moduleLogger)
691         def showEvent(self, showEvent):
692                 self._buttonArtist.show(self.palette())
693                 self._cachedCenterPosition = self.rect().center()
694
695                 QtGui.QWidget.showEvent(self, showEvent)
696
697         @misc_utils.log_exception(_moduleLogger)
698         def hideEvent(self, hideEvent):
699                 self._display.hide()
700                 self._select_at(PieFiling.SELECTION_NONE)
701                 QtGui.QWidget.hideEvent(self, hideEvent)
702
703         @misc_utils.log_exception(_moduleLogger)
704         def paintEvent(self, paintEvent):
705                 self.setButtonRadius(min(self.rect().width(), self.rect().height()) / 2 - 1)
706                 if self._poppedUp:
707                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_CENTER)
708                 else:
709                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_NONE)
710
711                 screen = QtGui.QPainter(self)
712                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
713
714                 QtGui.QWidget.paintEvent(self, paintEvent)
715
716         def __iter__(self):
717                 return iter(self._filing)
718
719         def __len__(self):
720                 return len(self._filing)
721
722         def _popup_child(self, position):
723                 self._poppedUp = True
724                 self.aboutToShow.emit()
725
726                 self._delayPopupTimer.stop()
727                 self._popupLocation = None
728
729                 position = position - QtCore.QPoint(self._filing.outerRadius(), self._filing.outerRadius())
730                 self._display.move(position)
731                 self._display.show()
732
733                 self.update()
734
735         def _hide_child(self):
736                 self._poppedUp = False
737                 self.aboutToHide.emit()
738                 self._display.hide()
739                 self.update()
740
741         def _select_at(self, index):
742                 self._selectionIndex = index
743
744         def _update_selection(self, lastMousePos, ignoreOuter = False):
745                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
746                 if radius < self._filing.innerRadius():
747                         self._select_at(PieFiling.SELECTION_CENTER)
748                 elif radius <= self._filing.outerRadius() or ignoreOuter:
749                         self._select_at(self.indexAt(lastMousePos))
750                 else:
751                         self._select_at(PieFiling.SELECTION_NONE)
752
753         def _activate_at(self, index):
754                 if index == PieFiling.SELECTION_NONE:
755                         self.canceled.emit()
756                         return
757                 elif index == PieFiling.SELECTION_CENTER:
758                         child = self._filing.center()
759                 else:
760                         child = self.itemAt(index)
761
762                 if child.action().isEnabled():
763                         child.action().trigger()
764                         self.activated.emit(index)
765                 else:
766                         self.canceled.emit()
767
768
769 class QPieMenu(QtGui.QWidget):
770
771         activated = QtCore.pyqtSignal(int)
772         highlighted = QtCore.pyqtSignal(int)
773         canceled = QtCore.pyqtSignal()
774         aboutToShow = QtCore.pyqtSignal()
775         aboutToHide = QtCore.pyqtSignal()
776
777         def __init__(self, parent = None):
778                 QtGui.QWidget.__init__(self, parent)
779                 self._cachedCenterPosition = self.rect().center()
780
781                 self._filing = PieFiling()
782                 self._artist = PieArtist(self._filing)
783                 self._selectionIndex = PieFiling.SELECTION_NONE
784
785                 self._mousePosition = ()
786                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
787
788         def popup(self, pos):
789                 self._update_selection(pos)
790                 self.show()
791
792         def insertItem(self, item, index = -1):
793                 self._filing.insertItem(item, index)
794                 self.update()
795
796         def removeItemAt(self, index):
797                 self._filing.removeItemAt(index)
798                 self.update()
799
800         def set_center(self, item):
801                 self._filing.set_center(item)
802                 self.update()
803
804         def clear(self):
805                 self._filing.clear()
806                 self.update()
807
808         def itemAt(self, index):
809                 return self._filing.itemAt(index)
810
811         def indexAt(self, point):
812                 return self._filing.indexAt(self._cachedCenterPosition, point)
813
814         def innerRadius(self):
815                 return self._filing.innerRadius()
816
817         def setInnerRadius(self, radius):
818                 self._filing.setInnerRadius(radius)
819                 self.update()
820
821         def outerRadius(self):
822                 return self._filing.outerRadius()
823
824         def setOuterRadius(self, radius):
825                 self._filing.setOuterRadius(radius)
826                 self.update()
827
828         def sizeHint(self):
829                 return self._artist.pieSize()
830
831         @misc_utils.log_exception(_moduleLogger)
832         def mousePressEvent(self, mouseEvent):
833                 lastSelection = self._selectionIndex
834
835                 lastMousePos = mouseEvent.pos()
836                 self._update_selection(lastMousePos)
837                 self._mousePosition = lastMousePos
838
839                 if lastSelection != self._selectionIndex:
840                         self.highlighted.emit(self._selectionIndex)
841                         self.update()
842
843         @misc_utils.log_exception(_moduleLogger)
844         def mouseMoveEvent(self, mouseEvent):
845                 lastSelection = self._selectionIndex
846
847                 lastMousePos = mouseEvent.pos()
848                 self._update_selection(lastMousePos)
849
850                 if lastSelection != self._selectionIndex:
851                         self.highlighted.emit(self._selectionIndex)
852                         self.update()
853
854         @misc_utils.log_exception(_moduleLogger)
855         def mouseReleaseEvent(self, mouseEvent):
856                 lastSelection = self._selectionIndex
857
858                 lastMousePos = mouseEvent.pos()
859                 self._update_selection(lastMousePos)
860                 self._mousePosition = ()
861
862                 self._activate_at(self._selectionIndex)
863                 self.update()
864
865         @misc_utils.log_exception(_moduleLogger)
866         def keyPressEvent(self, keyEvent):
867                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
868                         if self._selectionIndex != len(self._filing) - 1:
869                                 nextSelection = self._selectionIndex + 1
870                         else:
871                                 nextSelection = 0
872                         self._select_at(nextSelection)
873                         self.update()
874                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
875                         if 0 < self._selectionIndex:
876                                 nextSelection = self._selectionIndex - 1
877                         else:
878                                 nextSelection = len(self._filing) - 1
879                         self._select_at(nextSelection)
880                         self.update()
881                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
882                         self._activate_at(self._selectionIndex)
883                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
884                         self._activate_at(PieFiling.SELECTION_NONE)
885                 else:
886                         QtGui.QWidget.keyPressEvent(self, keyEvent)
887
888         @misc_utils.log_exception(_moduleLogger)
889         def showEvent(self, showEvent):
890                 self.aboutToShow.emit()
891                 self._cachedCenterPosition = self.rect().center()
892
893                 mask = self._artist.show(self.palette())
894                 self.setMask(mask)
895
896                 lastMousePos = self.mapFromGlobal(QtGui.QCursor.pos())
897                 self._update_selection(lastMousePos)
898
899                 QtGui.QWidget.showEvent(self, showEvent)
900
901         @misc_utils.log_exception(_moduleLogger)
902         def hideEvent(self, hideEvent):
903                 self._artist.hide()
904                 self._selectionIndex = PieFiling.SELECTION_NONE
905                 QtGui.QWidget.hideEvent(self, hideEvent)
906
907         @misc_utils.log_exception(_moduleLogger)
908         def paintEvent(self, paintEvent):
909                 canvas = self._artist.paint(self._selectionIndex)
910
911                 screen = QtGui.QPainter(self)
912                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
913
914                 QtGui.QWidget.paintEvent(self, paintEvent)
915
916         def __iter__(self):
917                 return iter(self._filing)
918
919         def __len__(self):
920                 return len(self._filing)
921
922         def _select_at(self, index):
923                 self._selectionIndex = index
924
925         def _update_selection(self, lastMousePos):
926                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
927                 if radius < self._filing.innerRadius():
928                         self._selectionIndex = PieFiling.SELECTION_CENTER
929                 elif radius <= self._filing.outerRadius():
930                         self._select_at(self.indexAt(lastMousePos))
931                 else:
932                         self._selectionIndex = PieFiling.SELECTION_NONE
933
934         def _activate_at(self, index):
935                 if index == PieFiling.SELECTION_NONE:
936                         self.canceled.emit()
937                         self.aboutToHide.emit()
938                         self.hide()
939                         return
940                 elif index == PieFiling.SELECTION_CENTER:
941                         child = self._filing.center()
942                 else:
943                         child = self.itemAt(index)
944
945                 if child.isEnabled():
946                         child.action().trigger()
947                         self.activated.emit(index)
948                 else:
949                         self.canceled.emit()
950                 self.aboutToHide.emit()
951                 self.hide()
952
953
954 def init_pies():
955         PieFiling.NULL_CENTER.setEnabled(False)
956
957
958 def _print(msg):
959         print msg
960
961
962 def _on_about_to_hide(app):
963         app.exit()
964
965
966 if __name__ == "__main__":
967         app = QtGui.QApplication([])
968         init_pies()
969
970         if False:
971                 pie = QPieMenu()
972                 pie.show()
973
974         if False:
975                 singleAction = QtGui.QAction(None)
976                 singleAction.setText("Boo")
977                 singleItem = QActionPieItem(singleAction)
978                 spie = QPieMenu()
979                 spie.insertItem(singleItem)
980                 spie.show()
981
982         if False:
983                 oneAction = QtGui.QAction(None)
984                 oneAction.setText("Chew")
985                 oneItem = QActionPieItem(oneAction)
986                 twoAction = QtGui.QAction(None)
987                 twoAction.setText("Foo")
988                 twoItem = QActionPieItem(twoAction)
989                 iconTextAction = QtGui.QAction(None)
990                 iconTextAction.setText("Icon")
991                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
992                 iconTextItem = QActionPieItem(iconTextAction)
993                 mpie = QPieMenu()
994                 mpie.insertItem(oneItem)
995                 mpie.insertItem(twoItem)
996                 mpie.insertItem(oneItem)
997                 mpie.insertItem(iconTextItem)
998                 mpie.show()
999
1000         if True:
1001                 oneAction = QtGui.QAction(None)
1002                 oneAction.setText("Chew")
1003                 oneAction.triggered.connect(lambda: _print("Chew"))
1004                 oneItem = QActionPieItem(oneAction)
1005                 twoAction = QtGui.QAction(None)
1006                 twoAction.setText("Foo")
1007                 twoAction.triggered.connect(lambda: _print("Foo"))
1008                 twoItem = QActionPieItem(twoAction)
1009                 iconAction = QtGui.QAction(None)
1010                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
1011                 iconAction.triggered.connect(lambda: _print("Icon"))
1012                 iconItem = QActionPieItem(iconAction)
1013                 iconTextAction = QtGui.QAction(None)
1014                 iconTextAction.setText("Icon")
1015                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
1016                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
1017                 iconTextItem = QActionPieItem(iconTextAction)
1018                 mpie = QPieMenu()
1019                 mpie.set_center(iconItem)
1020                 mpie.insertItem(oneItem)
1021                 mpie.insertItem(twoItem)
1022                 mpie.insertItem(oneItem)
1023                 mpie.insertItem(iconTextItem)
1024                 mpie.show()
1025                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
1026                 mpie.canceled.connect(lambda: _print("Canceled"))
1027
1028         if False:
1029                 oneAction = QtGui.QAction(None)
1030                 oneAction.setText("Chew")
1031                 oneAction.triggered.connect(lambda: _print("Chew"))
1032                 oneItem = QActionPieItem(oneAction)
1033                 twoAction = QtGui.QAction(None)
1034                 twoAction.setText("Foo")
1035                 twoAction.triggered.connect(lambda: _print("Foo"))
1036                 twoItem = QActionPieItem(twoAction)
1037                 iconAction = QtGui.QAction(None)
1038                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
1039                 iconAction.triggered.connect(lambda: _print("Icon"))
1040                 iconItem = QActionPieItem(iconAction)
1041                 iconTextAction = QtGui.QAction(None)
1042                 iconTextAction.setText("Icon")
1043                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
1044                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
1045                 iconTextItem = QActionPieItem(iconTextAction)
1046                 pieFiling = PieFiling()
1047                 pieFiling.set_center(iconItem)
1048                 pieFiling.insertItem(oneItem)
1049                 pieFiling.insertItem(twoItem)
1050                 pieFiling.insertItem(oneItem)
1051                 pieFiling.insertItem(iconTextItem)
1052                 mpie = QPieDisplay(pieFiling)
1053                 mpie.show()
1054
1055         if False:
1056                 oneAction = QtGui.QAction(None)
1057                 oneAction.setText("Chew")
1058                 oneAction.triggered.connect(lambda: _print("Chew"))
1059                 oneItem = QActionPieItem(oneAction)
1060                 twoAction = QtGui.QAction(None)
1061                 twoAction.setText("Foo")
1062                 twoAction.triggered.connect(lambda: _print("Foo"))
1063                 twoItem = QActionPieItem(twoAction)
1064                 iconAction = QtGui.QAction(None)
1065                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
1066                 iconAction.triggered.connect(lambda: _print("Icon"))
1067                 iconItem = QActionPieItem(iconAction)
1068                 iconTextAction = QtGui.QAction(None)
1069                 iconTextAction.setText("Icon")
1070                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
1071                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
1072                 iconTextItem = QActionPieItem(iconTextAction)
1073                 mpie = QPieButton(iconItem)
1074                 mpie.set_center(iconItem)
1075                 mpie.insertItem(oneItem)
1076                 mpie.insertItem(twoItem)
1077                 mpie.insertItem(oneItem)
1078                 mpie.insertItem(iconTextItem)
1079                 mpie.show()
1080                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
1081                 mpie.canceled.connect(lambda: _print("Canceled"))
1082
1083         app.exec_()