Scheduled service maintenance on November 22


On Friday, November 22, 2024, between 06:00 CET and 18:00 CET, GIN services will undergo planned maintenance. Extended service interruptions should be expected. We will try to keep downtimes to a minimum, but recommend that users avoid critical tasks, large data uploads, or DOI requests during this time.

We apologize for any inconvenience.

param_form_utils.py 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. from collections.abc import Callable
  2. import functools
  3. from itertools import (
  4. chain,
  5. )
  6. from pathlib import Path
  7. from typing import (
  8. Any,
  9. Dict,
  10. )
  11. from PySide6.QtWidgets import (
  12. QFormLayout,
  13. QLabel,
  14. QWidget,
  15. QFileDialog,
  16. )
  17. from datalad.interface.common_opts import eval_params
  18. from datalad.support.constraints import EnsureChoice
  19. from datalad.support.param import Parameter
  20. from datalad.utils import (
  21. get_wrapped_class,
  22. )
  23. from . import param_widgets as pw
  24. from .param_multival_widget import MultiValueInputWidget
  25. from .active_api import (
  26. api,
  27. exclude_parameters,
  28. parameter_display_names,
  29. )
  30. from .api_utils import get_cmd_params
  31. from .utils import _NoValue
  32. __all__ = ['populate_form_w_params']
  33. def populate_form_w_params(
  34. basedir: Path,
  35. formlayout: QFormLayout,
  36. cmdname: str,
  37. cmdkwargs: Dict) -> None:
  38. """Populate a given QLayout with data entry widgets for a DataLad command
  39. """
  40. # localize to potentially delay heavy import
  41. from datalad import api as dlapi
  42. # get the matching callable from the DataLad API
  43. cmd = getattr(dlapi, cmdname)
  44. cmd_api_spec = api.get(cmdname, {})
  45. cmd_param_display_names = cmd_api_spec.get(
  46. 'parameter_display_names', {})
  47. # resolve to the interface class that has all the specification
  48. cmd_cls = get_wrapped_class(cmd)
  49. # collect widgets for a later connection setup
  50. form_widgets = dict()
  51. # loop over all parameters of the command (with their defaults)
  52. def _specific_params():
  53. for pname, pdefault in get_cmd_params(cmd):
  54. yield pname, pdefault, cmd_cls._params_[pname]
  55. # loop over all generic
  56. def _generic_params():
  57. for pname, param in eval_params.items():
  58. yield (
  59. pname,
  60. param.cmd_kwargs.get('default', _NoValue), \
  61. param,
  62. )
  63. for pname, pdefault, param_spec in sorted(
  64. # across cmd params, and generic params
  65. chain(_specific_params(), _generic_params()),
  66. # sort by custom order and/or parameter name
  67. key=lambda x: (
  68. cmd_api_spec.get(
  69. 'parameter_order', {}).get(x[0], 99),
  70. x[0])):
  71. if pname in exclude_parameters:
  72. continue
  73. if pname in cmd_api_spec.get('exclude_parameters', set()):
  74. continue
  75. # populate the layout with widgets for each of them
  76. pwidget = _get_parameter_widget(
  77. basedir,
  78. formlayout.parentWidget(),
  79. param_spec,
  80. pname,
  81. # will also be _NoValue, if there was none
  82. pdefault,
  83. )
  84. form_widgets[pname] = pwidget
  85. # query for a known display name
  86. # first in command-specific spec
  87. display_name = cmd_param_display_names.get(
  88. pname,
  89. # fallback to API specific override
  90. parameter_display_names.get(
  91. pname,
  92. # last resort:
  93. # use capitalized orginal with _ removed as default
  94. pname.replace('_', ' ').capitalize()
  95. ),
  96. )
  97. display_label = QLabel(display_name)
  98. display_label.setToolTip(f'API command parameter: `{pname}`')
  99. formlayout.addRow(display_label, pwidget)
  100. # wire widgets up to self update on changes in other widget
  101. # use case: dataset context change
  102. # so it could be just the dataset widget sending, and the other receiving.
  103. # but for now wire all with all others
  104. for pname1, pwidget1 in form_widgets.items():
  105. for pname2, pwidget2 in form_widgets.items():
  106. if pname1 == pname2:
  107. continue
  108. pwidget1.value_changed.connect(
  109. pwidget2.init_gooey_from_other_param)
  110. # when all is wired up, set the values that need setting
  111. for pname, pwidget in form_widgets.items():
  112. if pname in cmdkwargs:
  113. pwidget.set_gooey_param_value(cmdkwargs[pname])
  114. #
  115. # Internal helpers
  116. #
  117. def _get_parameter_widget(
  118. basedir: Path,
  119. parent: QWidget,
  120. param: Parameter,
  121. name: str,
  122. default: Any = pw._NoValue) -> QWidget:
  123. """Populate a given layout with a data entry widget for a command parameter
  124. `value` is an explicit setting requested by the caller. A value of
  125. `_NoValue` indicates that there was no specific value given. `default` is a
  126. command's default parameter value, with `_NoValue` indicating that the
  127. command has no default for a parameter.
  128. """
  129. # guess the best widget-type based on the argparse setup and configured
  130. # constraints
  131. pwid_factory = _get_parameter_widget_factory(
  132. name,
  133. default,
  134. param.constraints,
  135. param.cmd_kwargs,
  136. basedir)
  137. return pw.load_parameter_widget(
  138. parent,
  139. pwid_factory,
  140. name=name,
  141. docs=param._doc,
  142. default=default,
  143. validator=param.constraints,
  144. )
  145. def _get_parameter_widget_factory(
  146. name: str,
  147. default: Any,
  148. constraints: Callable or None,
  149. argparse_spec: Dict,
  150. basedir: Path) -> Callable:
  151. """Translate DataLad command parameter specs into Gooey input widgets"""
  152. # for now just one to play with
  153. # TODO each factory must provide a standard widget method
  154. # to return the final value, ready to pass onto the respective
  155. # parameter of the command call
  156. argparse_action = argparse_spec.get('action')
  157. # we must consider the following action specs for widget selection
  158. # - 'store_const'
  159. # - 'store_true' and 'store_false'
  160. # - 'append'
  161. # - 'append_const'
  162. # - 'count'
  163. # - 'extend'
  164. #if name == 'path':
  165. # return get_pathselection_widget
  166. # if we have no idea, use a simple line edit
  167. type_widget = pw.StrParamWidget
  168. # no some parameters where we can derive semantics from their name
  169. if name == 'dataset':
  170. type_widget = functools.partial(
  171. pw.PathParamWidget,
  172. pathtype=QFileDialog.Directory,
  173. basedir=basedir)
  174. elif name == 'path':
  175. type_widget = functools.partial(
  176. pw.PathParamWidget, basedir=basedir)
  177. elif name == 'cfg_proc':
  178. type_widget = pw.CfgProcParamWidget
  179. # now parameters where we make decisions based on their configuration
  180. elif argparse_action in ('store_true', 'store_false'):
  181. type_widget = pw.BoolParamWidget
  182. elif isinstance(constraints, EnsureChoice) and argparse_action is None:
  183. type_widget = functools.partial(
  184. pw.ChoiceParamWidget, choices=constraints._allowed)
  185. elif argparse_spec.get('choices'):
  186. type_widget = functools.partial(
  187. pw.ChoiceParamWidget, choices=argparse_spec.get('choices'))
  188. elif name == 'recursion_limit':
  189. type_widget = functools.partial(pw.PosIntParamWidget, allow_none=True)
  190. # we must consider the following nargs spec for widget selection
  191. # (int, '*', '+'), plus action=append
  192. # in all these cases, we need to expect multiple instances of the data type
  193. # for which we have selected the input widget above
  194. argparse_nargs = argparse_spec.get('nargs')
  195. if (argparse_action == 'append'
  196. or argparse_nargs in ('+', '*')
  197. or isinstance(argparse_nargs, int)):
  198. type_widget = functools.partial(
  199. # TODO give a fixed N as a parameter too
  200. MultiValueInputWidget, type_widget)
  201. return type_widget