Пример #1
0
    def update_object(self, event):
        """ Handles the user selecting a new value from the combo box.
        """
        self._no_enum_update += 1
        try:
            new_value = self.mapping[event.GetString()]
            if new_value == self.value and self.factory.is_grid_cell:
                # If the enum editor is in a grid cell and the value did not
                # change, we want the enum editor to go away, reverting back to
                # the normal cell appearance. This is for 2 reasons:
                #  1. it looks nicer
                #  2. if the grid id suddenly closed, wx freaks & causes a
                #     segfault

                grid = self.control.Parent.Parent
                grid.EnableEditing(False)
                grid.EnableEditing(True)

            self.value = new_value

        except:
            from traitsui.api import raise_to_debug

            raise_to_debug()

        self._no_enum_update -= 1
Пример #2
0
    def can_add_to_menu(self, action):
        """ Returns whether the action should be defined in the user interface.
        """
        if action.defined_when != '':

            try:
                if not eval(
                        action.defined_when,
                        globals(),
                        self._menu_context):
                    return False
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

        if action.visible_when != '':
            try:
                if not eval(
                        action.visible_when,
                        globals(),
                        self._menu_context):
                    return False
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

        return True
Пример #3
0
    def _perform(self, action):
        method_name = action.action
        info = self._menu_context['info']
        handler = self._menu_context['handler']
        object = self._menu_context['object']
        selection = self._menu_context['selection']
        self._menu_context['action'] = action

        if method_name.find('.') >= 0:
            if method_name.find('(') < 0:
                method_name += '()'
            try:
                eval(method_name, globals(), self._menu_context)
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()
            return

        method = getattr(handler, method_name, None)
        if method is not None:
            method(info, selection)
            return

        if action.on_perform is not None:
            action.on_perform(selection)

        action.perform(selection)
Пример #4
0
 def redo(self):
     """ Re-does the change.
     """
     try:
         setattr(self.object, self.name, self.new_value)
     except Exception:
         from traitsui.api import raise_to_debug
         raise_to_debug()
Пример #5
0
    def undo(self):
        """ Undoes the change.
        """
        try:
            setattr(self.object, self.name, self.old_value)
        except Exception:
            from traitsui.api import raise_to_debug

            raise_to_debug()
Пример #6
0
 def get_raw_value(self, object):
     """ Gets the unformatted value of the column for a specified object.
     """
     try:
         return xgetattr(self.get_object(object), self.name)
     except Exception as e:
         from traitsui.api import raise_to_debug
         raise_to_debug()
         return None
Пример #7
0
 def redo(self):
     """ Re-does the change.
     """
     try:
         list = getattr(self.object, self.name)
         list[self.index: (self.index + len(self.removed))] = self.added
     except Exception:
         from traitsui.api import raise_to_debug
         raise_to_debug()
Пример #8
0
    def redo(self):
        """Re-does the change."""
        try:
            list = getattr(self.object, self.name)
            list[self.index:(self.index + len(self.removed))] = self.added
        except Exception:
            from traitsui.api import raise_to_debug

            raise_to_debug()
Пример #9
0
 def get_raw_value(self, object):
     """ Gets the unformatted value of the column for a specified object.
     """
     try:
         return xgetattr(self.get_object(object), self.name)
     except Exception as e:
         from traitsui.api import raise_to_debug
         raise_to_debug()
         return None
Пример #10
0
 def update_object_on_scroll(self, pos):
     """ Handles the user changing the current slider value.
     """
     value = self._convert_from_slider(pos)
     self.control.text.setText(self.format % value)
     try:
         self.value = value
     except Exception as exc:
         from traitsui.api import raise_to_debug
         raise_to_debug()
Пример #11
0
 def update_object_on_scroll(self, pos):
     """ Handles the user changing the current slider value.
     """
     value = self._convert_from_slider(pos)
     self.control.text.setText(self.format % value)
     try:
         self.value = value
     except Exception as exc:
         from traitsui.api import raise_to_debug
         raise_to_debug()
Пример #12
0
 def update_object(self, text):
     """ Handles the user selecting a new value from the combo box.
     """
     if self._no_enum_update == 0:
         self._no_enum_update += 1
         try:
             self.value = self.mapping[six.text_type(text)]
         except Exception:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         self._no_enum_update -= 1
