Example #1
0
class ServiceOffer(HasTraits):
    """ An offer to provide a service. """

    #### 'ServiceOffer' interface #############################################

    #: The protocol that the service provides.
    #:
    #: This can be an actual class or interface, or a string that can be used
    #: to import a class or interface.
    #:
    #: e.g. 'foo.bar.baz.Baz' is turned into 'from foo.bar.baz import Baz'
    protocol = Union(Str, Type)

    #: A callable (or a string that can be used to import a callable) that is
    #: the factory that creates the actual service object.
    #:
    #: e.g::
    #:
    #:   callable(**properties) -> Any
    #:
    #: e.g. 'foo.bar.baz.Baz' is turned into 'from foo.bar.baz import Baz'
    factory = Union(Str, Callable)

    #: An optional set of properties to associate with the service offer.
    #:
    #: This dictionary is passed as keyword arguments to the factory.
    properties = Dict
Example #2
0
class BoundsEditor(RangeEditor):

    min = Union(None, Float)
    max = Union(None, Float)

    def _get_simple_editor_class(self):
        return _BoundsEditor

    def _get_custom_editor_class(self):
        return _BoundsEditor
Example #3
0
class ITimer(Interface):
    """ Interface for timer classes.

    This is a base interface which doesn't specify any particular notification
    mechanism.
    """

    # ITimer interface -------------------------------------------------------

    #: The interval at which to call the callback in seconds.
    interval = Range(low=0.0)

    #: The number of times to repeat the callback, or None if no limit.
    repeat = Union(None, Int)

    #: The maximum length of time to run in seconds, or None if no limit.
    expire = Union(None, Float)

    #: Whether or not the timer is currently running.
    active = Bool()

    # -------------------------------------------------------------------------
    # ITimer interface
    # -------------------------------------------------------------------------

    @classmethod
    def timer(cls, **traits):
        """ Convenience method that creates and starts a timer.
        """
        pass

    @classmethod
    def single_shot(cls, **traits):
        """ Convenience method that creates and starts a single-shot timer.
        """
        pass

    def start(self):
        """ Start the timer. """
        pass

    def stop(self):
        """ Stop the timer. """
        pass

    def perform(self):
        """ The method that will be called by the timer. """
        pass
Example #4
0
 class TestClass(HasTraits):
     atr = Union(
         Int(3),
         Float(4.1),
         Str("Something"),
         default_value="XYZ",
     )
Example #5
0
class DockLayout(LayoutItem):
    """ The layout for a main window's dock area.
    """

    # The layouts for the task's dock panes.
    left = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter))
    right = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter))
    top = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter))
    bottom = Union(Instance(PaneItem), Instance(Tabbed), Instance(Splitter))

    #: Assignments of dock areas to the window's corners. By default, the top
    #: and bottom dock areas extend into both of the top and both of the
    #: bottom corners, respectively.
    top_left_corner = Enum("top", "left")
    top_right_corner = Enum("top", "right")
    bottom_left_corner = Enum("bottom", "left")
    bottom_right_corner = Enum("bottom", "right")
Example #6
0
class TraitGridSelection(HasTraits):
    """ Structure for holding specification information. """

    # The selected object
    obj = Instance(HasTraits)

    # The specific trait selected on the object
    trait_name = Union(None, Str)
Example #7
0
    def test_union_incompatible_trait(self):
        with self.assertRaises(ValueError) as exception_context:
            Union(Str(), "none")

        self.assertEqual(
            str(exception_context.exception),
            "Union trait declaration expects a trait type or an instance of "
            "trait type or None, but got 'none' instead")
Example #8
0
class Tabbed(LayoutContainer):
    """ A tab area in a Task layout.
    """

    #: A tabbed layout can only contain PaneItems as sub-items. Splitters and
    #: other Tabbed layouts are not allowed.
    items = List(PaneItem, pretty_skip=True)

    #: The ID of the TaskPane which is active in layout. If not specified, the
    #: first pane is active.
    active_tab = Union(Str, Int, default_value="")
class ObjectWithEqualityComparisonMode(HasTraits):
    """ Class for supporting TestHasTraitsHelpersWarning """

    list_values = List(comparison_mode=2)
    dict_values = Dict(comparison_mode=2)
    set_values = Set(comparison_mode=2)
    property_list = Property(List(comparison_mode=2))
    container_in_union = Union(
        None,
        Set(comparison_mode=1),
        comparison_mode=2,
    )
