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 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  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.utils import (
  20. get_wrapped_class,
  21. )
  22. from . import param_widgets as pw
  23. from .param_multival_widget import MultiValueInputWidget
  24. from .active_suite import spec as active_suite
  25. from .api_utils import get_cmd_params
  26. from .utils import _NoValue
  27. from .constraints import (
  28. Constraint,
  29. EnsureExistingDirectory,
  30. EnsureDatasetSiblingName,
  31. )
  32. __all__ = ['populate_form_w_params']
  33. def populate_form_w_params(
  34. api,
  35. basedir: Path,
  36. formlayout: QFormLayout,
  37. cmdname: str,
  38. cmdkwargs: Dict) -> None:
  39. """Populate a given QLayout with data entry widgets for a DataLad command
  40. """
  41. # localize to potentially delay heavy import
  42. from datalad import api as dlapi
  43. # get the matching callable from the DataLad API
  44. cmd = getattr(dlapi, cmdname)
  45. cmd_api_spec = api.get(cmdname, {})
  46. cmd_param_display_names = cmd_api_spec.get(
  47. 'parameter_display_names', {})
  48. # resolve to the interface class that has all the specification
  49. cmd_cls = get_wrapped_class(cmd)
  50. # collect widgets for a later connection setup
  51. form_widgets = dict()
  52. def _get_nargs(pname, argparse_spec):
  53. # TODO we must consider the following action specs for widget selection
  54. # - 'store_const'
  55. # - 'store_true' and 'store_false'
  56. # - 'append'
  57. # - 'append_const'
  58. # - 'count'
  59. # - 'extend'
  60. if pname in cmd_api_spec.get('parameter_nargs', []):
  61. # take as gospel
  62. return cmd_api_spec['parameter_nargs'][pname]
  63. elif argparse_spec.get('action') == 'append':
  64. return '*'
  65. else:
  66. nargs = argparse_spec.get('nargs', None)
  67. try:
  68. nargs = int(nargs)
  69. except (ValueError, TypeError):
  70. pass
  71. return nargs
  72. # loop over all parameters of the command (with their defaults)
  73. def _specific_params():
  74. for pname, pdefault in get_cmd_params(cmd):
  75. yield pname, pdefault, cmd_cls._params_[pname]
  76. # loop over all generic
  77. def _generic_params():
  78. for pname, param in eval_params.items():
  79. yield (
  80. pname,
  81. param.cmd_kwargs.get('default', _NoValue), \
  82. param,
  83. )
  84. for pname, pdefault, param_spec in sorted(
  85. # across cmd params, and generic params
  86. chain(_specific_params(), _generic_params()),
  87. # sort by custom order and/or parameter name
  88. key=lambda x: (
  89. cmd_api_spec.get(
  90. 'parameter_order', {}).get(x[0], 99),
  91. x[0])):
  92. if pname in active_suite.get('exclude_parameters', []):
  93. continue
  94. if pname in cmd_api_spec.get('exclude_parameters', []):
  95. continue
  96. if pname in cmd_api_spec.get('parameter_constraints', []):
  97. # we have a better idea in gooey then what the original
  98. # command knows
  99. param_spec.constraints = \
  100. cmd_api_spec['parameter_constraints'][pname]
  101. # populate the layout with widgets for each of them
  102. # we do not pass Parameter instances further down, but disassemble
  103. # and homogenize here
  104. pwidget = _get_parameter_widget(
  105. basedir=basedir,
  106. parent=formlayout.parentWidget(),
  107. name=pname,
  108. constraints=cmd_api_spec['parameter_constraints'][pname]
  109. if pname in cmd_api_spec.get('parameter_constraints', [])
  110. else param_spec.constraints,
  111. nargs=_get_nargs(pname, param_spec.cmd_kwargs),
  112. # will also be _NoValue, if there was none
  113. default=pdefault,
  114. docs=param_spec._doc,
  115. # TODO make obsolete
  116. argparse_spec=param_spec.cmd_kwargs,
  117. )
  118. form_widgets[pname] = pwidget
  119. # query for a known display name
  120. # first in command-specific spec
  121. display_name = cmd_param_display_names.get(
  122. pname,
  123. # fallback to API specific override
  124. active_suite.get('parameter_display_names', {}).get(
  125. pname,
  126. # last resort:
  127. # use capitalized orginal with _ removed as default
  128. pname.replace('_', ' ').capitalize()
  129. ),
  130. )
  131. display_label = QLabel(display_name)
  132. display_label.setToolTip(f'API command parameter: `{pname}`')
  133. formlayout.addRow(display_label, pwidget)
  134. # wire widgets up to self update on changes in other widget
  135. # use case: dataset context change
  136. # so it could be just the dataset widget sending, and the other receiving.
  137. # but for now wire all with all others
  138. for pname1, pwidget1 in form_widgets.items():
  139. for pname2, pwidget2 in form_widgets.items():
  140. if pname1 == pname2:
  141. continue
  142. pwidget1.value_changed.connect(
  143. pwidget2.init_gooey_from_other_param)
  144. # when all is wired up, set the values that need setting
  145. for pname, pwidget in form_widgets.items():
  146. if pname in cmdkwargs:
  147. pwidget.set_gooey_param_value(cmdkwargs[pname])
  148. #
  149. # Internal helpers
  150. #
  151. def _get_parameter_widget(
  152. basedir: Path,
  153. parent: QWidget,
  154. name: str,
  155. constraints: Constraint,
  156. nargs: int or str,
  157. default: Any = pw._NoValue,
  158. docs: str = '',
  159. argparse_spec: Dict = None) -> QWidget:
  160. """Populate a given layout with a data entry widget for a command parameter
  161. `value` is an explicit setting requested by the caller. A value of
  162. `_NoValue` indicates that there was no specific value given. `default` is a
  163. command's default parameter value, with `_NoValue` indicating that the
  164. command has no default for a parameter.
  165. """
  166. # guess the best widget-type based on the argparse setup and configured
  167. # constraints
  168. pwid_factory = _get_parameter_widget_factory(
  169. name,
  170. default,
  171. constraints,
  172. nargs,
  173. basedir,
  174. # TODO make obsolete
  175. argparse_spec)
  176. return pw.load_parameter_widget(
  177. parent,
  178. pwid_factory,
  179. name=name,
  180. docs=docs,
  181. default=default,
  182. validator=constraints,
  183. )
  184. def _get_parameter_widget_factory(
  185. name: str,
  186. default: Any,
  187. constraints: Callable or None,
  188. nargs: int or str,
  189. basedir: Path,
  190. # TODO make obsolete
  191. argparse_spec: Dict) -> Callable:
  192. """Translate DataLad command parameter specs into Gooey input widgets"""
  193. if argparse_spec is None:
  194. argparse_spec = {}
  195. argparse_action = argparse_spec.get('action')
  196. # if we have no idea, use a simple line edit
  197. type_widget = pw.StrParamWidget
  198. # now some parameters where we can derive semantics from their name
  199. if name == 'dataset' or isinstance(constraints, EnsureExistingDirectory):
  200. type_widget = functools.partial(
  201. pw.PathParamWidget,
  202. pathtype=QFileDialog.Directory,
  203. disable_manual_edit=active_suite.get('options', {}).get(
  204. 'disable_manual_path_input', False),
  205. basedir=basedir)
  206. elif name == 'path':
  207. type_widget = functools.partial(
  208. pw.PathParamWidget, basedir=basedir)
  209. elif name == 'cfg_proc':
  210. type_widget = pw.CfgProcParamWidget
  211. elif name == 'recursion_limit':
  212. type_widget = functools.partial(pw.PosIntParamWidget, allow_none=True)
  213. # now parameters where we make decisions based on their configuration
  214. elif isinstance(constraints, EnsureDatasetSiblingName):
  215. type_widget = pw.SiblingChoiceParamWidget
  216. # TODO ideally the suite API would normalize this to a EnsureBool
  217. # constraint
  218. elif argparse_action in ('store_true', 'store_false'):
  219. type_widget = pw.BoolParamWidget
  220. elif isinstance(constraints, EnsureChoice) and argparse_action is None:
  221. type_widget = functools.partial(
  222. pw.ChoiceParamWidget, choices=constraints._allowed)
  223. # TODO ideally the suite API would normalize this to a EnsureChoice
  224. # constraint
  225. elif argparse_spec.get('choices'):
  226. type_widget = functools.partial(
  227. pw.ChoiceParamWidget, choices=argparse_spec.get('choices'))
  228. # we must consider the following nargs spec for widget selection
  229. # (int, '*', '+'), plus action=append
  230. # in all these cases, we need to expect multiple instances of the data type
  231. # for which we have selected the input widget above
  232. if isinstance(nargs, int):
  233. # we have a concrete number
  234. if nargs > 1:
  235. type_widget = functools.partial(
  236. # TODO give a fixed N as a parameter too
  237. MultiValueInputWidget, type_widget)
  238. else:
  239. if nargs in ('+', '*') or argparse_action == 'append':
  240. type_widget = functools.partial(
  241. MultiValueInputWidget, type_widget)
  242. return type_widget