summaryrefslogtreecommitdiff
path: root/silx/gui/widgets/ColormapNameComboBox.py
blob: fa8faf15bec05707f300013d78c50c61f0145770 (plain)
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2004-2018 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/
"""A QComboBox to display prefered colormaps
"""

from __future__ import division

__authors__ = ["V.A. Sole", "T. Vincent", "H. Payno"]
__license__ = "MIT"
__date__ = "27/11/2018"


import logging
import numpy

from .. import qt
from .. import colors as colors_mdl

_logger = logging.getLogger(__name__)


_colormapIconPreview = {}


class ColormapNameComboBox(qt.QComboBox):
    def __init__(self, parent=None):
        qt.QComboBox.__init__(self, parent)
        self.__initItems()

    LUT_NAME = qt.Qt.UserRole + 1
    LUT_COLORS = qt.Qt.UserRole + 2

    def __initItems(self):
        for colormapName in colors_mdl.preferredColormaps():
            index = self.count()
            self.addItem(str.title(colormapName))
            self.setItemIcon(index, self.getIconPreview(name=colormapName))
            self.setItemData(index, colormapName, role=self.LUT_NAME)

    def getIconPreview(self, name=None, colors=None):
        """Return an icon preview from a LUT name.

        This icons are cached into a global structure.

        :param str name: Name of the LUT
        :param numpy.ndarray colors: Colors identify the LUT
        :rtype: qt.QIcon
        """
        if name is not None:
            iconKey = name
        else:
            iconKey = tuple(colors)
        icon = _colormapIconPreview.get(iconKey, None)
        if icon is None:
            icon = self.createIconPreview(name, colors)
            _colormapIconPreview[iconKey] = icon
        return icon

    def createIconPreview(self, name=None, colors=None):
        """Create and return an icon preview from a LUT name.

        This icons are cached into a global structure.

        :param str name: Name of the LUT
        :param numpy.ndarray colors: Colors identify the LUT
        :rtype: qt.QIcon
        """
        colormap = colors_mdl.Colormap(name)
        size = 32
        if name is not None:
            lut = colormap.getNColors(size)
        else:
            lut = colors
            if len(lut) > size:
                # Down sample
                step = int(len(lut) / size)
                lut = lut[::step]
            elif len(lut) < size:
                # Over sample
                indexes = numpy.arange(size) / float(size) * (len(lut) - 1)
                indexes = indexes.astype("int")
                lut = lut[indexes]
        if lut is None or len(lut) == 0:
            return qt.QIcon()

        pixmap = qt.QPixmap(size, size)
        painter = qt.QPainter(pixmap)
        for i in range(size):
            rgb = lut[i]
            r, g, b = rgb[0], rgb[1], rgb[2]
            painter.setPen(qt.QColor(r, g, b))
            painter.drawPoint(qt.QPoint(i, 0))

        painter.drawPixmap(0, 1, size, size - 1, pixmap, 0, 0, size, 1)
        painter.end()

        return qt.QIcon(pixmap)

    def getCurrentName(self):
        return self.itemData(self.currentIndex(), self.LUT_NAME)

    def getCurrentColors(self):
        return self.itemData(self.currentIndex(), self.LUT_COLORS)

    def findLutName(self, name):
        return self.findData(name, role=self.LUT_NAME)

    def findLutColors(self, lut):
        for index in range(self.count()):
            if self.itemData(index, role=self.LUT_NAME) is not None:
                continue
            colors = self.itemData(index, role=self.LUT_COLORS)
            if colors is None:
                continue
            if numpy.array_equal(colors, lut):
                return index
        return -1

    def setCurrentLut(self, colormap):
        name = colormap.getName()
        if name is not None:
            self._setCurrentName(name)
        else:
            lut = colormap.getColormapLUT()
            self._setCurrentLut(lut)

    def _setCurrentLut(self, lut):
        index = self.findLutColors(lut)
        if index == -1:
            index = self.count()
            self.addItem("Custom")
            self.setItemIcon(index, self.getIconPreview(colors=lut))
            self.setItemData(index, None, role=self.LUT_NAME)
            self.setItemData(index, lut, role=self.LUT_COLORS)
        self.setCurrentIndex(index)

    def _setCurrentName(self, name):
        index = self.findLutName(name)
        if index < 0:
            index = self.count()
            self.addItem(str.title(name))
            self.setItemIcon(index, self.getIconPreview(name=name))
            self.setItemData(index, name, role=self.LUT_NAME)
        self.setCurrentIndex(index)