Example #10
0
    def test_default_raise_error(self):
        # If 'default' is defined, it could be caused by migration from
        # ``Either``. Raise an error to aid migrations from ``Either``
        # to ``Union``

        with self.assertRaises(ValueError) as exception_context:
            Union(Int(), Float(), default=1.0)

        self.assertEqual(
            str(exception_context.exception),
            "Union default value should be set via 'default_value', not "
            "'default'.")
Example #11
0
class TraitGridColumn(GridColumn):
    """ Structure for holding column specifications in a TraitGridModel. """

    # The trait name for this column. This takes precedence over method
    name = Union(None, Str)

    # A method name to call to get the value for this column
    method = Union(None, Str)

    # A method to be used to sort on this column
    sorter = Callable

    # A dictionary of formats for the display of different types. If it is
    # defined as a callable, then that callable must accept a single argument.
    formats = Dict(Type, Union(Str, Callable))

    # A name to designate the type of this column
    typename = Union(None, Str)
    # note: context menus should go in here as well? but we need
    #       more info than we have available at this point

    size = Int(-1)
Example #12
0
class Splitter(LayoutContainer):
    """ A split area in a Task layout.
    """

    #: The orientation of the splitter.
    orientation = Enum("horizontal", "vertical")

    #: The sub-items of the splitter, which are PaneItems, Tabbed layouts, and
    #: other Splitters.
    items = List(
        Union(
            Instance(PaneItem),
            Instance(Tabbed),
            Instance("pyface.tasks.task_layout.Splitter"),
        ),
        pretty_skip=True,
    )
Example #13
0
class TaskWindowLayout(LayoutContainer):
    """ The layout of a TaskWindow.
    """

    #: The ID of the active task. If unspecified, the first task will be
    #: active.
    active_task = Str()

    #: The tasks contained in the window. If an ID is specified, the task will
    #: use its default layout. Otherwise, it will use the specified TaskLayout
    items = List(Union(Str, Instance(TaskLayout)), pretty_skip=True)

    #: The position of the window.
    position = Tuple(-1, -1)

    #: The size of the window.
    size = Tuple(800, 600)

    #: Whether or not the application is maximized.
    size_state = Enum("normal", "maximized")

    def get_active_task(self):
        """ Returns the ID of the active task in the layout, or None if there is
            no active task.
        """
        if self.active_task:
            return self.active_task
        elif self.items:
            first = self.items[0]
            return first if isinstance(first, str) else first.id
        return None

    def get_tasks(self):
        """ Returns the IDs of the tasks in the layout.
        """
        return [(item if isinstance(item, str) else item.id)
                for item in self.items]

    def is_equivalent_to(self, layout):
        """ Returns whether two layouts are equivalent, i.e. whether they
            contain the same tasks.
        """
        return isinstance(layout, TaskWindowLayout) and set(
            self.get_tasks()) == set(layout.get_tasks())
Example #14
0
def CVType(type, **metadata):
    """Factory that creates a union of a trait type and a ContextValue trait.

    This also sets up one-way synchronization to the editor if no
    other synchronization is specified.

    Parameters
    ----------
    type : trait type
        The trait type that is expected for constant values.
    **metadata
        Additional metadata for the trait.

    Returns
    -------
    cv_type_trait : trait
        A trait which can either hold a constant of the specified
        type or an instance of the ContextValue class.
    """
    metadata.setdefault("sync_value", "to")
    return Union(type, InstanceOfContextValue, **metadata)
Example #15
0
class PaneItem(LayoutItem):
    """ A pane in a Task layout.
    """

    #: The ID of the item. If the item refers to a TaskPane, this is the ID of
    #: that TaskPane.
    id = Union(Str, Int, default_value="", pretty_skip=True)

    #: The width of the pane in pixels. If not specified, the pane will be
    #: sized according to its size hint.
    width = Int(-1)

    #: The height of the pane in pixels. If not specified, the pane will be
    #: sized according to its size hint.
    height = Int(-1)

    def __init__(self, id="", **traits):
        super().__init__(**traits)
        self.id = id

    def pargs(self):
        return [self.id]
