Cleaning up some dead code
[ejpi] / src / libraries / 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 = 32
75         OUTER_RADIUS_DEFAULT = 128
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 = 32
196
197         def __init__(self, filing):
198                 self._filing = filing
199
200                 self._cachedOuterRadius = self._filing.outerRadius()
201                 self._cachedInnerRadius = self._filing.innerRadius()
202                 canvasSize = self._cachedOuterRadius * 2 + 1
203                 self._canvas = QtGui.QPixmap(canvasSize, canvasSize)
204                 self._mask = None
205                 self.palette = None
206
207         def pieSize(self):
208                 diameter = self._filing.outerRadius() * 2 + 1
209                 return QtCore.QSize(diameter, diameter)
210
211         def centerSize(self):
212                 painter = QtGui.QPainter(self._canvas)
213                 text = self._filing.center().action().text()
214                 fontMetrics = painter.fontMetrics()
215                 if text:
216                         textBoundingRect = fontMetrics.boundingRect(text)
217                 else:
218                         textBoundingRect = QtCore.QRect()
219                 textWidth = textBoundingRect.width()
220                 textHeight = textBoundingRect.height()
221
222                 return QtCore.QSize(
223                         textWidth + self.ICON_SIZE_DEFAULT,
224                         max(textHeight, self.ICON_SIZE_DEFAULT),
225                 )
226
227         def show(self, palette):
228                 self.palette = palette
229
230                 if (
231                         self._cachedOuterRadius != self._filing.outerRadius() or
232                         self._cachedInnerRadius != self._filing.innerRadius()
233                 ):
234                         self._cachedOuterRadius = self._filing.outerRadius()
235                         self._cachedInnerRadius = self._filing.innerRadius()
236                         self._canvas = self._canvas.scaled(self.pieSize())
237
238                 if self._mask is None:
239                         self._mask = QtGui.QBitmap(self._canvas.size())
240                         self._mask.fill(QtCore.Qt.color0)
241                         self._generate_mask(self._mask)
242                         self._canvas.setMask(self._mask)
243                 return self._mask
244
245         def hide(self):
246                 self.palette = None
247
248         def paint(self, selectionIndex):
249                 painter = QtGui.QPainter(self._canvas)
250                 painter.setRenderHint(QtGui.QPainter.Antialiasing, True)
251
252                 adjustmentRect = self._canvas.rect().adjusted(0, 0, -1, -1)
253
254                 numChildren = len(self._filing)
255                 if numChildren == 0:
256                         if selectionIndex == PieFiling.SELECTION_CENTER and self._filing.center().isEnabled():
257                                 painter.setBrush(self.palette.highlight())
258                         else:
259                                 painter.setBrush(self.palette.background())
260                         painter.setPen(self.palette.mid().color())
261
262                         painter.drawRect(self._canvas.rect())
263                         self._paint_center_foreground(painter, selectionIndex)
264                         return self._canvas
265                 elif numChildren == 1:
266                         if selectionIndex == 0 and self._filing[0].isEnabled():
267                                 painter.setBrush(self.palette.highlight())
268                         else:
269                                 painter.setBrush(self.palette.background())
270
271                         painter.fillRect(self._canvas.rect(), painter.brush())
272                 else:
273                         for i in xrange(len(self._filing)):
274                                 self._paint_slice_background(painter, adjustmentRect, i, selectionIndex)
275
276                 self._paint_center_background(painter, adjustmentRect, selectionIndex)
277                 self._paint_center_foreground(painter, selectionIndex)
278
279                 for i in xrange(len(self._filing)):
280                         self._paint_slice_foreground(painter, i, selectionIndex)
281
282                 return self._canvas
283
284         def _generate_mask(self, mask):
285                 """
286                 Specifies on the mask the shape of the pie menu
287                 """
288                 painter = QtGui.QPainter(mask)
289                 painter.setPen(QtCore.Qt.color1)
290                 painter.setBrush(QtCore.Qt.color1)
291                 painter.drawEllipse(mask.rect().adjusted(0, 0, -1, -1))
292
293         def _paint_slice_background(self, painter, adjustmentRect, i, selectionIndex):
294                 if i == selectionIndex and self._filing[i].isEnabled():
295                         painter.setBrush(self.palette.highlight())
296                 else:
297                         painter.setBrush(self.palette.background())
298                 painter.setPen(self.palette.mid().color())
299
300                 a = self._filing._index_to_angle(i, True)
301                 b = self._filing._index_to_angle(i + 1, True)
302                 if b < a:
303                         b += _TWOPI
304                 size = b - a
305                 if size < 0:
306                         size += _TWOPI
307
308                 startAngleInDeg = (a * 360 * 16) / _TWOPI
309                 sizeInDeg = (size * 360 * 16) / _TWOPI
310                 painter.drawPie(adjustmentRect, int(startAngleInDeg), int(sizeInDeg))
311
312         def _paint_slice_foreground(self, painter, i, selectionIndex):
313                 child = self._filing[i]
314
315                 a = self._filing._index_to_angle(i, True)
316                 b = self._filing._index_to_angle(i + 1, True)
317                 if b < a:
318                         b += _TWOPI
319                 middleAngle = (a + b) / 2
320                 averageRadius = (self._cachedInnerRadius + self._cachedOuterRadius) / 2
321
322                 sliceX = averageRadius * math.cos(middleAngle)
323                 sliceY = - averageRadius * math.sin(middleAngle)
324
325                 piePos = self._canvas.rect().center()
326                 pieX = piePos.x()
327                 pieY = piePos.y()
328                 self._paint_label(
329                         painter, child.action(), i == selectionIndex, pieX+sliceX, pieY+sliceY
330                 )
331
332         def _paint_label(self, painter, action, isSelected, x, y):
333                 text = action.text()
334                 fontMetrics = painter.fontMetrics()
335                 if text:
336                         textBoundingRect = fontMetrics.boundingRect(text)
337                 else:
338                         textBoundingRect = QtCore.QRect()
339                 textWidth = textBoundingRect.width()
340                 textHeight = textBoundingRect.height()
341
342                 icon = action.icon().pixmap(
343                         QtCore.QSize(self.ICON_SIZE_DEFAULT, self.ICON_SIZE_DEFAULT),
344                         QtGui.QIcon.Normal,
345                         QtGui.QIcon.On,
346                 )
347                 iconWidth = icon.width()
348                 iconHeight = icon.width()
349                 averageWidth = (iconWidth + textWidth)/2
350                 if not icon.isNull():
351                         iconRect = QtCore.QRect(
352                                 x - averageWidth,
353                                 y - iconHeight/2,
354                                 iconWidth,
355                                 iconHeight,
356                         )
357
358                         painter.drawPixmap(iconRect, icon)
359
360                 if text:
361                         if isSelected:
362                                 if action.isEnabled():
363                                         pen = self.palette.highlightedText()
364                                         brush = self.palette.highlight()
365                                 else:
366                                         pen = self.palette.mid()
367                                         brush = self.palette.background()
368                         else:
369                                 if action.isEnabled():
370                                         pen = self.palette.text()
371                                 else:
372                                         pen = self.palette.mid()
373                                 brush = self.palette.background()
374
375                         leftX = x - averageWidth + iconWidth
376                         topY = y + textHeight/2
377                         painter.setPen(pen.color())
378                         painter.setBrush(brush)
379                         painter.drawText(leftX, topY, text)
380
381         def _paint_center_background(self, painter, adjustmentRect, selectionIndex):
382                 dark = self.palette.dark().color()
383                 light = self.palette.light().color()
384                 if selectionIndex == PieFiling.SELECTION_CENTER and self._filing.center().isEnabled():
385                         background = self.palette.highlight().color()
386                 else:
387                         background = self.palette.background().color()
388
389                 innerRadius = self._cachedInnerRadius
390                 adjustmentCenterPos = adjustmentRect.center()
391                 innerRect = QtCore.QRect(
392                         adjustmentCenterPos.x() - innerRadius,
393                         adjustmentCenterPos.y() - innerRadius,
394                         innerRadius * 2 + 1,
395                         innerRadius * 2 + 1,
396                 )
397
398                 painter.setPen(QtCore.Qt.NoPen)
399                 painter.setBrush(background)
400                 painter.drawPie(innerRect, 0, 360 * 16)
401
402                 painter.setPen(QtGui.QPen(dark, 1))
403                 painter.setBrush(QtCore.Qt.NoBrush)
404                 painter.drawEllipse(innerRect)
405
406                 painter.setPen(QtGui.QPen(dark, 1))
407                 painter.setBrush(QtCore.Qt.NoBrush)
408                 painter.drawEllipse(adjustmentRect)
409
410                 r = QtCore.QRect(innerRect)
411                 innerCenter = r.center()
412                 innerRect.setLeft(innerCenter.x() + ((r.left() - innerCenter.x()) / 3) * 1)
413                 innerRect.setRight(innerCenter.x() + ((r.right() - innerCenter.x()) / 3) * 1)
414                 innerRect.setTop(innerCenter.y() + ((r.top() - innerCenter.y()) / 3) * 1)
415                 innerRect.setBottom(innerCenter.y() + ((r.bottom() - innerCenter.y()) / 3) * 1)
416
417         def _paint_center_foreground(self, painter, selectionIndex):
418                 centerPos = self._canvas.rect().center()
419                 pieX = centerPos.x()
420                 pieY = centerPos.y()
421
422                 x = pieX
423                 y = pieY
424
425                 self._paint_label(
426                         painter,
427                         self._filing.center().action(),
428                         selectionIndex == PieFiling.SELECTION_CENTER,
429                         x, y
430                 )
431
432
433 class QPieDisplay(QtGui.QWidget):
434
435         def __init__(self, filing, parent = None, flags = QtCore.Qt.Window):
436                 QtGui.QWidget.__init__(self, parent, flags)
437                 self._filing = filing
438                 self._artist = PieArtist(self._filing)
439                 self._selectionIndex = PieFiling.SELECTION_NONE
440
441         def popup(self, pos):
442                 self._update_selection(pos)
443                 self.show()
444
445         def sizeHint(self):
446                 return self._artist.pieSize()
447
448         @misc_utils.log_exception(_moduleLogger)
449         def showEvent(self, showEvent):
450                 mask = self._artist.show(self.palette())
451                 self.setMask(mask)
452
453                 QtGui.QWidget.showEvent(self, showEvent)
454
455         @misc_utils.log_exception(_moduleLogger)
456         def hideEvent(self, hideEvent):
457                 self._artist.hide()
458                 self._selectionIndex = PieFiling.SELECTION_NONE
459                 QtGui.QWidget.hideEvent(self, hideEvent)
460
461         @misc_utils.log_exception(_moduleLogger)
462         def paintEvent(self, paintEvent):
463                 canvas = self._artist.paint(self._selectionIndex)
464
465                 screen = QtGui.QPainter(self)
466                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
467
468                 QtGui.QWidget.paintEvent(self, paintEvent)
469
470         def selectAt(self, index):
471                 self._selectionIndex = index
472                 self.update()
473
474
475 class QPieButton(QtGui.QWidget):
476
477         activated = QtCore.pyqtSignal(int)
478         highlighted = QtCore.pyqtSignal(int)
479         canceled = QtCore.pyqtSignal()
480         aboutToShow = QtCore.pyqtSignal()
481         aboutToHide = QtCore.pyqtSignal()
482
483         BUTTON_RADIUS = 24
484
485         def __init__(self, buttonSlice, parent = None):
486                 QtGui.QWidget.__init__(self, parent)
487                 self._cachedCenterPosition = self.rect().center()
488
489                 self._filing = PieFiling()
490                 self._display = QPieDisplay(self._filing, None, QtCore.Qt.SplashScreen)
491                 self._selectionIndex = PieFiling.SELECTION_NONE
492
493                 self._buttonFiling = PieFiling()
494                 self._buttonFiling.set_center(buttonSlice)
495                 # @todo Figure out how to make the button auto-fill to content
496                 self._buttonFiling.setOuterRadius(self.BUTTON_RADIUS)
497                 self._buttonArtist = PieArtist(self._buttonFiling)
498                 self._poppedUp = False
499
500                 self._mousePosition = None
501                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
502
503         def insertItem(self, item, index = -1):
504                 self._filing.insertItem(item, index)
505
506         def removeItemAt(self, index):
507                 self._filing.removeItemAt(index)
508
509         def set_center(self, item):
510                 self._filing.set_center(item)
511
512         def set_button(self, item):
513                 self.update()
514
515         def clear(self):
516                 self._filing.clear()
517
518         def itemAt(self, index):
519                 return self._filing.itemAt(index)
520
521         def indexAt(self, point):
522                 return self._filing.indexAt(self._cachedCenterPosition, point)
523
524         def innerRadius(self):
525                 return self._filing.innerRadius()
526
527         def setInnerRadius(self, radius):
528                 self._filing.setInnerRadius(radius)
529
530         def outerRadius(self):
531                 return self._filing.outerRadius()
532
533         def setOuterRadius(self, radius):
534                 self._filing.setOuterRadius(radius)
535
536         def buttonRadius(self):
537                 return self._buttonFiling.outerRadius()
538
539         def setButtonRadius(self, radius):
540                 self._buttonFiling.setOuterRadius(radius)
541
542         def sizeHint(self):
543                 return self._buttonArtist.pieSize()
544
545         @misc_utils.log_exception(_moduleLogger)
546         def mousePressEvent(self, mouseEvent):
547                 self._popup_child(mouseEvent.globalPos())
548                 lastSelection = self._selectionIndex
549
550                 lastMousePos = mouseEvent.pos()
551                 self._mousePosition = lastMousePos
552                 self._update_selection(self._cachedCenterPosition)
553
554                 if lastSelection != self._selectionIndex:
555                         self.highlighted.emit(self._selectionIndex)
556                         self._display.selectAt(self._selectionIndex)
557
558         @misc_utils.log_exception(_moduleLogger)
559         def mouseMoveEvent(self, mouseEvent):
560                 lastSelection = self._selectionIndex
561
562                 lastMousePos = mouseEvent.pos()
563                 if self._mousePosition is None:
564                         # Absolute
565                         self._update_selection(lastMousePos)
566                 else:
567                         # Relative
568                         self._update_selection(self._cachedCenterPosition + (lastMousePos - self._mousePosition))
569
570                 if lastSelection != self._selectionIndex:
571                         self.highlighted.emit(self._selectionIndex)
572                         self._display.selectAt(self._selectionIndex)
573
574         @misc_utils.log_exception(_moduleLogger)
575         def mouseReleaseEvent(self, mouseEvent):
576                 lastSelection = self._selectionIndex
577
578                 lastMousePos = mouseEvent.pos()
579                 if self._mousePosition is None:
580                         # Absolute
581                         self._update_selection(lastMousePos)
582                 else:
583                         # Relative
584                         self._update_selection(self._cachedCenterPosition + (lastMousePos - self._mousePosition))
585                 self._mousePosition = None
586
587                 self._activate_at(self._selectionIndex)
588                 self._hide_child()
589
590         @misc_utils.log_exception(_moduleLogger)
591         def keyPressEvent(self, keyEvent):
592                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
593                         self._popup_child(QtGui.QCursor.pos())
594                         if self._selectionIndex != len(self._filing) - 1:
595                                 nextSelection = self._selectionIndex + 1
596                         else:
597                                 nextSelection = 0
598                         self._select_at(nextSelection)
599                         self._display.selectAt(self._selectionIndex)
600                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
601                         self._popup_child(QtGui.QCursor.pos())
602                         if 0 < self._selectionIndex:
603                                 nextSelection = self._selectionIndex - 1
604                         else:
605                                 nextSelection = len(self._filing) - 1
606                         self._select_at(nextSelection)
607                         self._display.selectAt(self._selectionIndex)
608                 elif keyEvent.key() in [QtCore.Qt.Key_Space]:
609                         self._popup_child(QtGui.QCursor.pos())
610                         self._select_at(PieFiling.SELECTION_CENTER)
611                         self._display.selectAt(self._selectionIndex)
612                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
613                         self._activate_at(self._selectionIndex)
614                         self._hide_child()
615                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
616                         self._activate_at(PieFiling.SELECTION_NONE)
617                         self._hide_child()
618                 else:
619                         QtGui.QWidget.keyPressEvent(self, keyEvent)
620
621         @misc_utils.log_exception(_moduleLogger)
622         def showEvent(self, showEvent):
623                 self._buttonArtist.show(self.palette())
624                 self._cachedCenterPosition = self.rect().center()
625
626                 QtGui.QWidget.showEvent(self, showEvent)
627
628         @misc_utils.log_exception(_moduleLogger)
629         def hideEvent(self, hideEvent):
630                 self._display.hide()
631                 self._select_at(PieFiling.SELECTION_NONE)
632                 QtGui.QWidget.hideEvent(self, hideEvent)
633
634         @misc_utils.log_exception(_moduleLogger)
635         def paintEvent(self, paintEvent):
636                 if self._poppedUp:
637                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_CENTER)
638                 else:
639                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_NONE)
640
641                 screen = QtGui.QPainter(self)
642                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
643
644                 QtGui.QWidget.paintEvent(self, paintEvent)
645
646         def __iter__(self):
647                 return iter(self._filing)
648
649         def __len__(self):
650                 return len(self._filing)
651
652         def _popup_child(self, position):
653                 self._poppedUp = True
654                 self.aboutToShow.emit()
655
656                 position = position - QtCore.QPoint(self._filing.outerRadius(), self._filing.outerRadius())
657                 self._display.move(position)
658                 self._display.show()
659
660                 self.update()
661
662         def _hide_child(self):
663                 self._poppedUp = False
664                 self.aboutToHide.emit()
665                 self._display.hide()
666                 self.update()
667
668         def _select_at(self, index):
669                 self._selectionIndex = index
670
671         def _update_selection(self, lastMousePos):
672                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
673                 if radius < self._filing.innerRadius():
674                         self._select_at(PieFiling.SELECTION_CENTER)
675                 elif radius <= self._filing.outerRadius():
676                         self._select_at(self.indexAt(lastMousePos))
677                 else:
678                         self._select_at(PieFiling.SELECTION_NONE)
679
680         def _activate_at(self, index):
681                 if index == PieFiling.SELECTION_NONE:
682                         self.canceled.emit()
683                         return
684                 elif index == PieFiling.SELECTION_CENTER:
685                         child = self._filing.center()
686                 else:
687                         child = self.itemAt(index)
688
689                 if child.action().isEnabled():
690                         child.action().trigger()
691                         self.activated.emit(index)
692                 else:
693                         self.canceled.emit()
694
695
696 class QPieMenu(QtGui.QWidget):
697
698         activated = QtCore.pyqtSignal(int)
699         highlighted = QtCore.pyqtSignal(int)
700         canceled = QtCore.pyqtSignal()
701         aboutToShow = QtCore.pyqtSignal()
702         aboutToHide = QtCore.pyqtSignal()
703
704         def __init__(self, parent = None):
705                 QtGui.QWidget.__init__(self, parent)
706                 self._cachedCenterPosition = self.rect().center()
707
708                 self._filing = PieFiling()
709                 self._artist = PieArtist(self._filing)
710                 self._selectionIndex = PieFiling.SELECTION_NONE
711
712                 self._mousePosition = ()
713                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
714
715         def popup(self, pos):
716                 self._update_selection(pos)
717                 self.show()
718
719         def insertItem(self, item, index = -1):
720                 self._filing.insertItem(item, index)
721                 self.update()
722
723         def removeItemAt(self, index):
724                 self._filing.removeItemAt(index)
725                 self.update()
726
727         def set_center(self, item):
728                 self._filing.set_center(item)
729                 self.update()
730
731         def clear(self):
732                 self._filing.clear()
733                 self.update()
734
735         def itemAt(self, index):
736                 return self._filing.itemAt(index)
737
738         def indexAt(self, point):
739                 return self._filing.indexAt(self._cachedCenterPosition, point)
740
741         def innerRadius(self):
742                 return self._filing.innerRadius()
743
744         def setInnerRadius(self, radius):
745                 self._filing.setInnerRadius(radius)
746                 self.update()
747
748         def outerRadius(self):
749                 return self._filing.outerRadius()
750
751         def setOuterRadius(self, radius):
752                 self._filing.setOuterRadius(radius)
753                 self.update()
754
755         def sizeHint(self):
756                 return self._artist.pieSize()
757
758         @misc_utils.log_exception(_moduleLogger)
759         def mousePressEvent(self, mouseEvent):
760                 lastSelection = self._selectionIndex
761
762                 lastMousePos = mouseEvent.pos()
763                 self._update_selection(lastMousePos)
764                 self._mousePosition = lastMousePos
765
766                 if lastSelection != self._selectionIndex:
767                         self.highlighted.emit(self._selectionIndex)
768                         self.update()
769
770         @misc_utils.log_exception(_moduleLogger)
771         def mouseMoveEvent(self, mouseEvent):
772                 lastSelection = self._selectionIndex
773
774                 lastMousePos = mouseEvent.pos()
775                 self._update_selection(lastMousePos)
776
777                 if lastSelection != self._selectionIndex:
778                         self.highlighted.emit(self._selectionIndex)
779                         self.update()
780
781         @misc_utils.log_exception(_moduleLogger)
782         def mouseReleaseEvent(self, mouseEvent):
783                 lastSelection = self._selectionIndex
784
785                 lastMousePos = mouseEvent.pos()
786                 self._update_selection(lastMousePos)
787                 self._mousePosition = ()
788
789                 self._activate_at(self._selectionIndex)
790                 self.update()
791
792         @misc_utils.log_exception(_moduleLogger)
793         def keyPressEvent(self, keyEvent):
794                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
795                         if self._selectionIndex != len(self._filing) - 1:
796                                 nextSelection = self._selectionIndex + 1
797                         else:
798                                 nextSelection = 0
799                         self._select_at(nextSelection)
800                         self.update()
801                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
802                         if 0 < self._selectionIndex:
803                                 nextSelection = self._selectionIndex - 1
804                         else:
805                                 nextSelection = len(self._filing) - 1
806                         self._select_at(nextSelection)
807                         self.update()
808                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
809                         self._activate_at(self._selectionIndex)
810                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
811                         self._activate_at(PieFiling.SELECTION_NONE)
812                 else:
813                         QtGui.QWidget.keyPressEvent(self, keyEvent)
814
815         @misc_utils.log_exception(_moduleLogger)
816         def showEvent(self, showEvent):
817                 self.aboutToShow.emit()
818                 self._cachedCenterPosition = self.rect().center()
819
820                 mask = self._artist.show(self.palette())
821                 self.setMask(mask)
822
823                 lastMousePos = self.mapFromGlobal(QtGui.QCursor.pos())
824                 self._update_selection(lastMousePos)
825
826                 QtGui.QWidget.showEvent(self, showEvent)
827
828         @misc_utils.log_exception(_moduleLogger)
829         def hideEvent(self, hideEvent):
830                 self._artist.hide()
831                 self._selectionIndex = PieFiling.SELECTION_NONE
832                 QtGui.QWidget.hideEvent(self, hideEvent)
833
834         @misc_utils.log_exception(_moduleLogger)
835         def paintEvent(self, paintEvent):
836                 canvas = self._artist.paint(self._selectionIndex)
837
838                 screen = QtGui.QPainter(self)
839                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
840
841                 QtGui.QWidget.paintEvent(self, paintEvent)
842
843         def __iter__(self):
844                 return iter(self._filing)
845
846         def __len__(self):
847                 return len(self._filing)
848
849         def _select_at(self, index):
850                 self._selectionIndex = index
851
852         def _update_selection(self, lastMousePos):
853                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
854                 if radius < self._filing.innerRadius():
855                         self._selectionIndex = PieFiling.SELECTION_CENTER
856                 elif radius <= self._filing.outerRadius():
857                         self._select_at(self.indexAt(lastMousePos))
858                 else:
859                         self._selectionIndex = PieFiling.SELECTION_NONE
860
861         def _activate_at(self, index):
862                 if index == PieFiling.SELECTION_NONE:
863                         self.canceled.emit()
864                         self.aboutToHide.emit()
865                         self.hide()
866                         return
867                 elif index == PieFiling.SELECTION_CENTER:
868                         child = self._filing.center()
869                 else:
870                         child = self.itemAt(index)
871
872                 if child.isEnabled():
873                         child.action().trigger()
874                         self.activated.emit(index)
875                 else:
876                         self.canceled.emit()
877                 self.aboutToHide.emit()
878                 self.hide()
879
880
881 def init_pies():
882         PieFiling.NULL_CENTER.setEnabled(False)
883
884
885 def _print(msg):
886         print msg
887
888
889 def _on_about_to_hide(app):
890         app.exit()
891
892
893 if __name__ == "__main__":
894         app = QtGui.QApplication([])
895         init_pies()
896
897         if False:
898                 pie = QPieMenu()
899                 pie.show()
900
901         if False:
902                 singleAction = QtGui.QAction(None)
903                 singleAction.setText("Boo")
904                 singleItem = QActionPieItem(singleAction)
905                 spie = QPieMenu()
906                 spie.insertItem(singleItem)
907                 spie.show()
908
909         if False:
910                 oneAction = QtGui.QAction(None)
911                 oneAction.setText("Chew")
912                 oneItem = QActionPieItem(oneAction)
913                 twoAction = QtGui.QAction(None)
914                 twoAction.setText("Foo")
915                 twoItem = QActionPieItem(twoAction)
916                 iconTextAction = QtGui.QAction(None)
917                 iconTextAction.setText("Icon")
918                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
919                 iconTextItem = QActionPieItem(iconTextAction)
920                 mpie = QPieMenu()
921                 mpie.insertItem(oneItem)
922                 mpie.insertItem(twoItem)
923                 mpie.insertItem(oneItem)
924                 mpie.insertItem(iconTextItem)
925                 mpie.show()
926
927         if True:
928                 oneAction = QtGui.QAction(None)
929                 oneAction.setText("Chew")
930                 oneAction.triggered.connect(lambda: _print("Chew"))
931                 oneItem = QActionPieItem(oneAction)
932                 twoAction = QtGui.QAction(None)
933                 twoAction.setText("Foo")
934                 twoAction.triggered.connect(lambda: _print("Foo"))
935                 twoItem = QActionPieItem(twoAction)
936                 iconAction = QtGui.QAction(None)
937                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
938                 iconAction.triggered.connect(lambda: _print("Icon"))
939                 iconItem = QActionPieItem(iconAction)
940                 iconTextAction = QtGui.QAction(None)
941                 iconTextAction.setText("Icon")
942                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
943                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
944                 iconTextItem = QActionPieItem(iconTextAction)
945                 mpie = QPieMenu()
946                 mpie.set_center(iconItem)
947                 mpie.insertItem(oneItem)
948                 mpie.insertItem(twoItem)
949                 mpie.insertItem(oneItem)
950                 mpie.insertItem(iconTextItem)
951                 mpie.show()
952                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
953                 mpie.canceled.connect(lambda: _print("Canceled"))
954
955         if False:
956                 oneAction = QtGui.QAction(None)
957                 oneAction.setText("Chew")
958                 oneAction.triggered.connect(lambda: _print("Chew"))
959                 oneItem = QActionPieItem(oneAction)
960                 twoAction = QtGui.QAction(None)
961                 twoAction.setText("Foo")
962                 twoAction.triggered.connect(lambda: _print("Foo"))
963                 twoItem = QActionPieItem(twoAction)
964                 iconAction = QtGui.QAction(None)
965                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
966                 iconAction.triggered.connect(lambda: _print("Icon"))
967                 iconItem = QActionPieItem(iconAction)
968                 iconTextAction = QtGui.QAction(None)
969                 iconTextAction.setText("Icon")
970                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
971                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
972                 iconTextItem = QActionPieItem(iconTextAction)
973                 pieFiling = PieFiling()
974                 pieFiling.set_center(iconItem)
975                 pieFiling.insertItem(oneItem)
976                 pieFiling.insertItem(twoItem)
977                 pieFiling.insertItem(oneItem)
978                 pieFiling.insertItem(iconTextItem)
979                 mpie = QPieDisplay(pieFiling)
980                 mpie.show()
981
982         if False:
983                 oneAction = QtGui.QAction(None)
984                 oneAction.setText("Chew")
985                 oneAction.triggered.connect(lambda: _print("Chew"))
986                 oneItem = QActionPieItem(oneAction)
987                 twoAction = QtGui.QAction(None)
988                 twoAction.setText("Foo")
989                 twoAction.triggered.connect(lambda: _print("Foo"))
990                 twoItem = QActionPieItem(twoAction)
991                 iconAction = QtGui.QAction(None)
992                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
993                 iconAction.triggered.connect(lambda: _print("Icon"))
994                 iconItem = QActionPieItem(iconAction)
995                 iconTextAction = QtGui.QAction(None)
996                 iconTextAction.setText("Icon")
997                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
998                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
999                 iconTextItem = QActionPieItem(iconTextAction)
1000                 mpie = QPieButton(iconItem)
1001                 mpie.set_center(iconItem)
1002                 mpie.insertItem(oneItem)
1003                 mpie.insertItem(twoItem)
1004                 mpie.insertItem(oneItem)
1005                 mpie.insertItem(iconTextItem)
1006                 mpie.show()
1007                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
1008                 mpie.canceled.connect(lambda: _print("Canceled"))
1009
1010         app.exec_()