Exemplo n.º 1
0
 def uncomment(self):
     if hasattr(self.currentWidget(), "uncomment"):
         self.currentWidget().uncomment()
         logger.debug("uncomment " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method uncomment in " +
                        self.currentWidget().applet.name)
Exemplo n.º 2
0
 def goto(self):
     if hasattr(self.currentWidget(), "goto"):
         self.currentWidget().goto()
         logger.debug("Goto " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method Goto in " +
                        self.currentWidget().applet.name)
Exemplo n.º 3
0
 def search(self):
     if hasattr(self.currentWidget(), "search"):
         self.currentWidget().search()
         logger.debug("Search " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method search in " +
                        self.currentWidget().applet.name)
Exemplo n.º 4
0
 def _load_entry_point_plugin(self,
                              category,
                              entry_point,
                              plugin_proxy=None):
     ep = entry_point
     identifier = '%s:%s:%s' % (category, ep.module_name, ep.name)
     plugin_class = None
     if identifier in self._plugin_loaded:
         plugin_class = self._plugin_loaded[identifier]
     else:
         if self.debug:
             plugin_class = ep.load()
             logger.debug('%s load plugin %s' %
                          (self.__class__.__name__, ep))
             self._plugin_loaded[identifier] = plugin_class
             self.add_plugin(category,
                             plugin_class,
                             plugin_proxy=plugin_proxy)
         else:
             try:
                 plugin_class = ep.load()
             except KeyboardInterrupt:
                 logger.error('%s: error loading %s ' % (category, ep))
             except Exception, e:
                 # never want a plugin load to kill the test run
                 # but we can't log here because the logger is not yet
                 # configured
                 warn("Unable to load plugin %s: %s" % (ep, e),
                      RuntimeWarning)
             else:
                 logger.debug('%s load plugin %s' %
Exemplo n.º 5
0
def geometry_2_piklable_geometry(manager, obj):
    """
    Transform a geometry object from PlantGL in picklable object.
    
    Rem: name of object is not changed
    :param manager: manager of object to transform
    :param obj: object to transform
    
    :return: tuple(transformed object, name_of_new_object)
    """
    geom = obj
    name = str(geom.getName())
    if isinstance(geom, NurbsPatch):
        new_obj = RedNurbsPatch(geom.ctrlPointMatrix, manager.typename)
        logger.debug("Transform NurbsPatch into RedNurbsPatch")
    elif isinstance(geom, Polyline2D):
        new_obj = RedPolyline2D(geom.pointList, manager.typename)
        logger.debug("Transform Polyline2D into RedPolyline2D")
    elif isinstance(geom, NurbsCurve2D):
        new_obj = RedNurbs2D(geom.ctrlPointList, manager.typename)
        logger.debug("Transform NurbsCurve2D into RedNurbs2D")
    elif isinstance(geom, BezierCurve2D):
        new_obj = RedBezierNurbs2D(geom.ctrlPointList, manager.typename)
        logger.debug("Transform BezierCurve2D into RedBezierNurbs2D")
    else:
        new_obj = obj
        new_obj.typename = manager.typename
        logger.debug("Transform Nothing %s" % str(geom))

    return (new_obj, name)
Exemplo n.º 6
0
def geometry_2_piklable_geometry(manager, obj):
    """
    Transform a geometry object from PlantGL in picklable object.
    
    Rem: name of object is not changed
    :param manager: manager of object to transform
    :param obj: object to transform
    
    :return: tuple(transformed object, name_of_new_object)
    """         
    geom = obj
    name = str(geom.getName())
    if isinstance(geom, NurbsPatch):
        new_obj = RedNurbsPatch(geom.ctrlPointMatrix, manager.typename)
        logger.debug("Transform NurbsPatch into RedNurbsPatch")
    elif isinstance(geom, Polyline2D):
        new_obj = RedPolyline2D(geom.pointList, manager.typename)
        logger.debug("Transform Polyline2D into RedPolyline2D")
    elif isinstance(geom, NurbsCurve2D):
        new_obj = RedNurbs2D(geom.ctrlPointList, manager.typename)
        logger.debug("Transform NurbsCurve2D into RedNurbs2D")
    elif isinstance(geom, BezierCurve2D):
        new_obj = RedBezierNurbs2D(geom.ctrlPointList, manager.typename)
        logger.debug("Transform BezierCurve2D into RedBezierNurbs2D")
    else:
        new_obj = obj
        new_obj.typename = manager.typename
        logger.debug("Transform Nothing %s"%str(geom))
    
    return(new_obj,name)         
Exemplo n.º 7
0
    def _add_plugin_from_ep(self, group, ep, plugin_class, plugin_proxy=None):
        logger.debug('%s load plugin %s' % (self.__class__.__name__, ep))
        from time import time
        if inspect.ismodule(plugin_class):
            plugin_classes = []
            for pl_name in dir(plugin_class):
                pl = getattr(plugin_class, pl_name)
                if self._is_plugin_class(pl):
                    plugin_classes.append(pl)
        elif isinstance(plugin_class, list):
            plugin_classes = plugin_class
        else:
            plugin_classes = [plugin_class]

        for plugin_class in plugin_classes:
            name = plugin_class.name if hasattr(
                plugin_class, 'name') else plugin_class.__name__
            parts = [
                str(s) for s in (ep.dist.egg_name(), group, ep.module_name,
                                 ep.name, name)
            ]
            identifier = ':'.join(parts)
            item = self.add(plugin_class,
                            group,
                            item_proxy=plugin_proxy,
                            identifier=identifier)
            self.patch_ep_plugin(item, ep)
Exemplo n.º 8
0
def extract_functions(codestring, filename='tmp'):
    """
    parse the code *codestring* and detect what are the functions defined inside
    :return: dict name -> code
    """
    # TODO: use ast.iter_child_nodes instead of walk to know nested level
    # For example, currently this code fails because indent level is wrong
    # if True:
    #   def f():
    #       print('hello')
    # This code fails because "return is outside of function"
    # def f():
    #    return 1
    # TODO: support IPython %magic

    funcs = {}

    r = ast_parse(codestring)
    for statement in ast.walk(r):
        if isinstance(statement, ast.FunctionDef):
            wrapped = ast.Interactive(body=statement.body)
            try:
                code = compile(wrapped, filename, 'single')
            except SyntaxError:
                logger.debug("Parsing code %s not yet supported" %
                             statement.name)
            else:
                funcs[statement.name] = code

    return funcs
Exemplo n.º 9
0
 def redo(self):
     if hasattr(self.currentWidget(), "redo"):
         self.currentWidget().redo()
         logger.debug("Redo " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method Redo in " +
                        self.currentWidget().applet.name)
Exemplo n.º 10
0
def extract_functions(codestring, filename='tmp'):
    """
    parse the code *codestring* and detect what are the functions defined inside
    :return: dict name -> code
    """
    # TODO: use ast.iter_child_nodes instead of walk to know nested level
    # For example, currently this code fails because indent level is wrong
    # if True:
    #   def f():
    #       print('hello')
    # This code fails because "return is outside of function"
    # def f():
    #    return 1
    # TODO: support IPython %magic

    funcs = {}

    r = ast_parse(codestring)
    for statement in ast.walk(r):
        if isinstance(statement, ast.FunctionDef):
            wrapped = ast.Interactive(body=statement.body)
            try:
                code = compile(wrapped, filename, 'single')
            except SyntaxError:
                logger.debug("Parsing code %s not yet supported" % statement.name)
            else:
                funcs[statement.name] = code

    return funcs
Exemplo n.º 11
0
def timeit(f, *args, **kwargs):
    t1 = time.time()
    ret = f(*args, **kwargs)
    t2 = time.time()
    logger.debug(f.__name__ + " took " + str(t2 - t1) + " seconds")
    if __debug__:
        print
    return ret
Exemplo n.º 12
0
def timeit(f, *args, **kwargs):
    t1 = time.time()
    ret = f(*args, **kwargs)
    t2 = time.time()
    logger.debug(f.__name__+" took "+str(t2-t1)+" seconds")
    if __debug__:
        print
    return ret
Exemplo n.º 13
0
 def insertCompletion(self, completion):
     logger.debug("insert completion")
     tc = self.textCursor()
     extra = (len(completion) - len(self.completer.completionPrefix()))
     tc.movePosition(QtGui.QTextCursor.Left)
     tc.movePosition(QtGui.QTextCursor.EndOfWord)
     tc.insertText(completion[-extra:])
     self.setTextCursor(tc)
     logger.debug("inserted completion")
Exemplo n.º 14
0
 def insertCompletion(self, completion):
     logger.debug("insert completion")
     tc = self.textCursor()
     extra = (len(completion) -
              len(self.completer.completionPrefix()))
     tc.movePosition(QtGui.QTextCursor.Left)
     tc.movePosition(QtGui.QTextCursor.EndOfWord)
     tc.insertText(completion[-extra:])
     self.setTextCursor(tc)
     logger.debug("inserted completion")
Exemplo n.º 15
0
    def setCompleter(self, completer):
        logger.debug("set completer " + str(completer))
        if self.completer:
            self.disconnect(self.completer, 0, self, 0)
        if not completer:
            return

        completer.setWidget(self)
        completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer = completer
        QtCore.QObject.connect(self.completer, QtCore.SIGNAL("activated(const QString&)"), self.insertCompletion)
Exemplo n.º 16
0
def showOpenFileDialog(extension=None, where=None, parent=None):
    if extension is None:
        extension = ""

    if where is not None:
        my_path = path(str(where)).abspath().splitpath()[0]
    else:
        my_path = path(settings.get_project_dir())
    logger.debug("Search to open file with extension " + extension + " from " + my_path)
    fname = QtGui.QFileDialog.getOpenFileName(parent, 'Select File to open',
                                              my_path, "All (*);;Scripts Files (%s)" % extension)
    return fname
Exemplo n.º 17
0
def ast_parse(string):
    logger.debug("Parse code: " + string[:10] + "...")
    try:
        M = ast.parse(string)
    except SyntaxError, e:
        #raise e
        logger.warning(str(e))
        wraper = textwrap.TextWrapper(width=30)
        txt = wraper.wrap(string)[0]  # Python 2
        # txt = textwrap.shorten(string, width=30, placeholder="...") # Python 3
        logger.warning("Syntax error when parsing: " + txt + "...")
        M = ast.parse("")
Exemplo n.º 18
0
def ast_parse(string):
    logger.debug("Parse code: " + string[:10] + "...")
    try:
        M = ast.parse(string)
    except SyntaxError, e:
        #raise e
        logger.warning(str(e))
        wraper = textwrap.TextWrapper(width=30)
        txt = wraper.wrap(string)[0]  # Python 2
        # txt = textwrap.shorten(string, width=30, placeholder="...") # Python 3
        logger.warning("Syntax error when parsing: " + txt + "...")
        M = ast.parse("")
Exemplo n.º 19
0
    def setCompleter(self, completer):
        logger.debug("set completer " + str(completer))
        if self.completer:
            self.disconnect(self.completer, 0, self, 0)
        if not completer:
            return

        completer.setWidget(self)
        completer.setCompletionMode(QtGui.QCompleter.PopupCompletion)
        completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
        self.completer = completer
        QtCore.QObject.connect(self.completer,
                               QtCore.SIGNAL("activated(const QString&)"),
                               self.insertCompletion)
Exemplo n.º 20
0
 def _load_entry_point_plugin(self, group, entry_point, item_proxy=None):
     ep = entry_point
     plugin_class = None
     if self.debug:
         plugin_class = ep.load()
         logger.debug('%s load plugin %s' % (self.__class__.__name__, ep))
         self._add_plugin_from_ep(group, ep, plugin_class, item_proxy)
     else:
         try:
             plugin_class = ep.load()
         except Exception:
             logger.error('%s: error loading %s ' % (group, ep))
         else:
             self._add_plugin_from_ep(group, ep, plugin_class, item_proxy)
Exemplo n.º 21
0
def showOpenFileDialog(extension=None, where=None, parent=None):
    if extension is None:
        extension = ""

    if where is not None:
        my_path = path(str(where)).abspath().splitpath()[0]
    else:
        my_path = path(settings.get_project_dir())
    logger.debug("Search to open file with extension " + extension + " from " +
                 my_path)
    fname = QtGui.QFileDialog.getOpenFileName(
        parent, 'Select File to open', my_path,
        "All (*);;Scripts Files (%s)" % extension)
    return fname
Exemplo n.º 22
0
    def searchBack(self):
        options = QtGui.QTextDocument.FindBackward

        if self.caseBtn.isChecked():
            options = options or QtGui.QTextDocument.FindCaseSensitively

        if self.wholeBtn.isChecked():
            options = options or QtGui.QTextDocument.FindWholeWords

        to_search_txt = self.lineEdit.text()

        if hasattr(self._editor, "find"):
            logger.debug("Search text: " + to_search_txt)
            self._editor.find(to_search_txt, options)
        else:
            logger.debug("Can't Search text " + to_search_txt)
Exemplo n.º 23
0
    def searchBack(self):
        options = QtGui.QTextDocument.FindBackward

        if self.caseBtn.isChecked():
            options = options or QtGui.QTextDocument.FindCaseSensitively

        if self.wholeBtn.isChecked():
            options = options or QtGui.QTextDocument.FindWholeWords

        to_search_txt = self.lineEdit.text()

        if hasattr(self._editor, "find"):
            logger.debug("Search text: " + to_search_txt)
            self._editor.find(to_search_txt, options)
        else:
            logger.debug("Can't Search text " + to_search_txt)
Exemplo n.º 24
0
    def _add_plugin_from_ep(self, group, ep, plugin_class, plugin_proxy=None):
        logger.debug('%s load plugin %s' % (self.__class__.__name__, ep))
        from time import time
        if inspect.ismodule(plugin_class):
            plugin_classes = []
            for pl_name in dir(plugin_class):
                pl = getattr(plugin_class, pl_name)
                if self._is_plugin_class(pl):
                    plugin_classes.append(pl)
        elif isinstance(plugin_class, list):
            plugin_classes = plugin_class
        else:
            plugin_classes = [plugin_class]

        for plugin_class in plugin_classes:
            name = plugin_class.name if hasattr(plugin_class, 'name') else plugin_class.__name__
            parts = [str(s) for s in (ep.dist.egg_name(), group, ep.module_name, ep.name, name)]
            identifier = ':'.join(parts)
            item = self.add(plugin_class, group, item_proxy=plugin_proxy, identifier=identifier)
            self.patch_ep_plugin(item, ep)
Exemplo n.º 25
0
 def _load_entry_point_plugin(self, category, entry_point, plugin_proxy=None):
     ep = entry_point
     identifier = "%s:%s:%s" % (category, ep.module_name, ep.name)
     plugin_class = None
     if identifier in self._plugin_loaded:
         plugin_class = self._plugin_loaded[identifier]
     else:
         if self.debug:
             plugin_class = ep.load()
             logger.debug("%s load plugin %s" % (self.__class__.__name__, ep))
             self._plugin_loaded[identifier] = plugin_class
             self.add_plugin(category, plugin_class, plugin_proxy=plugin_proxy)
         else:
             try:
                 plugin_class = ep.load()
             except KeyboardInterrupt:
                 logger.error("%s: error loading %s " % (category, ep))
             except Exception, e:
                 # never want a plugin load to kill the test run
                 # but we can't log here because the logger is not yet
                 # configured
                 warn("Unable to load plugin %s: %s" % (ep, e), RuntimeWarning)
             else:
                 logger.debug("%s load plugin %s" % (self.__class__.__name__, ep))
Exemplo n.º 26
0
    def load(self):
        """
        Get control from project and put them into widgets
        """
        self.clear()
        proj = self.session.project
        if not proj.control.has_key("color map"):
            proj.control["color map"] = self.colormap_editor.getTurtle(
            ).getColorList()
        if not proj.control["color map"]:
            proj.control["color map"] = self.colormap_editor.getTurtle(
            ).getColorList()
        i = 0
        logger.debug("Load Control color map: %s " %
                     str(proj.control["color map"]))
        for color in proj.control["color map"]:
            self.colormap_editor.getTurtle().setMaterial(i, color)
            i += 1

        managers = get_managers()
        geom = []
        scalars = []

        for control in proj.control:
            logger.debug(str(proj.control[control]))
            if hasattr(proj.control[control], "__module__"):
                if proj.control[
                        control].__module__ == "openalea.oalab.control.picklable_curves":
                    typename = proj.control[control].typename
                    proj.control[control].name = str(control)
                    manager = managers[typename]
                    geom.append((manager, proj.control[control]))
                elif str(control) != "color map":
                    scalars.append(proj.control[control])
            elif str(control) != "color map":
                scalars.append(proj.control[control])
        if geom is not list():
            logger.debug("Load Control Geom: %s " % str(geom))
            self.geometry_editor.setObjects(geom)
        if scalars is not list():
            logger.debug("Load Control Scalars: %s " % str(scalars))
            self.scalars_editor.setScalars(scalars)
Exemplo n.º 27
0
    def load(self):
        """
        Get control from project and put them into widgets
        """
        self.clear()
        proj = self.session.project
        if not proj.control.has_key("color map"):
            proj.control["color map"] = self.colormap_editor.getTurtle().getColorList()
        if not proj.control["color map"]:
            proj.control["color map"] = self.colormap_editor.getTurtle().getColorList()
        i = 0
        logger.debug("Load Control color map: %s " % str(proj.control["color map"]))
        for color in proj.control["color map"]:
            self.colormap_editor.getTurtle().setMaterial(i, color)
            i += 1

        managers = get_managers()
        geom = []
        scalars = []

        for control in proj.control:
            logger.debug(str(proj.control[control]))
            if hasattr(proj.control[control], "__module__"):
                if proj.control[control].__module__ == "openalea.oalab.control.picklable_curves":
                    typename = proj.control[control].typename
                    proj.control[control].name = str(control)
                    manager = managers[typename]
                    geom.append((manager, proj.control[control]))
                elif str(control) != "color map":
                    scalars.append(proj.control[control])
            elif str(control) != "color map":
                scalars.append(proj.control[control])
        if geom is not list():
            logger.debug("Load Control Geom: %s " % str(geom))
            self.geometry_editor.setObjects(geom)
        if scalars is not list():
            logger.debug("Load Control Scalars: %s " % str(scalars))
            self.scalars_editor.setScalars(scalars)
Exemplo n.º 28
0
 def goto(self):
     if hasattr(self.currentWidget(), "goto"):
         self.currentWidget().goto()
         logger.debug("Goto " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method Goto in " + self.currentWidget().applet.name)
Exemplo n.º 29
0
 def execute(self):
     self.currentWidget().applet.execute()
     logger.debug("Execute selected part " +
                  self.currentWidget().applet.name)
Exemplo n.º 30
0
 def run(self):
     self.currentWidget().applet.run()
     logger.debug("Run " + self.currentWidget().applet.name)
Exemplo n.º 31
0
 def run_in_shell(self):
     self.currentWidget().applet.run(run_in_shell=True)
     logger.debug("Run " + self.currentWidget().applet.name)
Exemplo n.º 32
0
 def init(self):
     self.currentWidget().applet.init()
     logger.debug("Init " + self.currentWidget().applet.name)
Exemplo n.º 33
0
 def redo(self):
     if hasattr(self.currentWidget(), "redo"):
         self.currentWidget().redo()
         logger.debug("Redo " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method Redo in " + self.currentWidget().applet.name)
Exemplo n.º 34
0
 def init(self):
     self.currentWidget().applet.init()
     logger.debug("Init " + self.currentWidget().applet.name)
Exemplo n.º 35
0
 def execute(self):
     self.currentWidget().applet.execute()
     logger.debug("Execute selected part " + self.currentWidget().applet.name)
Exemplo n.º 36
0
 def run_in_shell(self):
     self.currentWidget().applet.run(run_in_shell=True)
     logger.debug("Run " + self.currentWidget().applet.name)
Exemplo n.º 37
0
class PluginManager(object):

    __metaclass__ = Singleton

    def __init__(self, plugins=None, plugin_proxy=None):
        """
        :param plugins: list of plugins you want to add manually
        :param plugin_proxy: proxy class to use by default
        """
        self._plugin = {
        }  # dict category -> plugin name -> Plugin class or Plugin proxy
        self._plugin_proxy = {}
        self._plugin_loaded = {}

        self.debug = False
        self._proxies = {}

        self.plugin_proxy = plugin_proxy

        if plugins is not None:
            self.add_plugins(plugins)

    def clear(self):
        self._plugin = {
        }  # dict category -> plugin name -> Plugin class or Plugin proxy
        self._plugin_loaded = {}
        self._proxies = {}

    def set_proxy(self, category, plugin_proxy):
        """
        Embed all plugin for given category in plugin_proxy.
        """
        self._plugin_proxy[category] = plugin_proxy

    def add_plugin(self, category, plugin, plugin_proxy=None):
        if plugin_proxy is None and category in self._plugin_proxy:
            plugin_proxy = self._plugin_proxy[category]

        if plugin_proxy:
            plugin = plugin_proxy(plugin)

        try:
            name = plugin.name
        except AttributeError:
            name = plugin.__name__
        self._plugin.setdefault(category, {})[name] = plugin

    def add_plugins(self, plugins=None):
        if plugins is None:
            plugins = {}

        for category, plugin in plugins.iteritems():
            self.add_plugin(category, plugin)

    def _load_entry_point_plugin(self,
                                 category,
                                 entry_point,
                                 plugin_proxy=None):
        ep = entry_point
        identifier = '%s:%s:%s' % (category, ep.module_name, ep.name)
        plugin_class = None
        if identifier in self._plugin_loaded:
            plugin_class = self._plugin_loaded[identifier]
        else:
            if self.debug:
                plugin_class = ep.load()
                logger.debug('%s load plugin %s' %
                             (self.__class__.__name__, ep))
                self._plugin_loaded[identifier] = plugin_class
                self.add_plugin(category,
                                plugin_class,
                                plugin_proxy=plugin_proxy)
            else:
                try:
                    plugin_class = ep.load()
                except KeyboardInterrupt:
                    logger.error('%s: error loading %s ' % (category, ep))
                except Exception, e:
                    # never want a plugin load to kill the test run
                    # but we can't log here because the logger is not yet
                    # configured
                    warn("Unable to load plugin %s: %s" % (ep, e),
                         RuntimeWarning)
                else:
                    logger.debug('%s load plugin %s' %
                                 (self.__class__.__name__, ep))
                    self._plugin_loaded[identifier] = plugin_class
                    self.add_plugin(category,
                                    plugin_class,
                                    plugin_proxy=plugin_proxy)
Exemplo n.º 38
0
 def animate(self):
     self.currentWidget().applet.animate()
     logger.debug("Animate " + self.currentWidget().applet.name)
Exemplo n.º 39
0
 def uncomment(self):
     if hasattr(self.currentWidget(), "uncomment"):
         self.currentWidget().uncomment()
         logger.debug("uncomment " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method uncomment in " + self.currentWidget().applet.name)
Exemplo n.º 40
0
 def stop(self):
     self.currentWidget().applet.stop()
     logger.debug("Stop " + self.currentWidget().applet.name)
Exemplo n.º 41
0
 def search(self):
     if hasattr(self.currentWidget(), "search"):
         self.currentWidget().search()
         logger.debug("Search " + self.currentWidget().applet.name)
     else:
         logger.warning("Can't use method search in " + self.currentWidget().applet.name)
Exemplo n.º 42
0
 def animate(self):
     self.currentWidget().applet.animate()
     logger.debug("Animate " + self.currentWidget().applet.name)
Exemplo n.º 43
0
 def run(self):
     self.currentWidget().applet.run()
     logger.debug("Run " + self.currentWidget().applet.name)
Exemplo n.º 44
0
 def stop(self):
     self.currentWidget().applet.stop()
     logger.debug("Stop " + self.currentWidget().applet.name)