Debian Codegraph @

gavo/svcs/customwidgets.py

raw
1 """
2 gavo.formal custom widgets used by the DC (enumerations, table options,
3 etc)
4 """
5
6 #c Copyright 2008-2025, the GAVO project <[email protected]>
7 #c
8 #c This program is free software, covered by the GNU GPL. See the
9 #c COPYING file in the source distribution.
10
11
12 from twisted.python import components
13
14 from twisted.web.template import tags as T
15
16 from zope.interface import implementer
17
18 from gavo import base
19 from gavo import formal
20 from gavo import rscdef
21 from gavo import utils
22 from gavo.formal import iformal
23 from gavo.formal import types as formaltypes
24 from gavo.formal import widget
25 from gavo.formal import widgetFactory #noflake: for customWidget
26 from gavo.formal.util import render_cssid
27 from gavo.formal.widget import ( #noflake: exported names
28 TextInput, Checkbox, Password, TextArea, ChoiceBase, SelectChoice,
29 SelectOtherChoice, RadioChoice, CheckboxMultiChoice, FileUpload,
30 Hidden)
31
32
33 @implementer(iformal.IWidget)
34 class DBOptions(object):
35 """A widget that offers limit and sort options for db based cores.
36
37 This is for use in a formal form and goes together with the FormalDict
38 type below.
39 """
40
41 sortWidget = None
42 limitWidget = None
43
44 def __init__(self, typeOb, service, queryMeta):
45 self.service = service
46 self.typeOb = typeOb
47 if getattr(self.service.core, "sortKey", None) is None:
48 self.sortWidget = self._makeSortWidget(service, queryMeta)
49 self.directionWidget = self._makeDirectionWidget(service, queryMeta)
50 if getattr(self.service.core, "limit", None) is None:
51 self.limitWidget = self._makeLimitWidget(service)
52
53 def _makeSortWidget(self, service, queryMeta):
54 fields = [f for f in self.service.getCurOutputFields(queryMeta,
55 raiseOnUnknown=False)]
56 if not fields:
57 return None
58 defaultKey = service.core.getProperty("defaultSortKey", None)
59 if defaultKey:
60 return SelectChoice(formaltypes.String(),
61 options=[(field.name, field.getLabel())
62 for field in fields if field.name!=defaultKey],
63 noneOption=(defaultKey, defaultKey))
64 else:
65 return SelectChoice(formaltypes.String(),
66 options=[(field.name, field.getLabel()) for field in fields])
67
68 def _makeDirectionWidget(self, service, queryMeta):
69 return SelectChoice(formaltypes.String(),
70 options=[("DESC", "DESC")],
71 noneOption=("ASC", "ASC"))
72
73 def _makeLimitWidget(self, service):
74 keys = [(i, str(i)) for i in [1000, 5000, 10000, 100000, 250000]]
75 return SelectChoice(formaltypes.Integer(), options=keys,
76 noneOption=(100, "100"))
77
78 def render(self, request, key, args, errors):
79 # The whole plan sucks -- these should have been two separate widgets
80 children = []
81 if '_DBOPTIONS' in args:
82 # we're working from pre-parsed (nevow formal) arguments
83 v = [[args["_DBOPTIONS"]["order"]] or "",
84 [args["_DBOPTIONS"]["limit"] or "100"],
85 [args["_DBOPTIONS"]["direction"] or "ASC"]]
86 else:
87 # args come raw from t.w.Request
88 v = [args.get(b"_DBOPTIONS_ORDER", [b'']),
89 args.get(b"MAXREC", [b"100"]),
90 args.get(b"_DBOPTIONS_DIR", b"ASC")]
91
92 if errors:
93 # emulate t.w.Request no matter what
94 v = [args.get(b"_DBOPTIONS_ORDER", [b'']),
95 args.get(b"MAXREC", [b"100"]),
96 args.get(b"_DBOPTIONS_DIR", b"ASC")]
97
98 else:
99 args = {"_DBOPTIONS_ORDER": utils.debytify(v[0][0]),
100 "MAXREC": int(v[1][0]), "_DBOPTIONS_DIR": v[2][0]}
101
102 if self.sortWidget:
103 children.extend(["Sort by ",
104 self.sortWidget.render(request, "_DBOPTIONS_ORDER", args, errors),
105 " "])
106 children.extend([" ", self.directionWidget.render(request,
107 "_DBOPTIONS_DIR", args, errors)])
108
109 if self.limitWidget:
110 children.extend([T.br, "Limit to ",
111 self.limitWidget.render(request, "MAXREC", args, errors),
112 " items."])
113 return T.span(id=render_cssid(key))[children]
114
115 # XXX TODO: make this immutable.
116 renderImmutable = render
117
118 def processInput(self, request, key, args, default=''):
119 order, limit, direction = None, None, "ASC"
120 if self.sortWidget:
121 order = self.sortWidget.processInput(request, "_DBOPTIONS_ORDER", args)
122 if self.directionWidget:
123 direction = self.directionWidget.processInput(
124 request, "_DBOPTIONS_DIR", args)
125 if self.limitWidget:
126 limit = self.limitWidget.processInput(request, "MAXREC", args)
127 return {
128 "order": order,
129 "limit": limit,
130 "direction": direction,
131 }
132
133
134 class FormalDict(formaltypes.Type):
135 """is a formal type for dictionaries.
136 """
137 pass
138
139
140 # I might want to specialise PairOf to have just two items; let's
141 # see if that's necessary, though.
142 PairOf = formaltypes.Sequence
143
144
145 class SimpleSelectChoice(SelectChoice):
146 def __init__(self, original, options, noneLabel=None):
147 if noneLabel is None:
148 noneOption = None
149 else:
150 noneOption = (noneLabel, noneLabel)
151 super(SimpleSelectChoice, self).__init__(original,
152 [(o,o) for o in options], noneOption)
153
154
155 # MultiSelectChoice is like formal's choice except you can specify a size.
156
157 class MultiSelectChoice(SelectChoice):
158 size = 3
159 def __init__(self, original, size=None, **kwargs):
160 if size is not None:
161 self.size=size
162 SelectChoice.__init__(self, original, **kwargs)
163
164 def _renderTag(self, request, key, value, converter, disabled):
165 if not isinstance(value, (list, tuple)):
166 value = [value]
167
168 tag = T.select(name=key, id=render_cssid(key))
169
170 if self.noneOption is not None:
171 noneVal = iformal.IKey(self.noneOption).key()
172 option = T.option(value=str(noneVal))[
173 iformal.ILabel(self.noneOption).label()]
174 if value is None or value==noneVal:
175 option = option(selected='selected')
176 tag[option]
177
178 for item in self.options or []:
179 optValue = iformal.IKey(item).key()
180 optLabel = iformal.ILabel(item).label()
181 optValue = converter.fromType(optValue)
182 option = T.option(value=str(optValue))[
183 str(optLabel)]
184 if optValue in value:
185 option = option(selected='selected')
186 tag[option]
187
188 if disabled:
189 tag(class_='disabled', disabled='disabled')
190 return T.span(style="white-space:nowrap")[
191 tag(size=str(self.size), multiple="multiple"),
192 " ",
193 T.span(class_="fieldlegend")[
194 "No selection matches all, multiple values legal."]]
195
196 def render(self, request, key, args, errors):
197 converter = iformal.IStringConvertible(self.original)
198 if errors:
199 value = args.get(key, [])
200 else:
201 value = [converter.fromType(v) for v in args.get(key, [])]
202 return self._renderTag(request, key, value, converter, False)
203
204 def processInput(self, request, key, args, default=''):
205 values = args.get(key, default.split())
206 rv = []
207 for value in values:
208 value = iformal.IStringConvertible(self.original).toType(value)
209 if self.noneOption is not None and value==iformal.IKey(
210 self.noneOption).key():
211 # NoneOption means "any" here, don't generate a condition
212 return None
213 rv.append(self.original.validate(value))
214 return rv
215
216
217 def _getDisplayOptions(ik):
218 """helps EnumeratedWidget figure out the None option and the options
219 for selection.
220 """
221 noneOption = None
222 options = []
223 default = ik.values.default
224 if ik.value:
225 default = ik.value
226
227 if default is not None:
228 if ik.required:
229 # default given and field required: There's no noneOption but a
230 # selected default (this shouldn't happen when values.default is gone)
231 options = ik.values.options
232 else:
233 # default given and becomes the noneOption
234 for o in ik.values.options:
235 if o.content_==ik.values.default:
236 noneOption = o
237 else:
238 options.append(o)
239 else: # no default given, make up ANY option as noneOption unless
240 # ik is required.
241 options.extend(ik.values.options)
242 noneOption = None
243 if not ik.required and not ik.values.multiOk or ik.multiplicity=="multiple":
244 noneOption = base.makeStruct(rscdef.Option, title="ANY",
245 content_="__DaCHS__ANY__")
246 return noneOption, options
247
248
249 def EnumeratedWidget(ik):
250 """a widget factory for input keys over enumerated columns.
251
252 This probably contains a bit too much magic, but let's see. The current
253 rules are:
254
255 If values.multiOk is true, render a MultiSelectChoice, else
256 render a SelectChoice or a RadioChoice depending on how many
257 items there are.
258
259 If ik is not required, add an ANY key evaluating to None. For
260 MultiSelectChoices we don't need this since for them, you can
261 simply leave it all unselected.
262
263 If there is a default, it becomes the NoneOption.
264 """
265 if not ik.isEnumerated():
266 raise base.StructureError("%s is not enumerated"%ik.name)
267 noneOption, options = _getDisplayOptions(ik)
268 moreArgs = {"noneOption": noneOption}
269 if ik.values.multiOk or ik.multiplicity=="multiple":
270 if ik.showItems==-1 or len(options)<4:
271 baseWidget = CheckboxMultiChoice
272 del moreArgs["noneOption"]
273 else:
274 baseWidget = MultiSelectChoice
275 moreArgs["size"] = ik.showItems
276 moreArgs["noneOption"] = None
277 else:
278 if len(options)<4:
279 baseWidget = RadioChoice
280 else:
281 baseWidget = SelectChoice
282
283 res = formal.widgetFactory(baseWidget, options=options,
284 **moreArgs)
285 return res
286
287
288 class StringFieldWithBlurb(widget.TextInput):
289 """is a text input widget with additional material at the side.
290 """
291 additionalMaterial = ""
292
293 def __init__(self, *args, **kwargs):
294 am = kwargs.pop("additionalMaterial", None)
295 widget.TextInput.__init__(self, *args, **kwargs)
296 if am is not None:
297 self.additionalMaterial = am
298
299 def _renderTag(self, request, key, value, readonly):
300 plainTag = widget.TextInput._renderTag(self, request, key, value,
301 readonly)
302 return T.span(style="white-space:nowrap")[
303 plainTag,
304 " ",
305 T.span(class_="fieldlegend")[self.additionalMaterial]]
306
307
308 class NumericExpressionField(StringFieldWithBlurb):
309 additionalMaterial = T.a(href=base.makeSitePath(
310 "/static/help_vizier.shtml#floats"))[
311 "[?num. expr.]"]
312
313
314 class DateExpressionField(StringFieldWithBlurb):
315 additionalMaterial = T.a(href=base.makeSitePath(
316 "/static/help_vizier.shtml#dates"))[
317 "[?date expr.]"]
318
319
320 class StringExpressionField(StringFieldWithBlurb):
321 additionalMaterial = T.a(href=base.makeSitePath(
322 "/static/help_vizier.shtml#string"))[
323 "[?char expr.]"]
324
325
326 class ScalingTextArea(widget.TextArea):
327 """is a text area that scales with the width of the window.
328 """
329 def _renderTag(self, request, key, value, readonly):
330 tag=T.textarea(name=key, id=render_cssid(key), rows=str(self.rows),
331 style="width:100% !important")[str(value or '')]
332 if readonly:
333 tag(class_='readonly', readonly='readonly')
334 return tag
335
336
337 class Interval(object):
338 """A widget to enter an interval (lower/upper) pair of something.
339
340 As usual with formal widgets, this is constructed with the type, which
341 must be PairOf here; we're taking the widget we're supposed to pair from
342 it.
343 """
344 def __init__(self, original):
345 self.original = original
346 self.inputType = self.original.type
347
348 def _renderTag(self, request, key, values, readonly):
349 tags = []
350 for index, seqid in enumerate(["lower", "upper"]):
351 tag = T.input(type="text", name=key+seqid,
352 id=render_cssid(key+seqid), value=values[index])
353 if readonly:
354 tag(class_='readonly', readonly='readonly')
355 # TODO: make a placeholder in the interval
356 # if self.placeholder is not None:
357 # tag(placeholder=self.placeholder)
358 tags.append(tag)
359
360 tags[1:1] = " \u2013 "
361
362 return T.div(class_="form-interval")[tags]
363
364 def render(self, request, key, args, errors):
365 if errors:
366 values = [args.get(key+"lower", [''])[0],
367 args.get(key+"upper", [''])[0]]
368 else:
369 baseType = iformal.IStringConvertible(self.original)
370 values = [baseType.fromType(args.get(key+"lower")),
371 baseType.fromType(args.get(key+"upper"))]
372
373 return self._renderTag(request, key, values, False)
374
375 def renderImmutable(self, request, key, args, errors):
376 baseType = iformal.IStringConvertible(self.original)
377 values = [baseType.fromType(args.get(key+"lower")),
378 baseType.fromType(args.get(key+"upper"))]
379 return self._renderTag(request, key, values, True)
380
381 def processInput(self, request, key, args, default=["", ""]):
382 charset = "utf-8"
383 values = [
384 args.get(key+"lower", [default[0]])[0].decode(charset),
385 args.get(key+"upper", [default[0]])[0].decode(charset)]
386 baseType = iformal.IStringConvertible(self.original.type())
387 values = [baseType.toType(values[0]),
388 baseType.toType(values[1])]
389 return self.original.validate(values)
390
391
392 def makeWidgetFactory(code):
393 return eval(code)
394
395
396 ############# formal adapters for DaCHS objects
397
398 # column options
399 from gavo.rscdef import column
400
401 @implementer(iformal.ILabel, iformal.IKey)
402 class ToFormalAdapter(object):
403
404 def __init__(self, original):
405 self.original = original
406
407 def label(self):
408 return str(self.original.title)
409
410 def key(self):
411 return str(self.original.content_)
412
413 components.registerAdapter(ToFormalAdapter, column.Option, iformal.ILabel)
414 components.registerAdapter(ToFormalAdapter, column.Option, iformal.IKey)