Ejemplo n.º 1
0
def run_script(mayavi, script_name):
    """Execfiles a given script.  The name `mayavi` is bound to the
    mayavi script instance just like in the embedded interpreter.
    `script_name` is the name of the script to execute.

    Note that this function uses `execfile`. You should be careful
    when using this.

    It returns `False` if everything was OK and `True` if not.
    """
    from enthought.mayavi.core.common import exception

    g = sys.modules['__main__'].__dict__
    if 'mayavi' not in g:
        g['mayavi'] = mayavi
        g['engine'] = mayavi.engine
    error = False
    # Do execfile
    try:
        # If we don't pass globals twice we get NameErrors and nope,
        # using exec open(script_name).read() does not fix it.
        execfile(script_name, g, g)
    except Exception, msg:
        exception(str(msg))
        error = True
Ejemplo n.º 2
0
 def open(self, filename):
     """Open a data file if possible.
     """
     try:
         return self.engine.open(filename)
     except:
         exception()
Ejemplo n.º 3
0
 def add_source(self, src, scene=None):
     """Adds a given source to the MayaVi pipeline.
     """
     try:
         self.engine.add_source(src, scene=scene)
     except:
         exception()
Ejemplo n.º 4
0
 def add_source(self, src, scene=None):
     """Adds a given source to the MayaVi pipeline.
     """
     try:
         self.engine.add_source(src, scene=scene)
     except:
         exception()
Ejemplo n.º 5
0
 def load_visualization(self, fname):
     """Given a file/file name this loads the visualization.
     """
     try:
         self.engine.load_visualization(fname)
     except:
         exception()
Ejemplo n.º 6
0
 def perform(self, event):
     """ Performs the action. """
     wildcard = 'Python files (*.py)|*.py'
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title='Open Python file',
                         action='open', wildcard=wildcard
                         )
     if dialog.open() == OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist"%dialog.path, parent)
             return
         
         # Get the globals.
         # The following code is taken from scripts/mayavi2.py.
         g = sys.modules['__main__'].__dict__
         if 'mayavi' not in g:
             mv = get_imayavi(self.window)
             g['mayavi'] = mv
             g['engine'] = mv.engine
         # Do execfile
         try:
             # If we don't pass globals twice we get NameErrors and nope,
             # using exec open(script_name).read() does not fix it.
             execfile(dialog.path, g, g)
         except Exception, msg:
             exception(str(msg))
Ejemplo n.º 7
0
 def load_visualization(self, fname):
     """Given a file/file name this loads the visualization.
     """
     try:
         self.engine.load_visualization(fname)
     except:
         exception()
Ejemplo n.º 8
0
def run_script(mayavi, script_name):
    """Execfiles a given script.  The name `mayavi` is bound to the
    mayavi script instance just like in the embedded interpreter.
    `script_name` is the name of the script to execute.

    Note that this function uses `execfile`. You should be careful
    when using this.

    It returns `False` if everything was OK and `True` if not.
    """
    from enthought.mayavi.core.common import exception

    g = sys.modules['__main__'].__dict__
    if 'mayavi' not in g:
        g['mayavi'] = mayavi
        g['engine'] = mayavi.engine
    error = False
    # Do execfile
    try:
        # If we don't pass globals twice we get NameErrors and nope,
        # using exec open(script_name).read() does not fix it.
        execfile(script_name, g, g)
    except Exception, msg:
        exception(str(msg))
        error = True
Ejemplo n.º 9
0
 def open(self, filename):
     """Open a data file if possible.
     """
     try:
         return self.engine.open(filename)
     except:
         exception()
