File: helper.py

package info (click to toggle)
python-traitsui 8.0.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 18,232 kB
  • sloc: python: 58,982; makefile: 113
file content (292 lines) | stat: -rw-r--r-- 9,347 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
285
286
287
288
289
290
291
292
# (C) Copyright 2008-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

# ------------------------------------------------------------------------------
# Copyright (c) 2007, Riverbank Computing Limited
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD license.
# However, when used with the GPL version of PyQt the additional terms
# described in the PyQt GPL exception also apply

#
# Author: Riverbank Computing Limited
# ------------------------------------------------------------------------------

""" Defines helper functions and classes used to define PyQt-based trait
    editors and trait editor factories.
"""

import os.path

from pyface.api import SystemMetrics
from pyface.qt import QtCore, QtGui, is_qt5, is_pyqt, qt_api
from pyface.ui_traits import convert_image
from traits.api import Enum, CTrait, BaseTraitHandler, TraitError

from traitsui.ui_traits import SequenceTypes


#: Layout orientation for a control and its associated editor
Orientation = Enum("horizontal", "vertical")

#: Dock-related stubs.
DockStyle = Enum("horizontal", "vertical", "tab", "fixed")


def pixmap_cache(name, path=None):
    """Convert an image file name to a cached QPixmap

    Returns the QPixmap corresponding to a filename. If the filename does not
    contain a path component, 'path' is used (or if 'path' is not specified,
    the local 'images' directory is used).
    """
    if name[:1] == "@":
        image = convert_image(name.replace(" ", "_").lower())
        if image is not None:
            return image.create_image()

    name_path, name = os.path.split(name)
    name = name.replace(" ", "_").lower()
    if name_path:
        filename = os.path.join(name_path, name)
    else:
        if path is None:
            filename = os.path.join(os.path.dirname(__file__), "images", name)
        else:
            filename = os.path.join(path, name)
    filename = os.path.abspath(filename)

    if is_qt5:
        pm = QtGui.QPixmapCache.find(filename)
        if pm is None:
            pm = QtGui.QPixmap(filename)
            QtGui.QPixmapCache.insert(filename, pm)
    else:
        pm = QtGui.QPixmap()
        if not QtGui.QPixmapCache.find(filename, pm):
            pm.load(filename)
            QtGui.QPixmapCache.insert(filename, pm)
    return pm