Пример #13
0
 def editor_trait_modified ( new ):
     # Need this to include 'user_object' in closure:
     user_object
     if key not in self._no_trait_update:
         self._no_trait_update[ key ] = None
         try:
             setattr( eval( user_ref ), user_name, new )
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         del self._no_trait_update[ key ]
Пример #14
0
 def update_object(self, text):
     """ Handles the user selecting a new value from the combo box.
     """
     if self._no_enum_update == 0:
         self._no_enum_update += 1
         try:
             self.value = self.mapping[unicode(text)]
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         self._no_enum_update -= 1
Пример #15
0
 def editor_trait_modified(new):
     # Need this to include 'user_object' in closure:
     user_object
     if key not in self._no_trait_update:
         self._no_trait_update[key] = None
         try:
             setattr(eval(user_ref), user_name, new)
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         del self._no_trait_update[key]
Пример #16
0
 def user_list_modified ( event ):
     if isinstance( event, TraitListEvent ):
         if key not in self._no_trait_update:
             self._no_trait_update[ key ] = None
             n = event.index
             try:
                 getattr( self, editor_name )[
                     n: n + len(event.removed)] = event.added
             except:
                 from traitsui.api import raise_to_debug
                 raise_to_debug()
             del self._no_trait_update[ key ]
Пример #17
0
 def _selected_changed(self, new):
     if not self._no_update:
         if new is None:
             self._selected_row_changed(-1)
         else:
             try:
                 selected_row = self.value.index(new)
             except Exception:
                 from traitsui.api import raise_to_debug
                 raise_to_debug()
             else:
                 self._selected_row_changed(selected_row)
Пример #18
0
 def user_list_modified(event):
     if isinstance(event, TraitListEvent):
         if key not in self._no_trait_update:
             self._no_trait_update[key] = None
             n = event.index
             try:
                 getattr(self, editor_name)[
                     n: n + len(event.removed)] = event.added
             except:
                 from traitsui.api import raise_to_debug
                 raise_to_debug()
             del self._no_trait_update[key]
Пример #19
0
    def update_object(self, index):
        """Handles the user selecting a new value from the combo box."""
        if self._no_enum_update == 0:
            self._no_enum_update += 1
            try:
                text = self.names[index]
                self.value = self.mapping[text]
            except Exception:
                from traitsui.api import raise_to_debug

                raise_to_debug()
            self._no_enum_update -= 1
Пример #20
0
 def _selected_changed(self, new):
     if not self._no_update:
         if new is None:
             self._selected_row_changed(-1)
         else:
             try:
                 selected_row = self.value.index(new)
             except Exception:
                 from traitsui.api import raise_to_debug
                 raise_to_debug()
             else:
                 self._selected_row_changed(selected_row)
Пример #21
0
    def update_object_on_scroll(self, pos):
        """Handles the user changing the current slider value."""
        value = self._convert_from_slider(pos)
        blocked = self.control.text.blockSignals(True)
        try:
            self.value = value
            self.control.text.setText(self.string_value(value))
        except TraitError as exc:
            from traitsui.api import raise_to_debug

            raise_to_debug()
        finally:
            self.control.text.blockSignals(blocked)
Пример #22
0
 def editor_list_modified ( event ):
     # Need this to include 'user_object' in closure:
     user_object
     if key not in self._no_trait_update:
         self._no_trait_update[ key ] = None
         n = event.index
         try:
             eval( user_value )[ n:
                 n + len( event.removed ) ] = event.added
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         del self._no_trait_update[ key ]
Пример #23
0
 def update_editor(self):
     """ Updates the editor when the object trait changes externally to the
         editor.
     """
     if not self._locked:
         blocked = self.control.blockSignals(True)
         try:
             self.control.setValue(int(self.value))
         except Exception:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         finally:
             self.control.blockSignals(blocked)
Пример #24
0
 def update_editor(self):
     """ Updates the editor when the object trait changes externally to the
         editor.
     """
     if not self._locked:
         blocked = self.control.blockSignals(True)
         try:
             self.control.setValue(int(self.value))
         except Exception:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         finally:
             self.control.blockSignals(blocked)
