Beispiel #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)
Beispiel #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)
Beispiel #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)
Beispiel #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' %
Beispiel #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)
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)         
Beispiel #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)
Beispiel #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
Beispiel #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)
Beispiel #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
Beispiel #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
Beispiel #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
Beispiel #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")
Beispiel #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")
Beispiel #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)
Beispiel #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
Beispiel #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("")
Beispiel #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("")
Beispiel #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)
Beispiel #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)
Beispiel #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
Beispiel #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)
Beispiel #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)
Beispiel #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)
Beispiel #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))
Beispiel #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)
Beispiel #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)
Beispiel #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)
Beispiel #29
0
 def execute(self):
     self.currentWidget().applet.execute()
     logger.debug("Execute selected part " +
                  self.currentWidget().applet.name)
Beispiel #30
0
 def run(self):
     self.currentWidget().applet.run()
     logger.debug("Run " + self.currentWidget().applet.name)
Beispiel #31
0
 def run_in_shell(self):
     self.currentWidget().applet.run(run_in_shell=True)
     logger.debug("Run " + self.currentWidget().applet.name)
Beispiel #32
0
 def init(self):
     self.currentWidget().applet.init()
     logger.debug("Init " + self.currentWidget().applet.name)
Beispiel #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)
Beispiel #34
0
 def init(self):
     self.currentWidget().applet.init()
     logger.debug("Init " + self.currentWidget().applet.name)
Beispiel #35
0
 def execute(self):
     self.currentWidget().applet.execute()
     logger.debug("Execute selected part " + self.currentWidget().applet.name)
Beispiel #36
0
 def run_in_shell(self):
     self.currentWidget().applet.run(run_in_shell=True)
     logger.debug("Run " + self.currentWidget().applet.name)
Beispiel #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)
Beispiel #38
0
 def animate(self):
     self.currentWidget().applet.animate()
     logger.debug("Animate " + self.currentWidget().applet.name)
Beispiel #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)
Beispiel #40
0
 def stop(self):
     self.currentWidget().applet.stop()
     logger.debug("Stop " + self.currentWidget().applet.name)
Beispiel #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)
Beispiel #42
0
 def animate(self):
     self.currentWidget().applet.animate()
     logger.debug("Animate " + self.currentWidget().applet.name)
Beispiel #43
0
 def run(self):
     self.currentWidget().applet.run()
     logger.debug("Run " + self.currentWidget().applet.name)
Beispiel #44
0
 def stop(self):
     self.currentWidget().applet.stop()
     logger.debug("Stop " + self.currentWidget().applet.name)