Example #16
0
class CompoundEditorDemo(HasTraits):
    """Defines the main CompoundEditor demo class."""

    # Define a compound trait to view:
    compound_trait = Union(Range(1, 6),
                           Enum('a', 'b', 'c', 'd', 'e', 'f'),
                           default_value=1)

    # Display specification (one Item per editor style):
    comp_group = Group(
        Item('compound_trait', style='simple', label='Simple'),
        Item('_'),
        Item('compound_trait', style='custom', label='Custom'),
        Item('_'),
        Item('compound_trait', style='text', label='Text'),
        Item('_'),
        Item('compound_trait', style='readonly', label='ReadOnly'),
    )

    # Demo view:
    traits_view = View(comp_group,
                       title='CompoundEditor',
                       buttons=['OK'],
                       resizable=True)
Example #17
0
 class TestClass(HasTraits):
     atr = Union(Int(3), Float(4.1), Str("Something"))
Example #18
0
 class TestClass(HasTraits):
     none = Union()
Example #19
0
 class TestClass(HasTraits):
     int_or_none = Union(None, Int)
Example #20
0
 class TestClass(HasTraits):
     float_or_str_obj = Union(Instance(Float), Instance(Str))
Example #21
0
class BaseTimer(ABCHasTraits):
    """ Base class for timer classes.

    This class has a class variable which tracks active timers to prevent
    failures caused by garbage collection.  A timer is added to this tracker
    when it is started if the repeat value is not None.
    """

    # BaseTimer interface ----------------------------------------------------

    #: Class variable tracking all active timers.
    _active_timers = set()

    # ITimer interface -------------------------------------------------------

    #: The interval at which to call the callback in seconds.
    interval = Range(low=0.0, value=0.05)

    #: The number of times to repeat the callback, or None if no limit.
    repeat = Union(None, Int)

    #: The maximum length of time to run in seconds, or None if no limit.
    expire = Union(None, Float)

    #: Property that controls the state of the timer.
    active = Property(Bool, observe="_active")

    # Private interface ------------------------------------------------------

    #: Whether or not the timer is currently running.
    _active = Bool()

    #: The most recent start time.
    _start_time = Float()

    # -------------------------------------------------------------------------
    # ITimer interface
    # -------------------------------------------------------------------------

    @classmethod
    def timer(cls, **traits):
        """ Convenience method that creates and starts a timer.
        """
        timer = cls(**traits)
        timer.start()
        return timer

    @classmethod
    def single_shot(cls, **traits):
        timer = cls(repeat=1, **traits)
        timer.start()
        return timer

    def start(self):
        """ Start the timer. """
        if not self._active:
            if self.repeat is not None:
                self._active_timers.add(self)
            if self.expire is not None:
                self._start_time = perf_counter()
            self._active = True
            self._start()

    def stop(self):
        """ Stop the timer. """
        if self._active:
            self._active_timers.discard(self)
            self._stop()
            self._active = False

    def perform(self):
        """ Perform the callback.

        The timer will stop if repeats is not None and less than 1, or if
        the `_perform` method raises StopIteration.
        """
        if self.expire is not None:
            if perf_counter() - self._start_time > self.expire:
                self.stop()
                return

        if self.repeat is not None:
            self.repeat -= 1

        try:
            self._perform()
        except StopIteration:
            self.stop()
        except:
            self.stop()
            raise
        else:
            if self.repeat is not None and self.repeat <= 0:
                self.stop()
                self.repeat = 0

    # BaseTimer Protected methods

    def _start(self):
        """ Start the toolkit timer.

        Subclasses should overrided this method.
        """
        raise NotImplementedError()

    def _stop(self):
        """ Stop the toolkit timer.

        Subclasses should overrided this method.
        """
        raise NotImplementedError()

    @abstractmethod
    def _perform(self):
        """ perform the appropriate action.

        Subclasses should overrided this method.
        """
        raise NotImplementedError()

    # -------------------------------------------------------------------------
    # Private interface
    # -------------------------------------------------------------------------

    # Trait property handlers ------------------------------------------------

    def _get_active(self):
        return self._active

    def _set_active(self, value):
        if value:
            self.start()
        else:
            self.stop()
