File: tooltip.py

package info (click to toggle)
taskcoach 1.4.1-4
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 32,496 kB
  • ctags: 17,810
  • sloc: python: 72,170; makefile: 254; ansic: 120; xml: 29; sh: 16
file content (284 lines) | stat: -rw-r--r-- 10,201 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
'''
Task Coach - Your friendly task manager
Copyright (C) 2004-2014 Task Coach developers <developers@taskcoach.org>

Task Coach is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Task Coach is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
'''

from taskcoachlib import operating_system
import wx
import textwrap


class ToolTipMixin(object):
    """Subclass this and override OnBeforeShowToolTip to provide
    dynamic tooltip over a control."""

    def __init__(self, *args, **kwargs):
        self.__enabled = kwargs.pop('tooltipsEnabled', True)
        super(ToolTipMixin, self).__init__(*args, **kwargs)

        self.__timer = wx.Timer(self, wx.NewId())

        self.__tip = None
        self.__position = (0, 0)
        self.__text = None
        self.__frozen = True

        self.GetMainWindow().Bind(wx.EVT_MOTION, self.__OnMotion)
        self.GetMainWindow().Bind(wx.EVT_LEAVE_WINDOW, self.__OnLeave)
        self.Bind(wx.EVT_TIMER, self.__OnTimer, id=self.__timer.GetId())        

    def SetToolTipsEnabled(self, enabled):
        self.__enabled = enabled

    def PopupMenu(self, menu):
        self.__frozen = False
        super(ToolTipMixin, self).PopupMenu(menu)
        self.__frozen = True

    def ShowTip(self, x, y):
        # Ensure we're not too big (in the Y direction anyway) for the
        # desktop display area. This doesn't work on Linux because
        # ClientDisplayRect() returns the whole display size, not
        # taking the taskbar into account...

        if self.__frozen:
            theDisplay = wx.Display(wx.Display.GetFromPoint(wx.Point(x, y)))
            displayX, displayY, displayWidth, displayHeight = theDisplay.GetClientArea()
            tipWidth, tipHeight = self.__tip.GetSizeTuple()

            if tipHeight > displayHeight:
                # Too big. Take as much space as possible.
                y = 5
                tipHeight = displayHeight - 10
            elif y + tipHeight > displayY + displayHeight:
                # Adjust y so that the whole tip is visible.
                y = displayY + displayHeight - tipHeight - 5

            if tipWidth > displayWidth:
                x = 5
            elif x + tipWidth > displayX + displayWidth:
                x = displayX + displayWidth - tipWidth - 5

            self.__tip.Show(x, y, tipWidth, tipHeight)

    def DoShowTip(self, x, y, tip):
        self.__tip = tip
        self.ShowTip(x, y)

    def HideTip(self):
        if self.__tip:
            self.__tip.Hide()

    def OnBeforeShowToolTip(self, x, y):
        """Should return a wx.Frame instance that will be displayed as
        the tooltip, or None."""
        raise NotImplementedError  # pragma: no cover

    def __OnMotion(self, event):
        x, y = event.GetPosition()

        self.__timer.Stop()

        if self.__tip is not None:
            self.HideTip()
            self.__tip = None

        if self.__enabled:
            newTip = self.OnBeforeShowToolTip(x, y)
            if newTip is not None:
                self.__tip = newTip
                self.__tip.Bind(wx.EVT_MOTION, self.__OnTipMotion)
                self.__position = (x + 20, y + 10)
                self.__timer.Start(200, True)

        event.Skip()

    def __OnTipMotion(self, event):  # pylint: disable=W0613
        self.HideTip()

    def __OnLeave(self, event):
        self.__timer.Stop()

        if self.__tip is not None:
            self.HideTip()
            self.__tip = None

        event.Skip()

    def __OnTimer(self, event):  # pylint: disable=W0613
        self.ShowTip(*self.GetMainWindow().ClientToScreenXY(*self.__position))


if operating_system.isWindows():
    class ToolTipBase(wx.MiniFrame):
        def __init__(self, parent):
            style = wx.FRAME_NO_TASKBAR | wx.FRAME_FLOAT_ON_PARENT | wx.NO_BORDER
            super(ToolTipBase, self).__init__(parent, wx.ID_ANY, 'Tooltip',
                                              style=style)

        def Show(self, x, y, w, h):  # pylint: disable=W0221
            self.SetDimensions(x, y, w, h)
            super(ToolTipBase, self).Show()

elif operating_system.isMac():
    class ToolTipBase(wx.Frame):
        def __init__(self, parent):  # pylint: disable=E1003
            style = wx.FRAME_NO_TASKBAR | wx.FRAME_FLOAT_ON_PARENT | wx.NO_BORDER
            super(ToolTipBase, self).__init__(parent, wx.ID_ANY, 'ToolTip',
                                              style=style)

            # There are some subtleties on Mac regarding multi-monitor
            # displays...

            self.__maxWidth, self.__maxHeight = 0, 0
            for index in xrange(wx.Display.GetCount()):
                x, y, width, height = wx.Display(index).GetGeometry()
                self.__maxWidth = max(self.__maxWidth, x + width)
                self.__maxHeight = max(self.__maxHeight, y + height)

            self.MoveXY(self.__maxWidth, self.__maxHeight)
            super(ToolTipBase, self).Show()

        def Show(self, x, y, width, height):  # pylint: disable=W0221
            self.SetDimensions(x, y, width, height)

        def Hide(self):  # pylint: disable=W0221
            self.MoveXY(self.__maxWidth, self.__maxHeight)

