File: validators.py

package info (click to toggle)
pyfai 0.20.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 78,460 kB
  • sloc: python: 49,743; lisp: 7,059; sh: 225; ansic: 165; makefile: 119
file content (251 lines) | stat: -rw-r--r-- 8,757 bytes parent folder | download | duplicates (4)
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
# coding: utf-8
# /*##########################################################################
#
# Copyright (C) 2016-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.
#
# ###########################################################################*/

__authors__ = ["V. Valls"]
__license__ = "MIT"
__date__ = "16/10/2020"

import logging
from silx.gui import qt

_logger = logging.getLogger(__name__)


class DoubleValidator(qt.QDoubleValidator):
    """
    Double validator with extra feature.

    The default locale used is not the default one. It uses locale C with
    RejectGroupSeparator option. This allows to have consistant rendering of
    double using dot separator without any comma.

    QLocale provides an API to support or not groups on numbers. Unfortunatly
    the default Qt QDoubleValidator do not filter out the group character in
    case the locale rejected it. This implementation reject the group character
    from the validation, and remove it from the fixup. Only if the locale is
    defined to reject it.

    This validator also allow to type a dot anywhere in the text. The last dot
    replace the previous one. In this way, it became convenient to fix the
    location of the dot, without complex manual manipulation of the text.
    """

    def __init__(self, parent=None):
        qt.QDoubleValidator.__init__(self, parent)
        locale = qt.QLocale(qt.QLocale.C)
        locale.setNumberOptions(qt.QLocale.RejectGroupSeparator)
        self.setLocale(locale)

    def validate(self, inputText, pos):
        """
        Reimplemented from `QDoubleValidator.validate`.

        :param str inputText: Text to validate
        :param int pos: Position of the cursor
        """
        if pos > 0:
            locale = self.locale()

            # If the typed character is a dot, move the dot instead of ignoring it
            if inputText[pos - 1] == locale.decimalPoint():
                beforeDot = inputText[0:pos].count(locale.decimalPoint())
                pos -= beforeDot
                inputText = inputText.replace(locale.decimalPoint(), "")
                inputText = inputText[0:pos] + locale.decimalPoint() + inputText[pos:]
                pos = pos + 1

            if locale.numberOptions() == qt.QLocale.RejectGroupSeparator:
                    if inputText[pos - 1] == locale.groupSeparator():
                        # filter the group separator
                        inputText = inputText[pos - 1:] + inputText[pos:]
                        pos = pos - 1

        return super(DoubleValidator, self).validate(inputText, pos)

    def fixup(self, inputText):
        """
        Remove group characters from the input text if the locale is defined to
        do so.

        :param str inputText: Text to validate
        """
        locale = self.locale()
        if locale.numberOptions() == qt.QLocale.RejectGroupSeparator:
            inputText = inputText.replace(locale.groupSeparator(), "")
        return inputText

    def toValue(self, text):
        """Convert the input string into an interpreted value

        :param str text: Input string
        :rtype: Tuple[object,bool]
        :returns: A tuple containing the resulting object and True if the
            string is valid
        """
        value, validated = self.locale().toDouble(text)
        return value, validated

    def toText(self, value):
        """Convert the input string into an interpreted value

        :param object value: Input object
        :rtype: str
        """
        return str(value)


class AdvancedDoubleValidator(DoubleValidator):
    """
    Validate double values and provides features to allow or disable other
    things.
    """

    def __init__(self, parent=None):
        super(AdvancedDoubleValidator, self).__init__(parent=parent)
        self.__allowEmpty = False
        self.__boundIncluded = True, True

    def setAllowEmpty(self, allow):
        """
        Allow the field to be empty. Default is false.

        An empty field is represented as a `None` value.

        :param bool allow: New state.
        """
        self.__allowEmpty = allow

    def setIncludedBound(self, minBoundIncluded, maxBoundIncluded):
        """
        Allow the include or exclude boundary ranges. Default including both
        boundaries.
        """
        self.__boundIncluded = minBoundIncluded, maxBoundIncluded

    def validate(self, inputText, pos):
        """
        Reimplemented from `QDoubleValidator.validate`.

        Allow to provide an empty value.

        :param str inputText: Text to validate
        :param int pos: Position of the cursor
        """
        if self.__allowEmpty:
            if inputText.strip() == "":
                # python API is not the same as C++ one
                return qt.QValidator.Acceptable, inputText, pos

        acceptable, inputText, pos = super(AdvancedDoubleValidator, self).validate(inputText, pos)

        if acceptable == qt.QValidator.Acceptable:
            # Check boundaries
            if self.__boundIncluded != (True, True):
                value, isValid = self.toValue(inputText)
                if not isValid:
                    acceptable = qt.QValidator.Intermediate

        return acceptable, inputText, pos

    def toValue(self, text):
        """Convert the input string into an interpreted value

        :param str text: Input string
        :rtype: Tuple[object,bool]
        :returns: A tuple containing the resulting object and True if the
            string is valid
        """
        if self.__allowEmpty:
            if text.strip() == "":
                return None, True

        value, isValid = super(AdvancedDoubleValidator, self).toValue(text)

        if isValid:
            # Check boundaries
            if self.__boundIncluded != (True, True):
                if not self.__boundIncluded[0]:
                    if value == self.bottom():
                        isValid = False
                if not self.__boundIncluded[1]:
                    if value == self.top():
                        isValid = False

        return value, isValid

    def toText(self, value):
        """Convert the input string into an interpreted value

        :param object value: Input object
        :rtype: str
        """
        if self.__allowEmpty:
            if value is None:
                return ""
        return super(AdvancedDoubleValidator, self).toText(value)


class IntegerAndEmptyValidator(qt.QIntValidator):
    """
    Validate double values or empty string.
    """

    def validate(self, inputText, pos):
        """
        Reimplemented from `QIntValidator.validate`.

        Allow to provide an empty value.

        :param str inputText: Text to validate
        :param int pos: Position of the cursor
        """
        if inputText.strip() == "":
            # python API is not the same as C++ one
            return qt.QValidator.Acceptable, inputText, pos

        return super(IntegerAndEmptyValidator, self).validate(inputText, pos)

    def toValue(self, text):
        """Convert the input string into an interpreted value

        :param str text: Input string
        :rtype: Tuple[object,bool]
        :returns: A tuple containing the resulting object and True if the
            string is valid
        """
        if text.strip() == "":
            return None, True
        value, validated = self.locale().toInt(text)
        return value, validated

    def toText(self, value):
        """Convert the input string into an interpreted value

        :param object value: Input object
        :rtype: str
        """
        if value is None:
            return ""
        return str(value)