Пример #25
0
 def editor_list_modified(event):
     # Need this to include 'user_object' in closure:
     user_object
     if key not in self._no_trait_update:
         self._no_trait_update[key] = None
         n = event.index
         try:
             eval(user_value
                  )[n:n + len(event.removed)] = event.added
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         del self._no_trait_update[key]
Пример #26
0
 def eval_when(self, condition, object, trait):
     """ Evaluates a condition within a defined context, and sets a
     specified object trait based on the result, which is assumed to be a
     Boolean.
     """
     if condition != '':
         value = True
         try:
             if not eval(condition, globals(), self._menu_context):
                 value = False
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         setattr(object, trait, value)
Пример #27
0
    def eval_when(self, when, result=True):
        """ Evaluates an expression in the UI's **context** and returns the
            result.
        """
        context = self._get_context(self.context)
        try:
            result = eval(when, globals(), context)
        except:
            from traitsui.api import raise_to_debug
            raise_to_debug()

        del context['ui']

        return result
Пример #28
0
 def eval_when(self, condition, object, trait):
     """ Evaluates a condition within a defined context, and sets a
     specified object trait based on the result, which is assumed to be a
     Boolean.
     """
     if condition != '':
         value = True
         try:
             if not eval(condition, globals(), self._menu_context):
                 value = False
         except:
             from traitsui.api import raise_to_debug
             raise_to_debug()
         setattr(object, trait, value)
Пример #29
0
    def eval_when(self, when, result=True):
        """ Evaluates an expression in the UI's **context** and returns the
            result.
        """
        context = self._get_context(self.context)
        try:
            result = eval(when, globals(), context)
        except:
            from traitsui.api import raise_to_debug
            raise_to_debug()

        del context['ui']

        return result
Пример #30
0
    def _evaluate_condition ( self, conditions, trait ):
        """ Evaluates a list of (eval,editor) pairs and sets a specified trait
        on each editor to reflect the Boolean value of the expression.
        """
        context = self._get_context( self.context )
        for when, editor in conditions:
            value = True
            try:
                if not eval( when, globals(), context ):
                    value = False
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

            setattr( editor, trait, value )
Пример #31
0
 def add_item(self, offset):
     """ Adds a new value at the specified list index.
     """
     list, index = self.get_info()
     index += offset
     item_trait = self._trait_handler.item_trait
     value = item_trait.default_value_for(self.object, self.name)
     try:
         self.value = list[:index] + [value] + list[index:]
     # if the default new item is invalid, we just don't add it to the list.
     # traits will still give an error message, but we don't want to crash
     except TraitError:
         from traitsui.api import raise_to_debug
         raise_to_debug()
     self.update_editor()
Пример #32
0
    def _evaluate_label_condition(self, conditions, kind):
        """Evaluates a list of (eval, widget) pairs and calls the appropriate
        method on the label widget to toggle whether it is visible/enabled
        as needed.
        """
        context = self.ui._get_context(self.ui.context)

        method_dict = {"visible": "setVisible", "enabled": "setEnabled"}

        for when, label in conditions:
            method_to_call = getattr(label, method_dict[kind])
            try:
                cond_value = eval(when, globals(), context)
                method_to_call(bool(cond_value))
            except Exception:
                # catch errors in the validate_when expression
                from traitsui.api import raise_to_debug

                raise_to_debug()
Пример #33
0
    def can_add_to_menu(self, action) :
        """ Returns whether the action should be defined in the user interface.
        """
        if action.defined_when != '':

            try:
                if not eval( action.defined_when, globals(), self._menu_context ):
                    return False
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

        if action.visible_when != '':
            try:
                if not eval( action.visible_when, globals(), self._menu_context ):
                    return False
            except:
                from traitsui.api import raise_to_debug
                raise_to_debug()

        return True