Ejemplo n.º 10
0
 def save_visualization(self, fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     try:
         self.engine.save_visualization(fname)
     except:
         exception()
Ejemplo n.º 11
0
 def save_visualization(self, fname):
     """Given a file or a file name, this saves the current
     visualization to the file.
     """
     try:
         self.engine.save_visualization(fname)
     except:
         exception()
Ejemplo n.º 12
0
 def add_module(self, mod, obj=None):
     """Adds a given module to the MayaVi pipeline. Adds it to the selected 
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_module(mod, obj=obj)
     except:
         exception()
Ejemplo n.º 13
0
 def add_module(self, mod, obj=None):
     """Adds a given module to the MayaVi pipeline. Adds it to the selected 
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_module(mod, obj=obj)
     except:
         exception()
Ejemplo n.º 14
0
 def add_filter(self, fil, obj=None):
     """Adds a given filter to the MayaVi pipeline. Adds it to the selected 
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_filter(fil, obj=obj)
     except:
         exception()
Ejemplo n.º 15
0
 def add_filter(self, fil, obj=None):
     """Adds a given filter to the MayaVi pipeline. Adds it to the selected 
     object, or to an object passed thought the kwarg `obj`.
     """
     try:
         self.engine.add_filter(fil, obj=obj)
     except:
         exception()
Ejemplo n.º 16
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control

        # path from preference manager
        pref_script_path = preference_manager.cviewerui.scriptpath

        if pref_script_path == '':
            # store executed script path in preferences
            dialog = FileDialog(
                parent=parent,
                title='Open Python file',
                action='open',
                wildcard=wildcard,
            )
        else:
            dialog = FileDialog(
                parent=parent,
                title='Open Python file',
                action='open',
                wildcard=wildcard,
                default_directory=pref_script_path,
            )

        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist" % dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine

            if 'cfile' not in g:
                # load cfile reference into gloabl name space
                cfile = self.window.application.get_service(
                    'cviewer.plugins.cff2.cfile.CFile')
                g['cfile'] = cfile

            # always store last executed path in preferences
            # but this only gets definitely stored when one open the preference manager
            preference_manager.cviewerui.scriptpath = dirname(dialog.path)

            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                execfile(dialog.path, g, g)
            except Exception, msg:
                exception(str(msg))
Ejemplo n.º 17
0
 def _handle_children(self, removed, added):
     for obj in removed:
         obj.stop()
     for obj in added:
         obj.set(scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Ejemplo n.º 18
0
 def _handle_children(self, removed, added):
     for obj in removed:
         obj.stop()
     for obj in added:
         obj.set(scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Ejemplo n.º 19
0
 def _handle_children(self, removed, added):
     # Stop all the old children.
     for obj in removed:
         obj.stop()
     # Setup and start the new ones.
     for obj in added:
         obj.set(module_manager=self, scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Ejemplo n.º 20
0
 def _handle_children(self, removed, added):
     # Stop all the old children.
     for obj in removed:
         obj.stop()
     # Setup and start the new ones.
     for obj in added:
         obj.set(module_manager=self, scene=self.scene, parent=self)
         if self.running:
             # It makes sense to start children only if we are running.
             # If not, the children will be started when we start.
             try:
                 obj.start()
             except:
                 exception()
Ejemplo n.º 21
0
 def perform(self, event):
     """ Performs the action. """
     wildcard = 'Python files (*.py)|*.py'
     parent = self.window.control
     
     # path from preference manager
     pref_script_path = preference_manager.cviewerui.scriptpath
     
     if pref_script_path == '':
         # store executed script path in preferences
         dialog = FileDialog(parent=parent,
                         title='Open Python file',
                         action='open', wildcard=wildcard,
                         )            
     else:
         dialog = FileDialog(parent=parent,
                         title='Open Python file',
                         action='open', wildcard=wildcard,
                         default_directory=pref_script_path,
                         )
     
     if dialog.open() == OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist"%dialog.path, parent)
             return
         
         # Get the globals.
         # The following code is taken from scripts/mayavi2.py.
         g = sys.modules['__main__'].__dict__
         if 'mayavi' not in g:
             mv = get_imayavi(self.window)
             g['mayavi'] = mv
             g['engine'] = mv.engine
             
         if 'cfile' not in g:
             # load cfile reference into gloabl name space
             cfile = self.window.application.get_service('cviewer.plugins.cff2.cfile.CFile')
             g['cfile'] = cfile
         
         # always store last executed path in preferences
         # but this only gets definitely stored when one open the preference manager
         preference_manager.cviewerui.scriptpath = dirname(dialog.path)
         
         # Do execfile
         try:
             # If we don't pass globals twice we get NameErrors and nope,
             # using exec open(script_name).read() does not fix it.
             execfile(dialog.path, g, g)
         except Exception, msg:
             exception(str(msg))
Ejemplo n.º 22
0
    def _handle_children(self, removed, added):
        # Stop all the removed children.
        for obj in removed:
            obj.stop()

        # Process the new objects.
        for obj in added:
            obj.set(scene=self.scene, parent=self)
            if isinstance(obj, ModuleManager):
                obj.source = self
            elif is_filter(obj):
                obj.inputs.append(self)
            if self.running:
                try:
                    obj.start()
                except:
                    exception()
Ejemplo n.º 23
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.
        """
        # Do nothing if we are already running.
        if self.running:
            return
        
        # Start all our children.
        for obj in self.children:
            try:
                obj.start()
            except:
                exception()

        # Call parent method to set the running state.
        super(Source, self).start()
Ejemplo n.º 24
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.  Note that when start is invoked, all the other
        information for the pipeline should be already set.
        """
        if self.running:
            return

        # Setup event handlers.
        self._setup_event_handlers()

        # Setup the pipeline.
        self.update_pipeline()

        # Start the components.
        try:
            for component in self.components:
                component.start()
        except:
            exception()

        # Call parent method to set the running state.
        super(Module, self).start()
Ejemplo n.º 25
0
    def start(self):
        """This is invoked when this object is added to the mayavi
        pipeline.  Note that when start is invoked, all the other
        information for the pipeline should be already set.
        """
        if self.running:
            return

        # Setup event handlers.
        self._setup_event_handlers()

        # Setup the pipeline.        
        self.update_pipeline()

        # Start the components.
        try:
            for component in self.components:
                component.start()
        except:
            exception()

        # Call parent method to set the running state.
        super(Module, self).start()
Ejemplo n.º 26
0
def process_cmd_line(app, opts, args):
    """ Processes the passed command line arguments.

    Input Arguments:
      app -- A Mayavi application instance.

      opts -- The list of options returned by getopt.

      args -- The remaining arguments returned by getopt.
    """    

    from enthought.mayavi.core.common import error, exception
    from enthought.tvtk.common import camel2enthought

    sources = _get_non_file_sources()
    script = app.script
    last_obj = None

    # Start a new scene by default if there is none currently and none
    # was specified at the start of the command line arguments.
    if script.engine.current_scene is None:
        new_scene = False
        if len(opts) == 0:
            if len(args) == 0:
                new_scene = True
        elif (opts[0][0] not in ('-n', '--new-scene', '-z',
                                 '--visualization', '--viz',
                                 '-x', '--exec')):
            new_scene = True
        if new_scene:            
            last_obj = script.new_scene()
        
    for o, a in opts:
        if o in ('-d', '--data'):
            base, ext = splitext(a)
            if exists(a):
                last_obj = script.open(a)
            elif a in sources:
                md = sources[a]
                src = md.get_callable()()
                script.add_source(src)
                last_obj = src
            else:
                error("File/Source %s does not exist!"%a)
                return

        if o in ('-m', '--module'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx+1:]
            else:
                modname = 'enthought.mayavi.modules.%s'%camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                m = getattr(mod, classname)()
                if classname == 'Labels':
                    m.object = script.engine.current_object
                script.add_module(m)
                last_obj = m

        if o in ('-f', '--filter'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx+1:]
            else:
                if a[:12] == 'UserDefined:':
                    modname = 'enthought.mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from enthought.tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'enthought.mayavi.filters.%s'%camel2enthought(a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                klass = getattr(mod, classname)
                if classname != 'UserDefined':
                    f = klass()
                else:
                    if extra is not None:
                        f = klass(filter=extra)
                    else:
                        f = klass()
                    f.setup_filter()
                script.add_filter(f)
                last_obj = f
Ejemplo n.º 27
0
            e = script.engine
            s = e.scenes[-1]
            e.set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec' ):
            err = run_script(script, a)
            if err: # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec stmt in locals(), globals()
            except Exception, msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext (arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err: # stop processing arguments.
                return
        else:
            script.open(arg)
Ejemplo n.º 28
0
            e = script.engine
            s = e.scenes[-1]
            e.set(current_scene=s, current_object=s)
            last_obj = s

        if o in ('-x', '--exec'):
            err = run_script(script, a)
            if err:  # stop processing options.
                return

        if o in ('-s', '--set'):
            try:
                stmt = 'last_obj.' + a
                exec stmt in locals(), globals()
            except Exception, msg:
                exception(str(msg))

        if o in ('-z', '--visualization', '--viz'):
            script.load_visualization(a)

    # for remaining arguments simply load saved visualizations.
    for arg in args:
        base, ext = splitext(arg)
        if ext == '.mv2':
            script.load_visualization(arg)
        elif ext == '.py':
            err = run_script(script, arg)
            if err:  # stop processing arguments.
                return
        else:
            script.open(arg)
Ejemplo n.º 29
0
def process_cmd_line(app, opts, args):
    """ Processes the passed command line arguments.

    Input Arguments:
      app -- A Mayavi application instance.

      opts -- The list of options returned by getopt.

      args -- The remaining arguments returned by getopt.
    """

    from enthought.mayavi.core.common import error, exception
    from enthought.tvtk.common import camel2enthought

    sources = _get_non_file_sources()
    script = app.script
    last_obj = None

    # Start a new scene by default if there is none currently and none
    # was specified at the start of the command line arguments.
    if script.engine.current_scene is None:
        new_scene = False
        if len(opts) == 0:
            if len(args) == 0:
                new_scene = True
        elif (opts[0][0] not in ('-n', '--new-scene', '-z', '--visualization',
                                 '--viz', '-x', '--exec')):
            new_scene = True
        if new_scene:
            last_obj = script.new_scene()

    for o, a in opts:
        if o in ('-d', '--data'):
            base, ext = splitext(a)
            if exists(a):
                last_obj = script.open(a)
            elif a in sources:
                md = sources[a]
                src = md.get_callable()()
                script.add_source(src)
                last_obj = src
            else:
                error("File/Source %s does not exist!" % a)
                return

        if o in ('-m', '--module'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx + 1:]
            else:
                modname = 'enthought.mayavi.modules.%s' % camel2enthought(a)
                classname = a
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                m = getattr(mod, classname)()
                if classname == 'Labels':
                    m.object = script.engine.current_object
                script.add_module(m)
                last_obj = m

        if o in ('-f', '--filter'):
            if '.' in a:
                idx = a.rfind('.')
                modname = a[:idx]
                classname = a[idx + 1:]
            else:
                if a[:12] == 'UserDefined:':
                    modname = 'enthought.mayavi.filters.user_defined'
                    classname = 'UserDefined'
                    # Create the wrapped filter.
                    fname = a[12:]
                    from enthought.tvtk.api import tvtk
                    try:
                        extra = getattr(tvtk, fname)()
                    except (AttributeError, TypeError):
                        # Don't worry about errors.
                        extra = None
                else:
                    modname = 'enthought.mayavi.filters.%s' % camel2enthought(
                        a)
                    classname = a
                    extra = None
            try:
                mod = __import__(modname, globals(), locals(), [classname])
            except ImportError, msg:
                exception(str(msg))
                return
            else:
                klass = getattr(mod, classname)
                if classname != 'UserDefined':
                    f = klass()
                else:
                    if extra is not None:
                        f = klass(filter=extra)
                    else:
                        f = klass()
                    f.setup_filter()
                script.add_filter(f)
                last_obj = f