import pkg_resources
import wx
import os

def load_plugins(wxframe):
    PluginClasses = []
    loaded_components = []
    pkg_env = pkg_resources.Environment()
    for name in pkg_env:
        egg = pkg_env[name][0]
        modules = []

        for name in egg.get_entry_map('motmot.fview.plugins'):
            egg.activate()
            entry_point = egg.get_entry_info('motmot.fview.plugins', name)
            if entry_point.module_name not in loaded_components:
                try:
                    PluginClass = entry_point.load()
                except Exception,x:
                    if int(os.environ.get('FVIEW_RAISE_ERRORS','0')):
                        raise
                    else:
                        import warnings
                        warnings.warn('could not load plugin (set env var FVIEW_RAISE_ERRORS to raise error) %s: %s'%(str(entry_point),str(x)))
                        continue
                PluginClasses.append( PluginClass )
                modules.append(entry_point.module_name)
                loaded_components.append(entry_point.module_name)
    # make instances of plugins
    plugins = [PluginClass(wxframe) for PluginClass in PluginClasses]
    plugin_dict = {}
    for plugin in plugins:
        class PluginHelper:
            def __init__(self,plugin):
                self.plugin = plugin
                self.frame = plugin.get_frame()
                wx.EVT_CLOSE(self.frame, self.OnWindowClose)
            def OnWindowClose(self,event):
                # don't really close the window, just hide it
                self.frame.Show(False)
            def OnShowFrame(self,event):
                self.frame.Show(True)
        plugin_dict[plugin] = PluginHelper(plugin)
    return plugins, plugin_dict

@@ -33,16 +33,43 @@
 mport os
+%0Aimport warnings, traceback
 %0A%0Adef lo
@@ -749,31 +749,57 @@
         
-import warnings
+formatted_error = traceback.format_exc(x)
 %0A       
@@ -869,76 +869,822 @@
 var 
-FVIEW_RAISE_ERRORS to raise error) %25s: %25s'%25(str(entry_point),str(x))
+'%0A                                      'FVIEW_RAISE_ERRORS to raise error) '%0A                                      '%25s: %25s%5Cn%25s'%25(str(entry_point),str(x),%0A                                                    formatted_error))%0A                        msg = 'While attempting to open the plugin %22%25s%22,%5Cn' %5C%0A                              'FView encountered an error. The error is:%5Cn%5Cn' %5C%0A                              '%25s%5Cn%5Cn' %5C%0A                              'More details:%5Cn' %5C%0A                              '%25s'%25( name, x, formatted_error )%0A                        dlg = wx.MessageDialog(wxframe, msg,%0A                                               'FView plugin error',%0A                                               wx.OK %7C wx.ICON_ERROR)%0A                        dlg.ShowModal()%0A                        dlg.Destroy(
 )%0A  

raise warning dialogs when plugin load error happens