Пример #34
0
    def _evaluate_condition(self, conditions, trait, at_init=False):
        """ Evaluates a list of (eval, editor) pairs and sets a specified trait
        on each editor to reflect the Boolean value of the expression.

        1) All conditions are evaluated
        2) The elements whose condition evaluates to False are updated
        3) The elements whose condition evaluates to True are updated

        E.g., we first make invisible all elements for which 'visible_when'
        evaluates to False, and then we make visible the ones
        for which 'visible_when' is True. This avoids mutually exclusive
        elements to be visible at the same time, and thus making a dialog
        unnecessarily large.

        The state of an editor is updated only when it changes, unless
        at_init is set to True.

        Parameters
        ----------
        conditions : list of (str, Editor) tuple
            A list of tuples, each formed by 1) a string that contains a
            condition that evaluates to either True or False, and
            2) the editor whose state depends on the condition

        trait : str
            The trait that is set by the condition.
            Either 'visible, 'enabled', or 'checked'.

        at_init : bool
            If False, the state of an editor is set only when it changes
            (e.g., a visible element would not be updated to visible=True
            again). If True, the state is always updated (used at
            initialization).
        """

        context = self._get_context(self.context)

        # list of elements that should be activated
        activate = []
        # list of elements that should be de-activated
        deactivate = []

        for when, editor in conditions:
            try:
                cond_value = eval(when, globals(), context)
                editor_state = getattr(editor, trait)

                # add to update lists only if at_init is True (called on
                # initialization), or if the editor state has to change

                if cond_value and (at_init or not editor_state):
                    activate.append(editor)

                if not cond_value and (at_init or editor_state):
                    deactivate.append(editor)

            except Exception:
                # catch errors in the validate_when expression
                from traitsui.api import raise_to_debug
                raise_to_debug()

        # update the state of the editors
        for editor in deactivate:
            setattr(editor, trait, False)
        for editor in activate:
            setattr(editor, trait, True)
