Debian Codegraph @

gavo/web/formrender.py

raw
1 """
2 The form renderer is the standard renderer for web-facing services.
3 """
4
5 #c Copyright 2008-2025, the GAVO project <[email protected]>
6 #c
7 #c This program is free software, covered by the GNU GPL. See the
8 #c COPYING file in the source distribution.
9
10
11 from twisted.internet import defer
12 from twisted.web import server
13 from twisted.web import template
14 from twisted.web.template import tags as T
15
16 from gavo import base
17 from gavo import formats
18 from gavo import svcs
19 from gavo.base import typesystems
20 from gavo import formal
21 from gavo.formal import nevowc
22 from gavo.svcs import customwidgets
23 from gavo.svcs import inputdef
24 from gavo.svcs import streaming
25 from gavo.svcs import weberrors
26 from gavo.web import grend
27 from gavo.web import serviceresults
28
29
30 class ToFormalConverter(typesystems.FromSQLConverter):
31 """is a converter from SQL types to Formal type specifications.
32
33 The result of the conversion is a tuple of formal type and widget factory.
34 """
35 typeSystem = "Formal"
36 simpleMap = {
37 "smallint": (formal.Integer, formal.TextInput),
38 "integer": (formal.Integer, formal.TextInput),
39 "int": (formal.Integer, formal.TextInput),
40 "bigint": (formal.Integer, formal.TextInput),
41 "real": (formal.Float, formal.TextInput),
42 "float": (formal.Float, formal.TextInput),
43 "boolean": (formal.Boolean, formal.Checkbox),
44 "double precision": (formal.Float, formal.TextInput),
45 "double": (formal.Float, formal.TextInput),
46 "text": (formal.String, formal.TextInput),
47 "unicode": (formal.String, formal.TextInput),
48 "char": (formal.String, formal.TextInput),
49 "date": (formal.Date, formal.widgetFactory(formal.DatePartsInput,
50 twoCharCutoffYear=50, dayFirst=True)),
51 "time": (formal.Time, formal.TextInput),
52 "timestamp": (formal.Date, formal.widgetFactory(formal.DatePartsInput,
53 twoCharCutoffYear=50, dayFirst=True)),
54 "vexpr-float": (formal.String, customwidgets.NumericExpressionField),
55 "vexpr-date": (formal.String, customwidgets.DateExpressionField),
56 "vexpr-string": (formal.String, customwidgets.StringExpressionField),
57 "vexpr-mjd": (formal.String, customwidgets.DateExpressionField),
58 "pql-string": (formal.String, formal.TextInput),
59 "pql-int": (formal.String, formal.TextInput),
60 "pql-float": (formal.String, formal.TextInput),
61 "pql-date": (formal.String, formal.TextInput),
62 "file": (formal.File, None),
63 "raw": (formal.String, formal.TextInput),
64 }
65
66 def convert(self, type, xtype=None):
67 if xtype=="interval":
68 baseType, baseWidget = self.convert(type.rsplit('[', 1)[0])
69 return (lambda **kw: customwidgets.PairOf(baseType, **kw),
70 customwidgets.Interval)
71
72 try:
73 return typesystems.FromSQLConverter.convert(self, type)
74 except base.ConversionError:
75 raise
76
77 def mapComplex(self, type, length):
78 if type in self._charTypes:
79 return formal.String, formal.TextInput
80
81 if length!='1' and type in self.simpleMap:
82 ftype, _ = self.simpleMap[type]
83 class S(formal.Sequence):
84 type = ftype
85 instance = ftype()
86 return S, formal.TextInput
87
88
89 sqltypeToFormal = ToFormalConverter().convert
90
91
92 def _getFormalType(inputKey):
93 return sqltypeToFormal(inputKey.type, xtype=inputKey.xtype
94 )[0](required=inputKey.required)
95
96
97 def _makeWithPlaceholder(origWidgetFactory, newPlaceholder):
98 """helps _addPlaceholder to keep the namespaces sane.
99 """
100 if newPlaceholder is None:
101 return origWidgetFactory
102
103 class widgetFactory(origWidgetFactory):
104 placeholder = newPlaceholder
105 return widgetFactory
106
107
108 def _getWidgetFactory(inputKey):
109 if not hasattr(inputKey, "_widgetFactoryCache"):
110 widgetFactory = inputKey.widgetFactory
111
112 if widgetFactory is None:
113 if inputKey.isEnumerated():
114 widgetFactory = customwidgets.EnumeratedWidget(inputKey)
115 else:
116 widgetFactory = sqltypeToFormal(inputKey.type, inputKey.xtype)[1]
117
118 if isinstance(widgetFactory, str):
119 widgetFactory = customwidgets.makeWidgetFactory(widgetFactory)
120
121 inputKey._widgetFactoryCache = _makeWithPlaceholder(widgetFactory,
122 inputKey.getProperty("placeholder", None))
123 return inputKey._widgetFactoryCache
124
125
126 def getFieldArgsForInputKey(inputKey):
127 """returns a dictionary of keyword arguments for gavo.formal
128 addField from a DaCHS InputKey.
129 """
130 # infer whether to show a unit and if so, which
131 unit = ""
132 if inputKey.type!="date": # Sigh.
133 unit = inputKey.inputUnit or inputKey.unit or ""
134 if unit:
135 unit = " [%s]"%unit
136 label = inputKey.getLabel()
137
138 res = {
139 "name": inputKey.name,
140 "type": _getFormalType(inputKey),
141 "widgetFactory": _getWidgetFactory(inputKey),
142 "label": label+unit,
143 "description": inputKey.description,
144 "cssClass": inputKey.getProperty("cssClass", None),}
145
146 if inputKey.values and inputKey.values.default:
147 res["default"] = str(inputKey.values.default)
148 if inputKey.value:
149 res["default"] = str(inputKey.value)
150
151 return res
152
153
154 class MultiField(formal.Group, template.Element):
155 """A "widget" containing multiple InputKeys (i.e., formal Fields) in
156 a single line.
157 """
158
159 loader = template.TagLoader(
160 T.div(class_=template.slot("class"), render="multifield")[
161 T.label(for_=template.slot('id'))[template.slot('label')],
162 T.div(class_="multiinputs", id=template.slot('id'),
163 render="childFields"),
164 T.div(class_='description')[template.slot('description')],
165 template.slot('message')])
166
167 @template.renderer
168 def childFields(self, request, tag):
169 formData = self.form.data
170 formErrors = self.form.errors
171
172 for field in self.items:
173 widget = field.makeWidget()
174 if field.type.immutable:
175 render = widget.renderImmutable
176 else:
177 render = widget.render
178 cssClass = " ".join(s for s in (field.cssClass, "inmulti") if s)
179
180 if formErrors:
181 formData = request.args
182
183 tag[
184 T.span(class_=cssClass)[
185 render(request, field.key, formData, formErrors)(
186 class_=cssClass, title=field.description or "")]]
187 return tag
188
189 def _getMessageElement(self, request):
190 errors = []
191 formErrors = self.form.errors
192 if formErrors is not None:
193 for field in self.items:
194 err = formErrors.getFieldError(field.key)
195 if err is not None:
196 errors.append(err.message)
197 if errors:
198 return T.div(class_='message')["; ".join(errors)]
199 else:
200 return ''
201
202 @template.renderer
203 def multifield(self, request, tag):
204 errMsg = self._getMessageElement(request)
205 tag.fillSlots(description=self.description,
206 label=self.label or "",
207 id="multigroup-"+self.key,
208 message=errMsg)
209 if errMsg:
210 tag.fillSlots(**{"class":'field error'})
211 else:
212 tag.fillSlots(**{"class":'field'})
213 return tag
214
215
216 class FormMixin:
217 """A mixin to produce input forms for services and display
218 errors within these forms.
219 """
220 parameterStyle = "form"
221
222 def _handleInputErrors(self, failure, request):
223 """goes as an errback to form handling code to allow correction form
224 rendering at later stages than validation.
225 """
226 if isinstance(failure.value, formal.FormError):
227 self.genForm.errors.add(failure.value)
228 elif isinstance(failure.value, base.ValidationError) and isinstance(
229 failure.value.colName, str):
230 try:
231 # Find out the formal name of the failing field...
232 failedField = failure.value.colName
233 # ...and make sure it exists
234 self.genForm.items.getItemByName(failedField)
235 self.genForm.errors.add(formal.FieldValidationError(
236 str(failure.getErrorMessage()), failedField))
237 except KeyError: # Failing field cannot be determined
238 self.genForm.errors.add(formal.FormError("Problem with input"
239 " in the internal or generated field '%s': %s"%(
240 failure.value.colName, failure.getErrorMessage())))
241 else:
242 base.ui.notifyFailure(failure)
243 return failure
244 return self.genForm.errors
245
246 def _addDefaults(self, request, form, additionalDefaults):
247 """adds defaults from additionalDefaults.
248
249 This is to let operators preset fields.
250 """
251 if request is None:
252 args = ()
253 else:
254 args = request.strargs
255
256 for key, value in list(additionalDefaults.items()):
257 if not key in args:
258 form.data[key] = value
259
260 def _addInputKey(self, form, container, inputKey):
261 """adds a form field for an inputKey to the form.
262 """
263 if inputKey.values and inputKey.values.default:
264 self._defaultsForForm[inputKey.name] = inputKey.values.default
265
266 if inputKey.hasProperty("defaultForForm"):
267 self._defaultsForForm[inputKey.name
268 ] = inputKey.getProperty("defaultForForm")
269
270 container.addField(**getFieldArgsForInputKey(inputKey))
271
272 def _groupQueryFields(self, inputTable):
273 """returns a list of "grouped" inputKey names from inputTable.
274
275 The idea here is that you can define "groups" in your input table.
276 Each such group can contain paramRefs. When the input table is rendered
277 in HTML, the grouped fields are created in a formal group. To make this
278 happen, they may need to be resorted. This happens in this function.
279
280 The returned list contains strings (parameter names), groups (meaning
281 "start a new group") and None (meaning end the current group).
282
283 This is understood and used by _addQueryFields.
284 """
285 groupedKeys = {}
286 for group in inputTable.groups:
287 for ref in group.paramRefs:
288 groupedKeys[ref.key] = group
289
290 inputKeySequence, addedNames = [], set()
291 for inputKey in inputTable.inputKeys:
292 thisName = inputKey.name
293
294 if thisName in addedNames:
295 # part of a group and added as such
296 continue
297
298 newGroup = groupedKeys.get(thisName)
299 if newGroup is None:
300 # not part of a group
301 inputKeySequence.append(thisName)
302 addedNames.add(thisName)
303 else:
304 # current key is part of a group: add it and all others in the group
305 # enclosed in group/None.
306 inputKeySequence.append(newGroup)
307 for ref in groupedKeys[inputKey.name].paramRefs:
308 inputKeySequence.append(ref.key)
309 addedNames.add(ref.key)
310 inputKeySequence.append(None)
311 return inputKeySequence
312
313 def _addQueryFieldsForInputTable(self, form, inputTable):
314 """generates input fields form the parameters of inputTable, taking
315 into account grouping if necessary.
316 """
317 containers = [form]
318 for item in self._groupQueryFields(inputTable):
319 if item is None: # end of group
320 containers.pop()
321
322 elif isinstance(item, str): # param reference
323 self._addInputKey(form, containers[-1],
324 inputTable.inputKeys.getColumnByName(item))
325
326 else:
327 # It's a new group -- if the group has a "style" property and
328 # it's "compact", use a special container form formal.
329 if item.getProperty("style", None)=="compact":
330 groupClass = MultiField
331 else:
332 groupClass = formal.Group
333
334 containers.append(
335 form.add(groupClass(item.name, description=item.description,
336 label=item.getProperty("label", None),
337 cssClass=item.getProperty("cssClass", None),
338 form=form)))
339
340 def _addQueryFields(self, form):
341 """adds the inputFields of the service to form, setting proper defaults
342 from the field or from data.
343 """
344 # we have an inputTable. Handle groups and other fancy stuff
345 self._addQueryFieldsForInputTable(form,
346 self.service.getCoreFor(self, self.queryMeta).inputTable)
347
348 # and add the service keys manually as appropriate
349 for item in inputdef.filterInputKeys(self.service.serviceKeys,
350 self.name, inputdef.getRendererAdaptor(self)):
351 self._addInputKey(form, form, item)
352
353 def _addMetaFields(self, form):
354 """adds fields to choose output properties to form.
355 """
356 try:
357 if self.service.core.wantsTableWidget():
358 form.addField("_DBOPTIONS", svcs.FormalDict,
359 formal.widgetFactory(svcs.DBOptions, self.service, self.queryMeta),
360 label="Table")
361 except AttributeError: # probably no wantsTableWidget method on core
362 pass
363
364 def _getFormLinks(self):
365 """returns stan for widgets building GET-type strings for the current
366 form content.
367 """
368 return T.div(class_="formLinks")[
369 T.a(href="", class_="resultlink", onmouseover=
370 "this.href=makeResultLink(getEnclosingForm(this))",
371 # Ugh -- when the form is flattened, the formal.FormRenderer
372 # is the renderFactory, and it doesn't know iflinkable.
373 # No idea how we'd do this in an XML template. Hm.
374 render=self.iflinkable)
375 ["[Result link]"],
376 " ",
377 T.a(href="", class_="resultlink", onmouseover=
378 "this.href=makeBookmarkLink(getEnclosingForm(this))")[
379 T.img(src=base.makeSitePath("/static/img/bookmark.png"),
380 class_="silentlink", title="Link to this form", alt="[bookmark]")
381 ],
382 ]
383
384 def form_genForm(self, request=None, data=None):
385 # this is an accumulator for defaultForForm items processed; this
386 # is used below to pre-fill forms without influencing service
387 # behaviour in the absence of parameters.
388 self._defaultsForForm = {}
389
390 form = formal.Form()
391 self._addQueryFields(form)
392 self._addMetaFields(form)
393 self._addDefaults(request, form, self._defaultsForForm)
394
395 if (self.name=="form"
396 and self.service.getProperty("fixedFormat", "")!="True"):
397 form.addField("_OUTPUT", formal.String,
398 formal.widgetFactory(serviceresults.OutputFormat,
399 self.service, self.queryMeta),
400 label="Output format")
401
402 form.actionURL = self.service.getURL(self.name)
403 form.addAction(self.submitAction, label="Go")
404 form.actionMaterial = self._getFormLinks()
405 self.genForm = form
406 return form
407
408 def _setResult(self, result):
409 """sets result as the renderer's internal result
410
411 This is the default callback of the submit action and is
412 required by various data and render functions. Once the
413 renderer is here, non-rsc.Data results have been dealt with already.
414 """
415 self.result = result
416 return result
417
418 def data_resultmeta(self, request, tag):
419 resultmeta = {
420 "itemsMatched": str(self.queryMeta.get("Matched",
421 len(self.result.getPrimaryTable()))),
422 "message": "",
423 }
424 return resultmeta
425
426 def data_inputRec(self, request, tag):
427 if self.queryMeta["inputTable"]:
428 return self.queryMeta["inputTable"].getParamDict()
429 else:
430 return {}
431
432 def data_table(self, request, tag):
433 return self.result.getPrimaryTable()
434
435 def data_tableWithRole(self, role):
436 """returns the table with role.
437
438 If no such table is available, this will return an empty string.
439 """
440 def _(req, tag):
441 try:
442 return self.result.getTableWithRole(role)
443 except (AttributeError, base.DataError):
444 return ""
445
446 return _
447
448 def _realSubmitAction(self, request, form, data):
449 """helps submitAction by doing the real work.
450
451 It is here so we can add an error handler in submitAction.
452 """
453 if self.queryMeta.get("format") in ("HTML", None):
454 resultWriter = self
455 else:
456 resultWriter = serviceresults.getFormat(self.queryMeta["format"])
457
458 if resultWriter.compute:
459 d = self.runAsyncWithFormalData(data, request)
460 else:
461 d = defer.succeed(None)
462
463 d.addCallback(self._setResult)
464 if resultWriter is not self:
465 d.addCallback(resultWriter._formatOutput, request, self.queryMeta)
466 return d
467
468 def submitAction(self, request, form, data):
469 """executes the service.
470
471 This is a callback for the formal form.
472 """
473 return defer.maybeDeferred(
474 self._realSubmitAction, request, form, data
475 ).addErrback(self._handleInputErrors, request)
476
477
478 class FormRenderer(formal.ResourceWithForm,
479 FormMixin,
480 grend.CustomTemplateMixin,
481 grend.HTMLResultRenderMixin,
482 grend.ServiceBasedPage):
483 """The "normal" renderer within DaCHS for web-facing services.
484
485 It will display a form and allow outputs in various formats.
486
487 It also does error reporting as long as that is possible within
488 the form.
489 """
490 name = "form"
491 runOnEmptyInputs = False
492 processOnGET = True
493 compute = True
494 defaultOutputFormat = "HTML"
495
496 def __init__(self, request, service):
497 grend.ServiceBasedPage.__init__(self, request, service)
498 if "form" in self.service.templates:
499 self.customTemplate = self.service.getTemplate("form")
500
501 # enable special handling if I'm rendering fixed-behaviour services
502 # (i.e., ones that never have inputs) XXX TODO: Figure out where I used this and fix that to use the fixed renderer (or whatever)
503 if not self.service.getInputKeysFor(self):
504 self.runOnEmptyInputs = True
505
506 @classmethod
507 def isBrowseable(self, service):
508 return True
509
510 @classmethod
511 def isCacheable(self, segments, request):
512 return segments==()
513
514 def render(self, request):
515 if self.runOnEmptyInputs:
516 request.args[formal.FORMS_KEY] = [b"genForm"]
517 # we need to override the normal render callback here because we
518 # may actually stream out completely different stuff, and
519 # if we do, these need to finish the request. But that's
520 # all arranged up in the submit action, so all we need to
521 # to here is ignore things.
522 return formal.ResourceWithForm.render(self,
523 request,
524 customCallback=lambda res: self._formatOutput(res, request))
525
526 def crash(self, failure, request):
527 return weberrors.renderDCErrorPage(failure, request)
528
529 handleError = crash
530
531 def _formatOutput(self, res, request):
532 """delivers the whole document, hopefully not blocking too much.
533 """
534 if res==server.NOT_DONE_YET:
535 # _realSubmitAction has arranged for someone else to write the result,
536 # and that's what its render method returned
537 return res
538
539 if isinstance(res, tuple):
540 # core returned a complete document (mime and string)
541 mime, payload = res
542 request.setHeader("content-type", mime)
543 if not mime.startswith("text/html"):
544 request.setHeader('content-disposition',
545 'attachment; filename=result%s'%formats.getExtensionFor(mime))
546 return streaming.streamOut(lambda f: f.write(payload),
547 request, self.queryMeta)
548
549 else:
550 if "response" in self.service.templates:
551 self.customTemplate = self.service.getTemplate("response")
552
553 nevowc.TemplatedPage.renderDocument(self, request
554 ).addErrback(weberrors.renderDCErrorPage, request
555 ).addCallback(request.finishCallback)
556 return server.NOT_DONE_YET
557
558 def getChild(self, name, request):
559 if name==b"":
560 # redirect so we're not a directory resource
561 raise svcs.WebRedirect(request.path.rstrip(b"/"))
562 else:
563 raise svcs.UnknownURI("Forms have no children")
564
565 defaultLoader = svcs.loadSystemTemplate("defaultresponse.html")