param_form_utils.py 7.8 KB

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