Пример #35
0
    def sync_value(self, user_name, editor_name, mode='both',
                   is_list=False, is_event=False):
        """
        Set up synchronization between an editor trait and a user object
        trait.

        Also sets the initial value of the editor trait from the
        user object trait (for modes 'from' and 'both'), and the initial
        value of the user object trait from the editor trait (for mode
        'to').

        Parameters
        ----------
        user_name : string
            The name of the trait to be used on the user object. If empty, no
            synchronization will be set up.
        editor_name : string
            The name of the relevant editor trait.
        mode : string, optional; one of 'to', 'from' or 'both'
            The direction of synchronization. 'from' means that trait changes
            in the user object should be propagated to the editor. 'to' means
            that trait changes in the editor should be propagated to the user
            object. 'both' means changes should be propagated in both
            directions. The default is 'both'.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        is_event : bool, optional
            If true, this method won't attempt to initialize the user
            object or editor trait values. The default is False.
        """
        if user_name != '':
            key = '%s:%s' % (user_name, editor_name)

            if self._no_trait_update is None:
                self._no_trait_update = {}

            user_ref = 'user_object'
            col = user_name.find('.')
            if col < 0:
                user_object = self.context_object
                xuser_name = user_name
            else:
                user_object = self.ui.context[user_name[: col]]
                user_name = xuser_name = user_name[col + 1:]
                col = user_name.rfind('.')
                if col >= 0:
                    user_ref += ('.' + user_name[: col])
                    user_name = user_name[col + 1:]

            user_value = compile('%s.%s' % (user_ref, user_name),
                                 '<string>', 'eval')
            user_ref = compile(user_ref, '<string>', 'eval')

            if mode in ('from', 'both'):

                def user_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(self, editor_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                user_object.on_trait_change(user_trait_modified, xuser_name)

                if self._user_to is None:
                    self._user_to = []
                self._user_to.append((user_object, xuser_name,
                                      user_trait_modified))

                if is_list:

                    def user_list_modified(event):
                        if isinstance(event, TraitListEvent):
                            if key not in self._no_trait_update:
                                self._no_trait_update[key] = None
                                n = event.index
                                try:
                                    getattr(self, editor_name)[
                                        n: n + len(event.removed)] = event.added
                                except:
                                    from traitsui.api import raise_to_debug
                                    raise_to_debug()
                                del self._no_trait_update[key]

                    user_object.on_trait_change(user_list_modified,
                                                xuser_name + '_items')
                    self._user_to.append((user_object, xuser_name + '_items',
                                          user_list_modified))

                if not is_event:
                    try:
                        setattr(self, editor_name, eval(user_value))
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()

            if mode in ('to', 'both'):

                def editor_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(eval(user_ref), user_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                self.on_trait_change(editor_trait_modified, editor_name)

                if self._user_from is None:
                    self._user_from = []
                self._user_from.append((editor_name, editor_trait_modified))

                if is_list:

                    def editor_list_modified(event):
                        # Need this to include 'user_object' in closure:
                        user_object
                        if key not in self._no_trait_update:
                            self._no_trait_update[key] = None
                            n = event.index
                            try:
                                eval(user_value)[
                                    n: n + len(event.removed)] = event.added
                            except:
                                from traitsui.api import raise_to_debug
                                raise_to_debug()
                            del self._no_trait_update[key]

                    self.on_trait_change(editor_list_modified,
                                         editor_name + '_items')
                    self._user_from.append((editor_name + '_items',
                                            editor_list_modified))

                if mode == 'to' and not is_event:
                    try:
                        setattr(eval(user_ref), user_name,
                                getattr(self, editor_name))
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()
Пример #36
0
    def sync_value(self, user_name, editor_name, mode='both',
                   is_list=False, is_event=False):
        """
        Set up synchronization between an editor trait and a user object
        trait.

        Also sets the initial value of the editor trait from the
        user object trait (for modes 'from' and 'both'), and the initial
        value of the user object trait from the editor trait (for mode
        'to').

        Parameters
        ----------
        user_name : string
            The name of the trait to be used on the user object. If empty, no
            synchronization will be set up.
        editor_name : string
            The name of the relevant editor trait.
        mode : string, optional; one of 'to', 'from' or 'both'
            The direction of synchronization. 'from' means that trait changes
            in the user object should be propagated to the editor. 'to' means
            that trait changes in the editor should be propagated to the user
            object. 'both' means changes should be propagated in both
            directions. The default is 'both'.
        is_list : bool, optional
            If true, synchronization for item events will be set up in
            addition to the synchronization for the object itself.
            The default is False.
        is_event : bool, optional
            If true, this method won't attempt to initialize the user
            object or editor trait values. The default is False.
        """
        if user_name != '':
            key = '%s:%s' % (user_name, editor_name)

            if self._no_trait_update is None:
                self._no_trait_update = {}

            user_ref = 'user_object'
            col = user_name.find('.')
            if col < 0:
                user_object = self.context_object
                xuser_name = user_name
            else:
                user_object = self.ui.context[user_name[: col]]
                user_name = xuser_name = user_name[col + 1:]
                col = user_name.rfind('.')
                if col >= 0:
                    user_ref += ('.' + user_name[: col])
                    user_name = user_name[col + 1:]

            user_value = compile('%s.%s' % (user_ref, user_name),
                                 '<string>', 'eval')
            user_ref = compile(user_ref, '<string>', 'eval')

            if mode in ('from', 'both'):

                def user_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(self, editor_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                user_object.on_trait_change(user_trait_modified, xuser_name)

                if self._user_to is None:
                    self._user_to = []
                self._user_to.append((user_object, xuser_name,
                                      user_trait_modified))

                if is_list:

                    def user_list_modified(event):
                        if isinstance(event, TraitListEvent):
                            if key not in self._no_trait_update:
                                self._no_trait_update[key] = None
                                n = event.index
                                try:
                                    getattr(self, editor_name)[
                                        n: n + len(event.removed)] = event.added
                                except:
                                    from traitsui.api import raise_to_debug
                                    raise_to_debug()
                                del self._no_trait_update[key]

                    user_object.on_trait_change(user_list_modified,
                                                xuser_name + '_items')
                    self._user_to.append((user_object, xuser_name + '_items',
                                          user_list_modified))

                if not is_event:
                    try:
                        setattr(self, editor_name, eval(user_value))
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()

            if mode in ('to', 'both'):

                def editor_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(eval(user_ref), user_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                self.on_trait_change(editor_trait_modified, editor_name)

                if self._user_from is None:
                    self._user_from = []
                self._user_from.append((editor_name, editor_trait_modified))

                if is_list:

                    def editor_list_modified(event):
                        # Need this to include 'user_object' in closure:
                        user_object
                        if key not in self._no_trait_update:
                            self._no_trait_update[key] = None
                            n = event.index
                            try:
                                eval(user_value)[
                                    n: n + len(event.removed)] = event.added
                            except:
                                from traitsui.api import raise_to_debug
                                raise_to_debug()
                            del self._no_trait_update[key]

                    self.on_trait_change(editor_list_modified,
                                         editor_name + '_items')
                    self._user_from.append((editor_name + '_items',
                                            editor_list_modified))

                if mode == 'to' and not is_event:
                    try:
                        setattr(eval(user_ref), user_name,
                                getattr(self, editor_name))
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()
Пример #37
0
    def sync_value(self, user_name, editor_name, mode="both", is_list=False):
        """ Sets or unsets synchronization between an editor trait and a user
            object trait.
        """
        if user_name != "":
            key = "%s:%s" % (user_name, editor_name)

            if self._no_trait_update is None:
                self._no_trait_update = {}

            user_ref = "user_object"
            col = user_name.find(".")
            if col < 0:
                user_object = self.context_object
                xuser_name = user_name
            else:
                user_object = self.ui.context[user_name[:col]]
                user_name = xuser_name = user_name[col + 1 :]
                col = user_name.rfind(".")
                if col >= 0:
                    user_ref += "." + user_name[:col]
                    user_name = user_name[col + 1 :]

            user_value = compile("%s.%s" % (user_ref, user_name), "<string>", "eval")
            user_ref = compile(user_ref, "<string>", "eval")

            if mode in ("from", "both"):

                def user_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(self, editor_name, new)
                        except:
                            from traitsui.api import raise_to_debug

                            raise_to_debug()
                        del self._no_trait_update[key]

                user_object.on_trait_change(user_trait_modified, xuser_name)

                if self._user_to is None:
                    self._user_to = []
                self._user_to.append((user_object, xuser_name, user_trait_modified))

                if is_list:

                    def user_list_modified(event):
                        if isinstance(event, TraitListEvent):
                            if key not in self._no_trait_update:
                                self._no_trait_update[key] = None
                                n = event.index
                                try:
                                    getattr(self, editor_name)[n : n + len(event.removed)] = event.added
                                except:
                                    from traitsui.api import raise_to_debug

                                    raise_to_debug()
                                del self._no_trait_update[key]

                    user_object.on_trait_change(user_list_modified, xuser_name + "_items")
                    self._user_to.append((user_object, xuser_name + "_items", user_list_modified))

                try:
                    setattr(self, editor_name, eval(user_value))
                except:
                    from traitsui.api import raise_to_debug

                    raise_to_debug()

            if mode in ("to", "both"):

                def editor_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(eval(user_ref), user_name, new)
                        except:
                            from traitsui.api import raise_to_debug

                            raise_to_debug()
                        del self._no_trait_update[key]

                self.on_trait_change(editor_trait_modified, editor_name)

                if self._user_from is None:
                    self._user_from = []
                self._user_from.append((editor_name, editor_trait_modified))

                if is_list:

                    def editor_list_modified(event):
                        # Need this to include 'user_object' in closure:
                        user_object
                        if key not in self._no_trait_update:
                            self._no_trait_update[key] = None
                            n = event.index
                            try:
                                eval(user_value)[n : n + len(event.removed)] = event.added
                            except:
                                from traitsui.api import raise_to_debug

                                raise_to_debug()
                            del self._no_trait_update[key]

                    self.on_trait_change(editor_list_modified, editor_name + "_items")
                    self._user_from.append((editor_name + "_items", editor_list_modified))

                if mode == "to":
                    try:
                        setattr(eval(user_ref), user_name, getattr(self, editor_name))
                    except:
                        from traitsui.api import raise_to_debug

                        raise_to_debug()
Пример #38
0
    def sync_value(self, user_name, editor_name, mode='both', is_list=False):
        """ Sets or unsets synchronization between an editor trait and a user
            object trait.
        """
        if user_name != '':
            key = '%s:%s' % (user_name, editor_name)

            if self._no_trait_update is None:
                self._no_trait_update = {}

            user_ref = 'user_object'
            col = user_name.find('.')
            if col < 0:
                user_object = self.context_object
                xuser_name = user_name
            else:
                user_object = self.ui.context[user_name[:col]]
                user_name = xuser_name = user_name[col + 1:]
                col = user_name.rfind('.')
                if col >= 0:
                    user_ref += ('.' + user_name[:col])
                    user_name = user_name[col + 1:]

            user_value = compile('%s.%s' % (user_ref, user_name), '<string>',
                                 'eval')
            user_ref = compile(user_ref, '<string>', 'eval')

            if mode in ('from', 'both'):

                def user_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(self, editor_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                user_object.on_trait_change(user_trait_modified, xuser_name)

                if self._user_to is None:
                    self._user_to = []
                self._user_to.append(
                    (user_object, xuser_name, user_trait_modified))

                if is_list:

                    def user_list_modified(event):
                        if isinstance(event, TraitListEvent):
                            if key not in self._no_trait_update:
                                self._no_trait_update[key] = None
                                n = event.index
                                try:
                                    getattr(self, editor_name
                                            )[n:n +
                                              len(event.removed)] = event.added
                                except:
                                    from traitsui.api import raise_to_debug
                                    raise_to_debug()
                                del self._no_trait_update[key]

                    user_object.on_trait_change(user_list_modified,
                                                xuser_name + '_items')
                    self._user_to.append((user_object, xuser_name + '_items',
                                          user_list_modified))

                try:
                    setattr(self, editor_name, eval(user_value))
                except:
                    from traitsui.api import raise_to_debug
                    raise_to_debug()

            if mode in ('to', 'both'):

                def editor_trait_modified(new):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[key] = None
                        try:
                            setattr(eval(user_ref), user_name, new)
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[key]

                self.on_trait_change(editor_trait_modified, editor_name)

                if self._user_from is None:
                    self._user_from = []
                self._user_from.append((editor_name, editor_trait_modified))

                if is_list:

                    def editor_list_modified(event):
                        # Need this to include 'user_object' in closure:
                        user_object
                        if key not in self._no_trait_update:
                            self._no_trait_update[key] = None
                            n = event.index
                            try:
                                eval(user_value
                                     )[n:n + len(event.removed)] = event.added
                            except:
                                from traitsui.api import raise_to_debug
                                raise_to_debug()
                            del self._no_trait_update[key]

                    self.on_trait_change(editor_list_modified,
                                         editor_name + '_items')
                    self._user_from.append(
                        (editor_name + '_items', editor_list_modified))

                if mode == 'to':
                    try:
                        setattr(eval(user_ref), user_name,
                                getattr(self, editor_name))
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()
Пример #39
0
    def sync_value ( self, user_name, editor_name, mode = 'both',
                           is_list = False ):
        """ Sets or unsets synchronization between an editor trait and a user
            object trait.
        """
        if user_name != '':
            key = '%s:%s' % ( user_name, editor_name )

            if self._no_trait_update is None:
                self._no_trait_update = {}

            user_ref = 'user_object'
            col      = user_name.find( '.' )
            if col < 0:
                user_object = self.context_object
                xuser_name  = user_name
            else:
                user_object = self.ui.context[ user_name[ : col ] ]
                user_name   = xuser_name = user_name[ col + 1: ]
                col         = user_name.rfind( '.' )
                if col >= 0:
                    user_ref += ('.' + user_name[ : col ])
                    user_name = user_name[ col + 1: ]

            user_value = compile( '%s.%s' % ( user_ref, user_name ),
                                  '<string>', 'eval' )
            user_ref   = compile( user_ref, '<string>', 'eval' )

            if mode in ( 'from', 'both' ):

                def user_trait_modified ( new ):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[ key ] = None
                        try:
                            setattr( self, editor_name, new )
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[ key ]

                user_object.on_trait_change( user_trait_modified, xuser_name )

                if self._user_to is None:
                    self._user_to = []
                self._user_to.append( ( user_object, xuser_name,
                                        user_trait_modified ) )

                if is_list:

                    def user_list_modified ( event ):
                        if isinstance( event, TraitListEvent ):
                            if key not in self._no_trait_update:
                                self._no_trait_update[ key ] = None
                                n = event.index
                                try:
                                    getattr( self, editor_name )[
                                        n: n + len(event.removed)] = event.added
                                except:
                                    from traitsui.api import raise_to_debug
                                    raise_to_debug()
                                del self._no_trait_update[ key ]

                    user_object.on_trait_change( user_list_modified,
                                    xuser_name + '_items' )
                    self._user_to.append( ( user_object, xuser_name + '_items',
                                            user_list_modified ) )

                try:
                    setattr( self, editor_name, eval( user_value ) )
                except:
                    from traitsui.api import raise_to_debug
                    raise_to_debug()

            if mode in ( 'to', 'both' ):

                def editor_trait_modified ( new ):
                    # Need this to include 'user_object' in closure:
                    user_object
                    if key not in self._no_trait_update:
                        self._no_trait_update[ key ] = None
                        try:
                            setattr( eval( user_ref ), user_name, new )
                        except:
                            from traitsui.api import raise_to_debug
                            raise_to_debug()
                        del self._no_trait_update[ key ]

                self.on_trait_change( editor_trait_modified, editor_name )

                if self._user_from is None:
                    self._user_from = []
                self._user_from.append( ( editor_name, editor_trait_modified ) )

                if is_list:

                    def editor_list_modified ( event ):
                        # Need this to include 'user_object' in closure:
                        user_object
                        if key not in self._no_trait_update:
                            self._no_trait_update[ key ] = None
                            n = event.index
                            try:
                                eval( user_value )[ n:
                                    n + len( event.removed ) ] = event.added
                            except:
                                from traitsui.api import raise_to_debug
                                raise_to_debug()
                            del self._no_trait_update[ key ]

                    self.on_trait_change( editor_list_modified,
                             editor_name + '_items' )
                    self._user_from.append( ( editor_name + '_items',
                                              editor_list_modified ) )

                if mode == 'to':
                    try:
                        setattr( eval( user_ref ), user_name,
                                 getattr( self, editor_name ) )
                    except:
                        from traitsui.api import raise_to_debug
                        raise_to_debug()
Пример #40
0
    def _evaluate_condition(self, conditions, trait, at_init=False):
        """ Evaluates a list of (eval, editor) pairs and sets a specified trait
        on each editor to reflect the Boolean value of the expression.

        1) All conditions are evaluated
        2) The elements whose condition evaluates to False are updated
        3) The elements whose condition evaluates to True are updated

        E.g., we first make invisible all elements for which 'visible_when'
        evaluates to False, and then we make visible the ones
        for which 'visible_when' is True. This avoids mutually exclusive
        elements to be visible at the same time, and thus making a dialog
        unnecessarily large.

        The state of an editor is updated only when it changes, unless
        at_init is set to True.

        Parameters
        ----------
        conditions : list of (str, Editor) tuple
            A list of tuples, each formed by 1) a string that contains a
            condition that evaluates to either True or False, and
            2) the editor whose state depends on the condition

        trait : str
            The trait that is set by the condition.
            Either 'visible, 'enabled', or 'checked'.

        at_init : bool
            If False, the state of an editor is set only when it changes
            (e.g., a visible element would not be updated to visible=True
            again). If True, the state is always updated (used at
            initialization).
        """

        context = self._get_context(self.context)

        # list of elements that should be activated
        activate = []
        # list of elements that should be de-activated
        deactivate = []

        for when, editor in conditions:
            try:
                cond_value = eval(when, globals(), context)
                editor_state = getattr(editor, trait)

                # add to update lists only if at_init is True (called on
                # initialization), or if the editor state has to change

                if cond_value and (at_init or not editor_state):
                    activate.append(editor)

                if not cond_value and (at_init or editor_state):
                    deactivate.append(editor)

            except Exception:
                # catch errors in the validate_when expression
                from traitsui.api import raise_to_debug

                raise_to_debug()

        # update the state of the editors
        for editor in deactivate:
            setattr(editor, trait, False)
        for editor in activate:
            setattr(editor, trait, True)