Example #22
0
class ConstantValue(AbstractValueType):
    """ A value type that does not depend on the underlying data model.

    This value type is not editable, but the other data channels it
    provides can be modified by changing the appropriate trait on the
    value type.
    """

    #: The text value to display.
    text = Str(update_value_type=True)

    #: The color value to display or None if no color.
    color = Union(None, PyfaceColor)

    #: The image value to display.
    image = Image(update_value_type=True)

    #: The tooltip value to display.
    tooltip = Str(update_value_type=True)

    def has_editor_value(self, model, row, column):
        return False

    def get_text(self, model, row, column):
        return self.text

    def has_color(self, model, row, column):
        """ Whether or not the value has color data.

        Returns true if the supplied color is not None.

        Parameters
        ----------
        model : AbstractDataModel
            The data model holding the data.
        row : sequence of int
            The row in the data model being queried.
        column : sequence of int
            The column in the data model being queried.

        Returns
        -------
        has_color : bool
            Whether or not the value has data-associated color
            values.
        """
        return self.color is not None

    def get_color(self, model, row, column):
        """ Get data-associated colour values for the given item.

        The default implementation returns white.

        Parameters
        ----------
        model : AbstractDataModel
            The data model holding the data.
        row : sequence of int
            The row in the data model being queried.
        column : sequence of int
            The column in the data model being queried.

        Returns
        -------
        color : Color instance
            The color associated with the cell.
        """
        return self.color

    def has_image(self, model, row, column):
        return self.image is not None

    def get_image(self, model, row, column):
        if self.image is not None:
            return self.image
        return super().get_image(model, row, column)

    def get_tooltip(self, model, row, column):
        return self.tooltip

    @observe('color.rgba')
    def _color_updated(self, event):
        self.updated = True
Example #23
0
 class TestClass(HasTraits):
     type_value = Union(CustomStrType, Int)
Example #24
0
 class TestClass(HasTraits):
     obj = Union(Instance(CustomClass), Int)
