1# (C) Copyright 2005-2020 Enthought, Inc., Austin, TX
2# All rights reserved.
3#
4# This software is provided without warranty under the terms of the BSD
5# license included in LICENSE.txt and may be redistributed only under
6# the conditions described in the aforementioned license. The license
7# is also available online at http://www.enthought.com/licenses/BSD.txt
8#
9# Thanks for using Enthought open source!
10
11from traits.api import Constant, HasTraits, Instance
12
13from .action import Action
14
15
16class TraitsUIWidgetAction(Action):
17    """ A widget action containing a TraitsUI.
18
19    If a object is supplied, then the UI is generated from the object's view,
20    otherwise the ui is generated on using the Action object.
21
22    Notes
23    -----
24    This is currently only supported by the Qt backend.
25    """
26
27    # TraitsUIWidgetAction traits -------------------------------------------
28
29    #: The underlying traits model to be displayed, or None.
30    model = Instance(HasTraits)
31
32    # Action traits ---------------------------------------------------------
33
34    #: This is a widget action.
35    style = Constant("widget")
36
37    # ------------------------------------------------------------------------
38    # Action interface
39    # ------------------------------------------------------------------------
40
41    def create_control(self, parent):
42        """ Called when creating a "widget" style action.
43
44        This constructs an TraitsUI subpanel-based control.  It does no binding
45        to the `perform` method.
46
47        Parameters
48        ----------
49        parent : toolkit control
50            The toolkit control, usually a toolbar.
51
52        Returns
53        -------
54        control : toolkit control
55            A toolkit control or None.
56        """
57        ui = self.edit_traits(kind="subpanel", parent=parent)
58        control = ui.control
59        control._ui = ui
60        return control
61
62    # ------------------------------------------------------------------------
63    # HasTraits interface
64    # ------------------------------------------------------------------------
65
66    def trait_context(self):
67        """ Use the model object for the Traits UI context, if appropriate.
68        """
69        if self.model is not None:
70            context = {"object": self.model, "action": self}
71            return context
72        return super(TraitsUIWidgetAction, self).trait_context()
73