def position_window(window, width=None, height=None, parent=None):
    """Positions a window on the screen with a specified width and height so
    that the window completely fits on the screen if possible.
    """
    # Get the available geometry of the screen containing the window.
    system_metrics = SystemMetrics()
    screen_dx = system_metrics.screen_width
    screen_dy = system_metrics.screen_height

    # Use the frame geometry even though it is very unlikely that the X11 frame
    # exists at this point.
    fgeom = window.frameGeometry()
    width = width or fgeom.width()
    height = height or fgeom.height()

    if parent is None:
        parent = window._parent

    if parent is None:
        # Center the popup on the screen.
        window.move((screen_dx - width) // 2, (screen_dy - height) // 2)
        return

    # Calculate the desired size of the popup control:
    if isinstance(parent, QtGui.QWidget):
        gpos = parent.mapToGlobal(QtCore.QPoint())
        x = gpos.x()
        y = gpos.y()
        cdx = parent.width()
        cdy = parent.height()

        # Get the frame height of the parent and assume that the window will
        # have a similar frame.  Note that we would really like the height of
        # just the top of the frame.
        pw = parent.window()
        fheight = pw.frameGeometry().height() - pw.height()
    else:
        # Special case of parent being a screen position and size tuple (used
        # to pop-up a dialog for a table cell):
        x, y, cdx, cdy = parent

        fheight = 0

    x -= (width - cdx) / 2
    y += cdy + fheight

    # Position the window (making sure it will fit on the screen).
    window.move(
        max(0, min(x, screen_dx - width)), max(0, min(y, screen_dy - height))
    )


def restore_window(ui):
    """Restores the user preference items for a specified UI."""
    prefs = ui.restore_prefs()
    if prefs is not None:
        ui.control.setGeometry(*prefs)


def save_window(ui):
    """Saves the user preference items for a specified UI."""
    geom = ui.control.geometry()
    ui.save_prefs((geom.x(), geom.y(), geom.width(), geom.height()))


class IconButton(QtGui.QPushButton):
    """The IconButton class is a push button that contains a small image or a
    standard icon provided by the current style.
    """

    def __init__(self, icon, slot):
        """Initialise the button.  icon is either the name of an image file or
        one of the QtGui.QStyle.SP_* values.
        """
        QtGui.QPushButton.__init__(self)

        # Get the current style.
        sty = QtGui.QApplication.instance().style()

        # Get the minimum icon size to use.
        ico_sz = sty.pixelMetric(QtGui.QStyle.PixelMetric.PM_ButtonIconSize)

        if isinstance(icon, str):
            pm = pixmap_cache(icon)

            # Increase the icon size to accomodate the image if needed.
            pm_width = pm.width()
            pm_height = pm.height()

            if ico_sz < pm_width:
                ico_sz = pm_width

            if ico_sz < pm_height:
                ico_sz = pm_height

            ico = QtGui.QIcon(pm)
        else:
            ico = sty.standardIcon(icon)

        # Configure the button.
        self.setIcon(ico)
        self.setFlat(True)
        self.setFocusPolicy(QtCore.Qt.FocusPolicy.NoFocus)

        self.clicked.connect(slot)

    def sizeHint(self):
        """Reimplement sizeHint to return a recommended button size based on
        the size of the icon.

        Returns
        -------
        size : QtCore.QSize
        """
        self.ensurePolished()

        # We want the button to have a size similar to the icon.
        # Using the size computed for a tool button gives a desirable size.
        option = QtGui.QStyleOptionButton()
        self.initStyleOption(option)
        size = self.style().sizeFromContents(
            QtGui.QStyle.ContentsType.CT_ToolButton, option, option.iconSize
        )
        return size


# ------------------------------------------------------------------------
# Text Rendering helpers
# ------------------------------------------------------------------------


def wrap_text_with_elision(text, font, width, height):
    """Wrap paragraphs to fit inside a given size, eliding if too long.

    Parameters
    ----------
    text : unicode
        The text to wrap.
    font : QFont instance
        The font the text will be rendered in.
    width : int
        The width of the box the text will display in.
    height : int
        The height of the box the text will display in.

    Returns
    -------
    lines : list of unicode
        The lines of text to display, split
    """
    # XXX having an LRU cache on this might be useful

    font_metrics = QtGui.QFontMetrics(font)
    line_spacing = font_metrics.lineSpacing()
    y_offset = 0

    lines = []
    for paragraph in text.splitlines():
        line_start = 0
        text_layout = QtGui.QTextLayout(paragraph, font)
        text_layout.beginLayout()
        while y_offset + line_spacing <= height:
            line = text_layout.createLine()
            if not line.isValid():
                break
            line.setLineWidth(int(width))
            line_start = line.textStart()
            line_end = line_start + line.textLength()
            line_text = paragraph[line_start:line_end].rstrip()
            lines.append(line_text)
            y_offset += line_spacing
        text_layout.endLayout()
        if y_offset + line_spacing > height:
            break
    if lines and y_offset + line_spacing > height:
        # elide last line as we ran out of room
        last_line = paragraph[line_start:]
        lines[-1] = font_metrics.elidedText(
            last_line, QtCore.Qt.TextElideMode.ElideRight, width
        )

    return lines


# ------------------------------------------------------------------------
# Object lifetime helpers
# ------------------------------------------------------------------------

def qobject_is_valid(qobject):
    """Return whether the wrapped Qt object is still valid.

    Parameters
    ----------
    qobject : QObject instance
        The wrapped Qt QObject to inspect.

    Returns
    -------
    valid : bool
        Whether or not the underlying C++ object still exists.
    """
    if is_pyqt:
        from sip import isdeleted
        return not isdeleted(qobject)
    elif qt_api == 'pyside2':
        from shiboken2 import isValid
        return isValid(qobject)
    elif qt_api == 'pyside6':
        from shiboken6 import isValid
        return isValid(qobject)
    else:
        # unknown wrapper
        raise RuntimeError("Unknown Qt API {qt_api}")