Example #25
0
class CSVListEditor(TextEditor):
    """A text editor for a List.

    This editor provides a single line of input text of comma separated
    values.  (Actually, the default separator is a comma, but this can
    changed.)  The editor can only be used with List traits whose inner
    trait is one of Int, Float, Str, Enum, or Range.

    The 'simple', 'text', 'custom' and readonly styles are based on
    TextEditor. The 'readonly' style provides the same formatting in the
    text field as the other editors, but the user cannot change the value.

    Like other Traits editors, the background of the text field will turn
    red if the user enters an incorrectly formatted list or if the values
    do not match the type of the inner trait.  This validation only occurs
    while editing the text field.  If, for example, the inner trait is
    Range(low='lower', high='upper'), a change in 'upper' will not trigger
    the validation code of the editor.

    The editor removes whitespace of entered items with strip(), so for
    Str types, the editor should not be used if whitespace at the beginning
    or end of the string must be preserved.

    Parameters
    ----------
    sep : str or None, optional
        The separator of the values in the list.  If None, each contiguous
        sequence of whitespace is a separator.
        Default is ','.

    ignore_trailing_sep : bool, optional
        If this is False, a line containing a trailing separator is invalid.
        Default is True.

    auto_set : bool
        If True, then every keystroke sets the value of the trait.

    enter_set : bool
        If True, the user input sets the value when the Enter key is pressed.

    Example
    -------
    The following will display a window containing a single input field.
    Entering, say, '0, .5, 1' in this field will result in the list
    x = [0.0, 0.5, 1.0].
    """

    #: The separator of the element in the list.
    sep = Union(None, Str, default_value=",")

    #: If False, it is an error to have a trailing separator.
    ignore_trailing_sep = Bool(True)

    #: Include some of the TextEditor API:

    #: Is user input set on every keystroke?
    auto_set = Bool(True)

    #: Is user input set when the Enter key is pressed?
    enter_set = Bool(False)

    def _funcs(self, object, name):
        """Create the evalution and formatting functions for the editor.

        Parameters
        ----------
        object : instance of HasTraits
            This is the object that has the List trait for which we are
            creating an editor.

        name : str
            Name of the List trait on `object`.

        Returns
        -------
        evaluate, fmt_func : callable, callable
            The functions for converting a string to a list (`evaluate`)
            and a list to a string (`fmt_func`).  These are the functions
            that are ultimately given as the keyword arguments 'evaluate'
            and 'format_func' of the TextEditor that will be generated by
            the CSVListEditor editor factory functions.
        """
        t = getattr(object, name)
        # Get the list of inner traits.  Only a single inner trait is allowed.
        it_list = t.trait.inner_traits()
        if len(it_list) > 1:
            raise TraitError("Only one inner trait may be specified when "
                             "using a CSVListEditor.")

        # `it` is the single inner trait.  This will be an instance of
        # traits.traits.CTrait.
        it = it_list[0]
        # The following 'if' statement figures out the appropriate evaluation
        # function (evaluate) and formatting function (fmt_func) for the
        # given inner trait.
        if (it.is_trait_type(Int) or it.is_trait_type(Float)
                or it.is_trait_type(Str)):
            evaluate = lambda s: _eval_list_str(
                s,
                sep=self.sep,
                item_eval=it.trait_type.evaluate,
                ignore_trailing_sep=self.ignore_trailing_sep,
            )
            fmt_func = lambda vals: _format_list_str(vals, sep=self.sep)
        elif it.is_trait_type(Enum):
            values, mapping, inverse_mapping = enum_values_changed(it)
            evaluate = lambda s: _eval_list_str(
                s,
                sep=self.sep,
                item_eval=mapping.__getitem__,
                ignore_trailing_sep=self.ignore_trailing_sep,
            )
            fmt_func = lambda vals: _format_list_str(
                vals, sep=self.sep, item_format=inverse_mapping.__getitem__)
        elif it.is_trait_type(Range):
            # Get the type of the values from the default value.
            # range_object will be an instance of traits.trait_types.Range.
            range_object = it.handler
            if range_object.default_value_type == 8:
                # range_object.default_value is callable.
                defval = range_object.default_value(object)
            else:
                # range_object.default_value *is* the default value.
                defval = range_object.default_value
            typ = type(defval)

            if range_object.validate is None:
                # This will be the case for dynamic ranges.
                item_eval = lambda s: _validate_range_value(
                    range_object, object, name, typ(s))
            else:
                # Static ranges have a validate method.
                item_eval = lambda s: range_object.validate(
                    object, name, typ(s))

            evaluate = lambda s: _eval_list_str(
                s,
                sep=self.sep,
                item_eval=item_eval,
                ignore_trailing_sep=self.ignore_trailing_sep,
            )
            fmt_func = lambda vals: _format_list_str(vals, sep=self.sep)
        else:
            raise TraitError("To use a CSVListEditor, the inner trait of the "
                             "List must be Int, Float, Range, Str or Enum.")

        return evaluate, fmt_func

    def simple_editor(self, ui, object, name, description, parent):
        """Generates an editor using the "simple" style."""
        self.evaluate, self.format_func = self._funcs(object, name)
        return self.simple_editor_class(
            parent,
            factory=self,
            ui=ui,
            object=object,
            name=name,
            description=description,
        )

    def custom_editor(self, ui, object, name, description, parent):
        """Generates an editor using the "custom" style."""
        self.evaluate, self.format_func = self._funcs(object, name)
        return self.custom_editor_class(
            parent,
            factory=self,
            ui=ui,
            object=object,
            name=name,
            description=description,
        )

    def text_editor(self, ui, object, name, description, parent):
        """Generates an editor using the "text" style."""
        self.evaluate, self.format_func = self._funcs(object, name)
        return self.text_editor_class(
            parent,
            factory=self,
            ui=ui,
            object=object,
            name=name,
            description=description,
        )

    def readonly_editor(self, ui, object, name, description, parent):
        """Generates an "editor" that is read-only."""
        self.evaluate, self.format_func = self._funcs(object, name)
        return self.readonly_editor_class(
            parent,
            factory=self,
            ui=ui,
            object=object,
            name=name,
            description=description,
        )
Example #26
0
 class TestClass(HasTraits):
     int_or_str_type = Union(Type, Int, Str)
 class MyNewCallable2(HasTraits):
     value = Callable(pow, allow_none=True)
     empty_callable = Callable()
     a_non_none_union = Union(Callable(allow_none=False), Int)
     a_allow_none_union = Union(Callable(allow_none=True), Int)
Example #28
0
 class TestClass(HasTraits):
     a = Union(int, Float)
Example #29
0
        class TestClass(HasTraits):
            union_attr = Union(Int)
            shadow_union_trait = None

            def _union_attr_changed(self, new):
                self.shadow_union_trait = new
Example #30
0
 class TestClass(HasTraits):
     a = Union([1, 2], Float)