Debian Codegraph @

pymeasure/display/widgets/filename_widget.py

raw
1 #
2 # This file is part of the PyMeasure package.
3 #
4 # Copyright (c) 2013-2024 PyMeasure Developers
5 #
6 # Permission is hereby granted, free of charge, to any person obtaining a copy
7 # of this software and associated documentation files (the "Software"), to deal
8 # in the Software without restriction, including without limitation the rights
9 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10 # copies of the Software, and to permit persons to whom the Software is
11 # furnished to do so, subject to the following conditions:
12 #
13 # The above copyright notice and this permission notice shall be included in
14 # all copies or substantial portions of the Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
22 # THE SOFTWARE.
23 #
24
25 import logging
26 import re
27 import textwrap
28
29 from ..Qt import QtCore, QtWidgets, QtGui
30
31 log = logging.getLogger(__name__)
32 log.addHandler(logging.NullHandler())
33
34
35 class FilenameLineEdit(QtWidgets.QLineEdit):
36 """
37 Widget that allows to choose a filename.
38 A completer is implemented for quick completion of placeholders
39 """
40
41 def __init__(self, procedure_class, parent=None):
42 super().__init__("DATA", parent=parent)
43
44 self.placeholders = procedure_class.placeholder_names()
45 self.placeholders.extend(["date", "time"])
46
47 completer = PlaceholderCompleter(self.placeholders)
48 self.setCompleter(completer)
49
50 validator = FilenameValidator(self.placeholders, self)
51 self.setValidator(validator)
52
53 self.set_tool_tip()
54
55 def set_tool_tip(self):
56 ext = self.parent().extensions[0]
57 extensions = ("'." + "', '.".join(self.parent().extensions[:-1]) +
58 f"', or '.{self.parent().extensions[-1]}'")
59 placeholders = "'" + "';\n- '".join(self.placeholders) + "'"
60 self.setToolTip("\n".join(textwrap.wrap(
61 "The filename of the file to which the measurement will be stored. Placeholders (in "
62 "standard python format, i.e.: '{variable name:formatspec}') will be replaced by "
63 f"the respective value. The extension '.{ext}' will be appended, unless an extension "
64 f"(one of {extensions}) is recognized. Additionally, an index number ('_#') is "
65 "added to ensure the uniqueness of the filename.", width=100)) +
66 f"\nValid placeholders are:\n- {placeholders}."
67 )
68
69
70 class PlaceholderCompleter(QtWidgets.QCompleter):
71 def __init__(self, placeholders):
72 super().__init__()
73 self.placeholders = placeholders
74
75 self.setCompletionMode(QtWidgets.QCompleter.CompletionMode.PopupCompletion)
76 self.setModelSorting(QtWidgets.QCompleter.ModelSorting.CaseInsensitivelySortedModel)
77 self.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
78 self.setFilterMode(QtCore.Qt.MatchContains)
79
80 def splitPath(self, path):
81 if path.endswith("{"):
82 options = [path + placeholder + "}" for placeholder in self.placeholders]
83 model = QtCore.QStringListModel(options)
84 self.setModel(model)
85 elif path.count("{") == path.count("}"):
86 # Clear the autocomplete options
87 self.setModel(QtCore.QStringListModel())
88
89 return [path]
90
91
92 class FilenameValidator(QtGui.QValidator):
93 def __init__(self, placeholders, parent):
94 self.parent = parent
95 self.placeholders = placeholders
96
97 self.full_placeholder = re.compile(r"{([^{}:]*)(:[^{}]*)?}")
98 self.half_placeholder = re.compile(r"{([^{}:]*)(:[^{}]*)?$")
99 self.valid_filename = re.compile(r"^[^<>:\"/\\|?*{}]*$")
100 super().__init__()
101
102 def fixup(self, input):
103 half_placeholder = self.half_placeholder.findall(input)
104
105 if half_placeholder:
106 input = input + "}"
107
108 return input
109
110 def validate(self, input, pos):
111 test_input = input
112
113 full_placeholders = self.full_placeholder.findall(input)
114 half_placeholder = self.half_placeholder.findall(input)
115
116 test_input = self.full_placeholder.sub("_plchldr_", test_input)
117 test_input = self.half_placeholder.sub("_plchldr", test_input)
118
119 valid_filename = self.valid_filename.fullmatch(test_input)
120
121 # Determine state of input
122 if not valid_filename:
123 state = QtGui.QValidator.Invalid
124 elif half_placeholder:
125 state = QtGui.QValidator.Intermediate
126 else:
127 state = QtGui.QValidator.Acceptable
128
129 # Control the warning for the invalid placeholders
130 incorrect_placeholders = [p for p in full_placeholders if p[0] not in self.placeholders]
131 if incorrect_placeholders:
132 if not self.parent.actions():
133 pixmapi = QtWidgets.QStyle.StandardPixmap.SP_MessageBoxCritical
134 icon = self.parent.style().standardIcon(pixmapi)
135 self.parent.addAction(icon, self.parent.ActionPosition.TrailingPosition)
136
137 # Add tooltip to show which placeholders are not valid
138 act = self.parent.actions()[0]
139
140 marked_input = input
141 for placeholder in [f"{{{p[0] + p[1]}}}" for p in incorrect_placeholders]:
142 marked_input = marked_input.replace(
143 placeholder, f"<b><font color='red'>{placeholder}</font></b>"
144 )
145
146 act.setToolTip(
147 "<p style='white-space:pre'>"
148 "The input filename contains placeholders with<br/>invalid variable names:<br/>"
149 " - '" + "',<br/> - '".join([p[0] for p in incorrect_placeholders]) + "'."
150 "<br/><br/>Received input:<br/>" + marked_input + "</p>"
151 )
152 else:
153 # Remove action, if it exists
154 if self.parent.actions():
155 assert len(self.parent.actions()) == 1, (
156 "More than 1 action defined, not sure " "which to remove."
157 )
158 self.parent.removeAction(self.parent.actions()[0])
159
160 return state, input, pos