else:
    class ToolTipBase(wx.PopupWindow):
        def Show(self, x, y, width, height):  # pylint: disable=E1003,W0221
            self.SetDimensions(x, y, width, height)
            super(ToolTipBase, self).Show()


class SimpleToolTip(ToolTipBase):
    def __init__(self, parent):
        super(SimpleToolTip, self).__init__(parent)
        self.data = []
        self.Bind(wx.EVT_PAINT, self.OnPaint)

    def SetData(self, data):
        self.data = self._wrapLongLines(data)
        self.SetSize(self._calculateSize())
        self.Refresh()  # Needed on Mac OS X
        
    def _wrapLongLines(self, data):
        wrappedData = []
        wrapper = textwrap.TextWrapper(width=78)
        for icon, lines in data:
            wrappedLines = []
            for line in lines:
                wrappedLines.extend(wrapper.fill(line).split('\n'))
            wrappedData.append((icon, wrappedLines))
        return wrappedData
        
    def _calculateSize(self):
        dc = wx.ClientDC(self)
        self._setFontBrushAndPen(dc)
        width, height = 0, 0
        for sectionIndex in range(len(self.data)):
            sectionWidth, sectionHeight = self._calculateSectionSize(dc, sectionIndex)
            width = max(width, sectionWidth)
            height += sectionHeight
        return wx.Size(width + 6, height + 6)
    
    def _calculateSectionSize(self, dc, sectionIndex):
        icon, lines = self.data[sectionIndex]
        sectionWidth, sectionHeight = 0, 0
        for line in lines:
            lineWidth, lineHeight = self._calculateLineSize(dc, line)
            sectionHeight += lineHeight + 1
            sectionWidth = max(sectionWidth, lineWidth)
        if 0 < sectionIndex < len(self.data) - 1:
            sectionHeight += 3  # Horizontal space between sections
        if icon:
            sectionWidth += 24  # Reserve width for icon(s)
        return sectionWidth, sectionHeight
    
    def _calculateLineSize(self, dc, line):
        return dc.GetTextExtent(line)

    def OnPaint(self, event):  # pylint: disable=W0613
        dc = wx.PaintDC(self)
        dc.BeginDrawing()
        try:
            self._setFontBrushAndPen(dc)
            self._drawBorder(dc)
            self._drawSections(dc)
        finally:
            dc.EndDrawing()
            
    def _setFontBrushAndPen(self, dc):
        font = wx.SystemSettings_GetFont(wx.SYS_DEFAULT_GUI_FONT)
        textColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_INFOTEXT)
        backgroundColour = wx.SystemSettings_GetColour(wx.SYS_COLOUR_INFOBK)
        dc.SetFont(font)
        dc.SetTextForeground(textColour)
        dc.SetBrush(wx.Brush(backgroundColour))
        dc.SetPen(wx.Pen(textColour))
        
    def _drawBorder(self, dc):
        width, height = self.GetClientSizeTuple()
        dc.DrawRectangle(0, 0, width, height)
        
    def _drawSections(self, dc):
        y = 3
        for sectionIndex in range(len(self.data)):
            y = self._drawSection(dc, y, sectionIndex)
                    
    def _drawSection(self, dc, y, sectionIndex):
        icon, lines = self.data[sectionIndex]
        if not lines:
            return y
        x = 3
        if sectionIndex != 0:
            y = self._drawSectionSeparator(dc, x, y)
        if icon:
            x = self._drawIcon(dc, icon, x, y)
        topOfSection = y
        bottomOfSection = self._drawTextLines(dc, lines, x, y)
        if icon:
            self._drawIconSeparator(dc, x - 2, topOfSection, bottomOfSection)
        return bottomOfSection
    
    def _drawSectionSeparator(self, dc, x, y):
        y += 1
        width = self.GetClientSizeTuple()[0]
        dc.DrawLine(x, y, width - x, y)
        return y + 2
        
    def _drawIcon(self, dc, icon, x, y):
        bitmap = wx.ArtProvider.GetBitmap(icon, wx.ART_FRAME_ICON, (16, 16))
        dc.DrawBitmap(bitmap, x, y, True)
        return 23  # New x
        
    def _drawTextLines(self, dc, textLines, x, y):
        for textLine in textLines:
            y = self._drawTextLine(dc, textLine, x, y)
        return y
        
    def _drawTextLine(self, dc, textLine, x, y):
        try:
            dc.DrawText(textLine, x, y)
        except:
            raise RuntimeError('Could not draw text %s' % repr(textLine))
        textHeight = dc.GetTextExtent(textLine)[1]
        return y + textHeight + 1
    
    def _drawIconSeparator(self, dc, x, top, bottom):
        ''' Draw a vertical line between the icon and the text. '''
        dc.DrawLine(x, top, x, bottom)