Experimenting with borders for my pie buttons
[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         def __init__(self, buttonSlice, parent = None):
484                 QtGui.QWidget.__init__(self, parent)
485                 self._cachedCenterPosition = self.rect().center()
486
487                 self._filing = PieFiling()
488                 self._display = QPieDisplay(self._filing, None, QtCore.Qt.SplashScreen)
489                 self._selectionIndex = PieFiling.SELECTION_NONE
490
491                 self._buttonFiling = PieFiling()
492                 self._buttonFiling.set_center(buttonSlice)
493                 self._buttonArtist = PieArtist(self._buttonFiling)
494                 centerSize = self._buttonArtist.centerSize()
495                 self._buttonFiling.setOuterRadius(max(centerSize.width(), centerSize.height()))
496                 self._poppedUp = False
497
498                 self._mousePosition = None
499                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
500
501         def insertItem(self, item, index = -1):
502                 self._filing.insertItem(item, index)
503
504         def removeItemAt(self, index):
505                 self._filing.removeItemAt(index)
506
507         def set_center(self, item):
508                 self._filing.set_center(item)
509
510         def set_button(self, item):
511                 self.update()
512
513         def clear(self):
514                 self._filing.clear()
515
516         def itemAt(self, index):
517                 return self._filing.itemAt(index)
518
519         def indexAt(self, point):
520                 return self._filing.indexAt(self._cachedCenterPosition, point)
521
522         def innerRadius(self):
523                 return self._filing.innerRadius()
524
525         def setInnerRadius(self, radius):
526                 self._filing.setInnerRadius(radius)
527
528         def outerRadius(self):
529                 return self._filing.outerRadius()
530
531         def setOuterRadius(self, radius):
532                 self._filing.setOuterRadius(radius)
533
534         def sizeHint(self):
535                 return self._buttonArtist.pieSize()
536
537         @misc_utils.log_exception(_moduleLogger)
538         def mousePressEvent(self, mouseEvent):
539                 self._popup_child(mouseEvent.globalPos())
540                 lastSelection = self._selectionIndex
541
542                 lastMousePos = mouseEvent.pos()
543                 self._mousePosition = lastMousePos
544                 self._update_selection(self._cachedCenterPosition)
545
546                 if lastSelection != self._selectionIndex:
547                         self.highlighted.emit(self._selectionIndex)
548                         self._display.selectAt(self._selectionIndex)
549
550         @misc_utils.log_exception(_moduleLogger)
551         def mouseMoveEvent(self, mouseEvent):
552                 lastSelection = self._selectionIndex
553
554                 lastMousePos = mouseEvent.pos()
555                 if self._mousePosition is None:
556                         # Absolute
557                         self._update_selection(lastMousePos)
558                 else:
559                         # Relative
560                         self._update_selection(self._cachedCenterPosition + (lastMousePos - self._mousePosition))
561
562                 if lastSelection != self._selectionIndex:
563                         self.highlighted.emit(self._selectionIndex)
564                         self._display.selectAt(self._selectionIndex)
565
566         @misc_utils.log_exception(_moduleLogger)
567         def mouseReleaseEvent(self, mouseEvent):
568                 lastSelection = self._selectionIndex
569
570                 lastMousePos = mouseEvent.pos()
571                 if self._mousePosition is None:
572                         # Absolute
573                         self._update_selection(lastMousePos)
574                 else:
575                         # Relative
576                         self._update_selection(self._cachedCenterPosition + (lastMousePos - self._mousePosition))
577                 self._mousePosition = None
578
579                 self._activate_at(self._selectionIndex)
580                 self._hide_child()
581
582         @misc_utils.log_exception(_moduleLogger)
583         def keyPressEvent(self, keyEvent):
584                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
585                         self._popup_child(QtGui.QCursor.pos())
586                         if self._selectionIndex != len(self._filing) - 1:
587                                 nextSelection = self._selectionIndex + 1
588                         else:
589                                 nextSelection = 0
590                         self._select_at(nextSelection)
591                         self._display.selectAt(self._selectionIndex)
592                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
593                         self._popup_child(QtGui.QCursor.pos())
594                         if 0 < self._selectionIndex:
595                                 nextSelection = self._selectionIndex - 1
596                         else:
597                                 nextSelection = len(self._filing) - 1
598                         self._select_at(nextSelection)
599                         self._display.selectAt(self._selectionIndex)
600                 elif keyEvent.key() in [QtCore.Qt.Key_Space]:
601                         self._popup_child(QtGui.QCursor.pos())
602                         self._select_at(PieFiling.SELECTION_CENTER)
603                         self._display.selectAt(self._selectionIndex)
604                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
605                         self._activate_at(self._selectionIndex)
606                         self._hide_child()
607                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
608                         self._activate_at(PieFiling.SELECTION_NONE)
609                         self._hide_child()
610                 else:
611                         QtGui.QWidget.keyPressEvent(self, keyEvent)
612
613         @misc_utils.log_exception(_moduleLogger)
614         def showEvent(self, showEvent):
615                 self._buttonFiling.setOuterRadius(max(self.size().width(), self.size().height()) / 2)
616                 self._buttonArtist.show(self.palette())
617                 self._cachedCenterPosition = self.rect().center()
618
619                 QtGui.QWidget.showEvent(self, showEvent)
620
621         @misc_utils.log_exception(_moduleLogger)
622         def hideEvent(self, hideEvent):
623                 self._display.hide()
624                 self._select_at(PieFiling.SELECTION_NONE)
625                 QtGui.QWidget.hideEvent(self, hideEvent)
626
627         @misc_utils.log_exception(_moduleLogger)
628         def paintEvent(self, paintEvent):
629                 if self._poppedUp:
630                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_CENTER)
631                 else:
632                         canvas = self._buttonArtist.paint(PieFiling.SELECTION_NONE)
633
634                 screen = QtGui.QPainter(self)
635                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
636
637                 QtGui.QWidget.paintEvent(self, paintEvent)
638
639         def __iter__(self):
640                 return iter(self._filing)
641
642         def __len__(self):
643                 return len(self._filing)
644
645         def _popup_child(self, position):
646                 self._poppedUp = True
647                 self.aboutToShow.emit()
648
649                 position = position - QtCore.QPoint(self._filing.outerRadius(), self._filing.outerRadius())
650                 self._display.move(position)
651                 self._display.show()
652
653                 self.update()
654
655         def _hide_child(self):
656                 self._poppedUp = False
657                 self.aboutToHide.emit()
658                 self._display.hide()
659                 self.update()
660
661         def _select_at(self, index):
662                 self._selectionIndex = index
663
664         def _update_selection(self, lastMousePos):
665                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
666                 if radius < self._filing.innerRadius():
667                         self._select_at(PieFiling.SELECTION_CENTER)
668                 elif radius <= self._filing.outerRadius():
669                         self._select_at(self.indexAt(lastMousePos))
670                 else:
671                         self._select_at(PieFiling.SELECTION_NONE)
672
673         def _activate_at(self, index):
674                 if index == PieFiling.SELECTION_NONE:
675                         self.canceled.emit()
676                         return
677                 elif index == PieFiling.SELECTION_CENTER:
678                         child = self._filing.center()
679                 else:
680                         child = self.itemAt(index)
681
682                 if child.action().isEnabled():
683                         child.action().trigger()
684                         self.activated.emit(index)
685                 else:
686                         self.canceled.emit()
687
688
689 class QPieMenu(QtGui.QWidget):
690
691         activated = QtCore.pyqtSignal(int)
692         highlighted = QtCore.pyqtSignal(int)
693         canceled = QtCore.pyqtSignal()
694         aboutToShow = QtCore.pyqtSignal()
695         aboutToHide = QtCore.pyqtSignal()
696
697         def __init__(self, parent = None):
698                 QtGui.QWidget.__init__(self, parent)
699                 self._cachedCenterPosition = self.rect().center()
700
701                 self._filing = PieFiling()
702                 self._artist = PieArtist(self._filing)
703                 self._selectionIndex = PieFiling.SELECTION_NONE
704
705                 self._mousePosition = ()
706                 self.setFocusPolicy(QtCore.Qt.StrongFocus)
707
708         def popup(self, pos):
709                 self._update_selection(pos)
710                 self.show()
711
712         def insertItem(self, item, index = -1):
713                 self._filing.insertItem(item, index)
714                 self.update()
715
716         def removeItemAt(self, index):
717                 self._filing.removeItemAt(index)
718                 self.update()
719
720         def set_center(self, item):
721                 self._filing.set_center(item)
722                 self.update()
723
724         def clear(self):
725                 self._filing.clear()
726                 self.update()
727
728         def itemAt(self, index):
729                 return self._filing.itemAt(index)
730
731         def indexAt(self, point):
732                 return self._filing.indexAt(self._cachedCenterPosition, point)
733
734         def innerRadius(self):
735                 return self._filing.innerRadius()
736
737         def setInnerRadius(self, radius):
738                 self._filing.setInnerRadius(radius)
739                 self.update()
740
741         def outerRadius(self):
742                 return self._filing.outerRadius()
743
744         def setOuterRadius(self, radius):
745                 self._filing.setOuterRadius(radius)
746                 self.update()
747
748         def sizeHint(self):
749                 return self._artist.pieSize()
750
751         @misc_utils.log_exception(_moduleLogger)
752         def mousePressEvent(self, mouseEvent):
753                 lastSelection = self._selectionIndex
754
755                 lastMousePos = mouseEvent.pos()
756                 self._update_selection(lastMousePos)
757                 self._mousePosition = lastMousePos
758
759                 if lastSelection != self._selectionIndex:
760                         self.highlighted.emit(self._selectionIndex)
761                         self.update()
762
763         @misc_utils.log_exception(_moduleLogger)
764         def mouseMoveEvent(self, mouseEvent):
765                 lastSelection = self._selectionIndex
766
767                 lastMousePos = mouseEvent.pos()
768                 self._update_selection(lastMousePos)
769
770                 if lastSelection != self._selectionIndex:
771                         self.highlighted.emit(self._selectionIndex)
772                         self.update()
773
774         @misc_utils.log_exception(_moduleLogger)
775         def mouseReleaseEvent(self, mouseEvent):
776                 lastSelection = self._selectionIndex
777
778                 lastMousePos = mouseEvent.pos()
779                 self._update_selection(lastMousePos)
780                 self._mousePosition = ()
781
782                 self._activate_at(self._selectionIndex)
783                 self.update()
784
785         @misc_utils.log_exception(_moduleLogger)
786         def keyPressEvent(self, keyEvent):
787                 if keyEvent.key() in [QtCore.Qt.Key_Right, QtCore.Qt.Key_Down, QtCore.Qt.Key_Tab]:
788                         if self._selectionIndex != len(self._filing) - 1:
789                                 nextSelection = self._selectionIndex + 1
790                         else:
791                                 nextSelection = 0
792                         self._select_at(nextSelection)
793                         self.update()
794                 elif keyEvent.key() in [QtCore.Qt.Key_Left, QtCore.Qt.Key_Up, QtCore.Qt.Key_Backtab]:
795                         if 0 < self._selectionIndex:
796                                 nextSelection = self._selectionIndex - 1
797                         else:
798                                 nextSelection = len(self._filing) - 1
799                         self._select_at(nextSelection)
800                         self.update()
801                 elif keyEvent.key() in [QtCore.Qt.Key_Return, QtCore.Qt.Key_Enter, QtCore.Qt.Key_Space]:
802                         self._activate_at(self._selectionIndex)
803                 elif keyEvent.key() in [QtCore.Qt.Key_Escape, QtCore.Qt.Key_Backspace]:
804                         self._activate_at(PieFiling.SELECTION_NONE)
805                 else:
806                         QtGui.QWidget.keyPressEvent(self, keyEvent)
807
808         @misc_utils.log_exception(_moduleLogger)
809         def showEvent(self, showEvent):
810                 self.aboutToShow.emit()
811                 self._cachedCenterPosition = self.rect().center()
812
813                 mask = self._artist.show(self.palette())
814                 self.setMask(mask)
815
816                 lastMousePos = self.mapFromGlobal(QtGui.QCursor.pos())
817                 self._update_selection(lastMousePos)
818
819                 QtGui.QWidget.showEvent(self, showEvent)
820
821         @misc_utils.log_exception(_moduleLogger)
822         def hideEvent(self, hideEvent):
823                 self._artist.hide()
824                 self._selectionIndex = PieFiling.SELECTION_NONE
825                 QtGui.QWidget.hideEvent(self, hideEvent)
826
827         @misc_utils.log_exception(_moduleLogger)
828         def paintEvent(self, paintEvent):
829                 canvas = self._artist.paint(self._selectionIndex)
830
831                 screen = QtGui.QPainter(self)
832                 screen.drawPixmap(QtCore.QPoint(0, 0), canvas)
833
834                 QtGui.QWidget.paintEvent(self, paintEvent)
835
836         def __iter__(self):
837                 return iter(self._filing)
838
839         def __len__(self):
840                 return len(self._filing)
841
842         def _select_at(self, index):
843                 self._selectionIndex = index
844
845         def _update_selection(self, lastMousePos):
846                 radius = _radius_at(self._cachedCenterPosition, lastMousePos)
847                 if radius < self._filing.innerRadius():
848                         self._selectionIndex = PieFiling.SELECTION_CENTER
849                 elif radius <= self._filing.outerRadius():
850                         self._select_at(self.indexAt(lastMousePos))
851                 else:
852                         self._selectionIndex = PieFiling.SELECTION_NONE
853
854         def _activate_at(self, index):
855                 if index == PieFiling.SELECTION_NONE:
856                         self.canceled.emit()
857                         self.aboutToHide.emit()
858                         self.hide()
859                         return
860                 elif index == PieFiling.SELECTION_CENTER:
861                         child = self._filing.center()
862                 else:
863                         child = self.itemAt(index)
864
865                 if child.isEnabled():
866                         child.action().trigger()
867                         self.activated.emit(index)
868                 else:
869                         self.canceled.emit()
870                 self.aboutToHide.emit()
871                 self.hide()
872
873
874 def init_pies():
875         PieFiling.NULL_CENTER.setEnabled(False)
876
877
878 def _print(msg):
879         print msg
880
881
882 def _on_about_to_hide(app):
883         app.exit()
884
885
886 if __name__ == "__main__":
887         app = QtGui.QApplication([])
888         init_pies()
889
890         if False:
891                 pie = QPieMenu()
892                 pie.show()
893
894         if False:
895                 singleAction = QtGui.QAction(None)
896                 singleAction.setText("Boo")
897                 singleItem = QActionPieItem(singleAction)
898                 spie = QPieMenu()
899                 spie.insertItem(singleItem)
900                 spie.show()
901
902         if False:
903                 oneAction = QtGui.QAction(None)
904                 oneAction.setText("Chew")
905                 oneItem = QActionPieItem(oneAction)
906                 twoAction = QtGui.QAction(None)
907                 twoAction.setText("Foo")
908                 twoItem = QActionPieItem(twoAction)
909                 iconTextAction = QtGui.QAction(None)
910                 iconTextAction.setText("Icon")
911                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
912                 iconTextItem = QActionPieItem(iconTextAction)
913                 mpie = QPieMenu()
914                 mpie.insertItem(oneItem)
915                 mpie.insertItem(twoItem)
916                 mpie.insertItem(oneItem)
917                 mpie.insertItem(iconTextItem)
918                 mpie.show()
919
920         if True:
921                 oneAction = QtGui.QAction(None)
922                 oneAction.setText("Chew")
923                 oneAction.triggered.connect(lambda: _print("Chew"))
924                 oneItem = QActionPieItem(oneAction)
925                 twoAction = QtGui.QAction(None)
926                 twoAction.setText("Foo")
927                 twoAction.triggered.connect(lambda: _print("Foo"))
928                 twoItem = QActionPieItem(twoAction)
929                 iconAction = QtGui.QAction(None)
930                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
931                 iconAction.triggered.connect(lambda: _print("Icon"))
932                 iconItem = QActionPieItem(iconAction)
933                 iconTextAction = QtGui.QAction(None)
934                 iconTextAction.setText("Icon")
935                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
936                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
937                 iconTextItem = QActionPieItem(iconTextAction)
938                 mpie = QPieMenu()
939                 mpie.set_center(iconItem)
940                 mpie.insertItem(oneItem)
941                 mpie.insertItem(twoItem)
942                 mpie.insertItem(oneItem)
943                 mpie.insertItem(iconTextItem)
944                 mpie.show()
945                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
946                 mpie.canceled.connect(lambda: _print("Canceled"))
947
948         if False:
949                 oneAction = QtGui.QAction(None)
950                 oneAction.setText("Chew")
951                 oneAction.triggered.connect(lambda: _print("Chew"))
952                 oneItem = QActionPieItem(oneAction)
953                 twoAction = QtGui.QAction(None)
954                 twoAction.setText("Foo")
955                 twoAction.triggered.connect(lambda: _print("Foo"))
956                 twoItem = QActionPieItem(twoAction)
957                 iconAction = QtGui.QAction(None)
958                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
959                 iconAction.triggered.connect(lambda: _print("Icon"))
960                 iconItem = QActionPieItem(iconAction)
961                 iconTextAction = QtGui.QAction(None)
962                 iconTextAction.setText("Icon")
963                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
964                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
965                 iconTextItem = QActionPieItem(iconTextAction)
966                 pieFiling = PieFiling()
967                 pieFiling.set_center(iconItem)
968                 pieFiling.insertItem(oneItem)
969                 pieFiling.insertItem(twoItem)
970                 pieFiling.insertItem(oneItem)
971                 pieFiling.insertItem(iconTextItem)
972                 mpie = QPieDisplay(pieFiling)
973                 mpie.show()
974
975         if False:
976                 oneAction = QtGui.QAction(None)
977                 oneAction.setText("Chew")
978                 oneAction.triggered.connect(lambda: _print("Chew"))
979                 oneItem = QActionPieItem(oneAction)
980                 twoAction = QtGui.QAction(None)
981                 twoAction.setText("Foo")
982                 twoAction.triggered.connect(lambda: _print("Foo"))
983                 twoItem = QActionPieItem(twoAction)
984                 iconAction = QtGui.QAction(None)
985                 iconAction.setIcon(QtGui.QIcon.fromTheme("gtk-open"))
986                 iconAction.triggered.connect(lambda: _print("Icon"))
987                 iconItem = QActionPieItem(iconAction)
988                 iconTextAction = QtGui.QAction(None)
989                 iconTextAction.setText("Icon")
990                 iconTextAction.setIcon(QtGui.QIcon.fromTheme("gtk-close"))
991                 iconTextAction.triggered.connect(lambda: _print("Icon and text"))
992                 iconTextItem = QActionPieItem(iconTextAction)
993                 mpie = QPieButton(iconItem)
994                 mpie.set_center(iconItem)
995                 mpie.insertItem(oneItem)
996                 mpie.insertItem(twoItem)
997                 mpie.insertItem(oneItem)
998                 mpie.insertItem(iconTextItem)
999                 mpie.show()
1000                 mpie.aboutToHide.connect(lambda: _on_about_to_hide(app))
1001                 mpie.canceled.connect(lambda: _print("Canceled"))
1002
1003         app.exec_()