Replace .config rather than reconstructing plugins, drivers, and UIs.
[hooke.git] / hooke / hooke.py
index 5fbc40bcd85cc0820df950e7ddab8c3c9151ee65..b9a659e77397d191ed913939b0bcb816d86378c3 100644 (file)
-#!/usr/bin/env python\r
-# -*- coding: utf-8 -*-\r
-\r
-'''\r
-HOOKE - A force spectroscopy review & analysis tool\r
-\r
-(C) 2008 Massimo Sandal\r
-\r
-Copyright (C) 2008 Massimo Sandal (University of Bologna, Italy).\r
-\r
-This program is released under the GNU General Public License version 2.\r
-'''\r
-\r
-from .libhooke import HOOKE_VERSION, WX_GOOD\r
-\r
-import os\r
-\r
-import wxversion\r
-wxversion.select(WX_GOOD)\r
-import wx\r
-import wxmpl\r
-from wx.lib.newevent import NewEvent\r
-\r
-import matplotlib.numerix as nx\r
-import scipy as sp\r
-\r
-from threading import Thread\r
-import Queue\r
-\r
-from .hooke_cli import HookeCli\r
-from .libhooke import HookeConfig, ClickedPoint\r
-from . import libhookecurve as lhc\r
-\r
-#import file versions, just to know with what we're working...\r
-from hooke_cli import __version__ as hookecli_version\r
-\r
-global __version__\r
-global events_from_gui\r
-global config\r
-global CLI_PLUGINS\r
-global GUI_PLUGINS\r
-global LOADED_PLUGINS\r
-global PLOTMANIP_PLUGINS\r
-global FILE_DRIVERS\r
-\r
-__version__=HOOKE_VERSION[0]\r
-__release_name__=HOOKE_VERSION[1]\r
-\r
-events_from_gui=Queue.Queue() #GUI ---> CLI COMMUNICATION\r
-\r
-print 'Starting Hooke.'\r
-#CONFIGURATION FILE PARSING\r
-config_obj=HookeConfig()\r
-config=config_obj.load_config('hooke.conf')\r
-\r
-#IMPORTING PLUGINS\r
-\r
-CLI_PLUGINS=[]\r
-GUI_PLUGINS=[]\r
-PLOTMANIP_PLUGINS=[]\r
-LOADED_PLUGINS=[]\r
-\r
-plugin_commands_namespaces=[]\r
-plugin_gui_namespaces=[]\r
-for plugin_name in config['plugins']:\r
-    try:\r
-        hooke_module=__import__('hooke.plugin.'+plugin_name)\r
-        plugin = getattr(hooke_module.plugin, plugin_name)\r
-        try:\r
-            #take Command plugin classes\r
-            commands = getattr(plugin, plugin_name+'Commands')\r
-            CLI_PLUGINS.append(commands)\r
-            plugin_commands_namespaces.append(dir(commands))\r
-        except:\r
-            pass\r
-        try:\r
-            #take Gui plugin classes\r
-            gui = getattr(plugin, plugin_name+'Gui')\r
-            GUI_PLUGINS.append(gui)\r
-            plugin_gui_namespaces.append(dir(gui))\r
-        except:\r
-            pass\r
-    except ImportError:\r
-        print 'Cannot find plugin ',plugin_name\r
-    else:\r
-        LOADED_PLUGINS.append(plugin_name)\r
-        print 'Imported plugin ',plugin_name\r
-\r
-#eliminate names common to all namespaces\r
-for i,namespace in enumerate(plugin_commands_namespaces):\r
-    plugin_commands_namespaces[i] = \\r
-        filter(lambda item : not (item.startswith('__')\r
-                                  or item == '_plug_init'),\r
-               namespace)\r
-#check for conflicts in namespaces between plugins\r
-#FIXME: only in commands now, because I don't have Gui plugins to check\r
-#FIXME: how to check for plugin-defined variables (self.stuff) ??\r
-plugin_commands_names=[]\r
-whatplugin_defines=[]\r
-plugin_gui_names=[]\r
-for namespace,plugin_name in zip(plugin_commands_namespaces, config['plugins']):\r
-    for item in namespace:\r
-        if item in plugin_commands_names:\r
-            i=plugin_commands_names.index(item) #we exploit the fact index gives the *first* occurrence of a name...\r
-            print 'Error. Plugin %s defines a function %s already defined by %s!' \\r
-                % (plugin_name, item, whatplugin_defines[i])\r
-            print 'This should not happen. Please disable one or both plugins and contact the plugin authors to solve the conflict.'\r
-            print 'Hooke cannot continue.'\r
-            exit()\r
-        else:\r
-            plugin_commands_names.append(item)\r
-            whatplugin_defines.append(plugin_name)\r
-\r
-\r
-config['loaded_plugins']=LOADED_PLUGINS #FIXME: kludge -this should be global but not in config!\r
-#IMPORTING DRIVERS\r
-#FIXME: code duplication\r
-FILE_DRIVERS=[]\r
-LOADED_DRIVERS=[]\r
-for driver_name in config['drivers']:\r
-    try:\r
-        hooke_module=__import__('hooke.driver.'+driver_name)\r
-        driver = getattr(hooke_module.driver, driver_name)\r
-        try:\r
-            FILE_DRIVERS.append(getattr(driver, driver_name+'Driver'))\r
-        except:\r
-            pass\r
-    except ImportError:\r
-        print 'Cannot find driver ',driver_name\r
-    else:\r
-        LOADED_DRIVERS.append(driver_name)\r
-        print 'Imported driver ',driver_name\r
-config['loaded_drivers']=LOADED_DRIVERS\r
-\r
-#LIST OF CUSTOM WX EVENTS FOR CLI ---> GUI COMMUNICATION\r
-#FIXME: do they need to be here?\r
-list_of_events={}\r
-\r
-plot_graph, EVT_PLOT = NewEvent()\r
-list_of_events['plot_graph']=plot_graph\r
-\r
-plot_contact, EVT_PLOT_CONTACT = NewEvent()\r
-list_of_events['plot_contact']=plot_contact\r
-\r
-measure_points, EVT_MEASURE_POINTS = NewEvent()\r
-list_of_events['measure_points']=measure_points\r
-\r
-export_image, EVT_EXPORT_IMAGE = NewEvent()\r
-list_of_events['export_image']=export_image\r
-\r
-close_plot, EVT_CLOSE_PLOT = NewEvent()\r
-list_of_events['close_plot'] = close_plot\r
-\r
-show_plots, EVT_SHOW_PLOTS = NewEvent()\r
-list_of_events['show_plots'] = show_plots\r
-\r
-get_displayed_plot, EVT_GET_DISPLAYED_PLOT = NewEvent()\r
-list_of_events['get_displayed_plot'] = get_displayed_plot\r
-#------------\r
-\r
-class CliThread(Thread):\r
-\r
-    def __init__(self,frame,list_of_events):\r
-        Thread.__init__(self)\r
-\r
-        #here we have to put temporary references to pass to the cli object.\r
-        self.frame=frame\r
-        self.list_of_events=list_of_events\r
-\r
-        self.debug=0 #to be used in the future\r
-\r
-    def run(self):\r
-        print '\n\nThis is Hooke, version',__version__ , __release_name__\r
-        print\r
-        print '(c) Massimo Sandal & others, 2006-2008. Released under the GNU Lesser General Public License Version 3'\r
-        print 'Hooke is Free software.'\r
-        print '----'\r
-        print ''\r
-\r
-        def make_command_class(*bases):\r
-            #FIXME: perhaps redundant\r
-            return type(HookeCli)("HookeCliPlugged", bases + (HookeCli,), {})\r
-        cli = make_command_class(*CLI_PLUGINS)(self.frame,self.list_of_events,events_from_gui,config,FILE_DRIVERS)\r
-        cli.cmdloop()\r
-\r
-'''\r
-GUI CODE\r
-\r
-FIXME: put it in a separate module in the future?\r
-'''\r
-class MainMenuBar(wx.MenuBar):\r
-    '''\r
-    Creates the menu bar\r
-    '''\r
-    def __init__(self):\r
-        wx.MenuBar.__init__(self)\r
-        '''the menu description. the key of the menu is XX&Menu, where XX is a number telling\r
-        the order of the menus on the menubar.\r
-        &Menu is the Menu text\r
-        the corresponding argument is ('&Item', 'itemname'), where &Item is the item text and itemname\r
-        the inner reference to use in the self.menu_items dictionary.\r
-\r
-        See create_menus() to see how it works\r
-\r
-        Note: the mechanism on page 124 of "wxPython in Action" is less awkward, maybe, but I want\r
-        binding to be performed later. Perhaps I'm wrong :)\r
-        ''' \r
-\r
-        self.menu_desc={'00&File':[('&Open playlist','openplaymenu'),('&Exit','exitmenu')], \r
-                        '01&Edit':[('&Export text...','exporttextmenu'),('&Export image...','exportimagemenu')],\r
-                        '02&Help':[('&About Hooke','aboutmenu')]}\r
-        self.create_menus()\r
-\r
-    def create_menus(self):\r
-        '''\r
-        Smartish routine to create the menu from the self.menu_desc dictionary\r
-        Hope it's a workable solution for the future.\r
-        '''\r
-        self.menus=[] #the menu objects to append to the menubar\r
-        self.menu_items={} #the single menu items dictionary, to bind to events\r
-\r
-        names=self.menu_desc.keys() #we gotta sort, because iterating keys goes in odd order\r
-        names.sort()\r
-\r
-        for name in names:\r
-            self.menus.append(wx.Menu())\r
-            for menu_item in self.menu_desc[name]:\r
-                self.menu_items[menu_item[1]]=self.menus[-1].Append(-1, menu_item[0])\r
-\r
-        for menu,name in zip(self.menus,names):\r
-            self.Append(menu,name[2:])\r
-\r
-class MainPanel(wx.Panel):\r
-    def __init__(self,parent,id):  \r
-\r
-        wx.Panel.__init__(self,parent,id)\r
-        self.splitter = wx.SplitterWindow(self)\r
-\r
-ID_FRAME=100        \r
-class MainWindow(wx.Frame):\r
-    '''we make a frame inheriting wx.Frame and setting up things on the init'''\r
-    def __init__(self,parent,id,title):\r
-\r
-        #-----------------------------\r
-        #WX WIDGETS INITIALIZATION\r
-\r
-        wx.Frame.__init__(self,parent,ID_FRAME,title,size=(800,600),style=wx.DEFAULT_FRAME_STYLE|wx.NO_FULL_REPAINT_ON_RESIZE)\r
-\r
-        self.mainpanel=MainPanel(self,-1)\r
-        self.cpanels=[]\r
-\r
-        self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
-        self.cpanels.append(wx.Panel(self.mainpanel.splitter,-1))\r
-\r
-        self.statusbar=wx.StatusBar(self,-1)\r
-        self.SetStatusBar(self.statusbar)\r
-\r
-        self.mainmenubar=MainMenuBar()\r
-        self.SetMenuBar(self.mainmenubar)\r
-\r
-        self.controls=[]\r
-        self.figures=[]\r
-        self.axes=[]\r
-\r
-        #This is our matplotlib plot\r
-        self.controls.append(wxmpl.PlotPanel(self.cpanels[0],-1))\r
-        self.controls.append(wxmpl.PlotPanel(self.cpanels[1],-1))\r
-        #These are our figure and axes, so to have easy references\r
-        #Also, we initialize\r
-        self.figures=[control.get_figure() for control in self.controls]\r
-        self.axes=[figure.gca() for figure in self.figures]\r
-\r
-       for i in range(len(self.axes)):\r
-         self.axes[i].xaxis.set_major_formatter(EngrFormatter())\r
-         self.axes[i].yaxis.set_major_formatter(EngrFormatter(2))\r
-\r
-\r
-        self.cpanels[1].Hide()\r
-        self.mainpanel.splitter.Initialize(self.cpanels[0])\r
-\r
-        self.sizer_dance() #place/size the widgets\r
-\r
-        self.controls[0].SetSize(self.cpanels[0].GetSize())\r
-        self.controls[1].SetSize(self.cpanels[1].GetSize())\r
-\r
-        #resize the frame to properly draw on Windows\r
-        frameSize=self.GetSize()\r
-        frameSize.DecBy(1, 1)\r
-        self.SetSize(frameSize)\r
-        '''\r
-        #if you need the exact same size as before DecBy, uncomment this block\r
-        frameSize.IncBy(1, 1)\r
-        self.SetSize(frameSize)\r
-        '''\r
-\r
-        #-------------------------------------------\r
-        #NON-WX WIDGETS INITIALIZATION\r
-\r
-        #Flags.\r
-        self.click_plot=0\r
-\r
-        #FIXME: These could become a single flag with different (string?) values\r
-        #self.on_measure_distance=False\r
-        #self.on_measure_force=False\r
-\r
-        self.plot_fit=False\r
-\r
-        #Number of points to be clicked\r
-        self.num_of_points = 2\r
-\r
-        #Data.\r
-        '''\r
-            self.current_x_ext=[[],[]]\r
-            self.current_y_ext=[[],[]]\r
-            self.current_x_ret=[[],[]]\r
-            self.current_y_ret=[[],[]]\r
-\r
-\r
-            self.current_x_unit=[None,None]\r
-            self.current_y_unit=[None,None]\r
-            '''\r
-\r
-        #Initialize xaxes, yaxes\r
-        #FIXME: should come from config\r
-        self.current_xaxes=0\r
-        self.current_yaxes=0\r
-\r
-        #Other\r
-\r
-\r
-        self.index_buffer=[]\r
-\r
-        self.clicked_points=[]\r
-\r
-        self.measure_set=None\r
-\r
-        self.events_from_gui = events_from_gui\r
-\r
-        '''\r
-            This dictionary keeps all the flags and the relative functon names that\r
-            have to be called when a point is clicked.\r
-            That is:\r
-            - if point is clicked AND foo_flag=True\r
-            - foo()\r
-\r
-            Conversely, foo_flag is True if a corresponding event is launched by the CLI.\r
-\r
-            self.ClickedPoints() takes care of handling this\r
-            '''\r
-\r
-        self.click_flags_functions={'measure_points':[False, 'MeasurePoints']}\r
-\r
-        #Binding of custom events from CLI --> GUI functions!                       \r
-        #FIXME: Should use the self.Bind() syntax\r
-        EVT_PLOT(self, self.PlotCurve)\r
-        EVT_PLOT_CONTACT(self, self.PlotContact)\r
-        EVT_GET_DISPLAYED_PLOT(self, self.OnGetDisplayedPlot)\r
-        EVT_MEASURE_POINTS(self, self.OnMeasurePoints)\r
-        EVT_EXPORT_IMAGE(self,self.ExportImage)\r
-        EVT_CLOSE_PLOT(self, self.OnClosePlot)\r
-        EVT_SHOW_PLOTS(self, self.OnShowPlots)\r
-\r
-        #This event and control decide what happens when I click on the plot 0.\r
-        wxmpl.EVT_POINT(self, self.controls[0].GetId(), self.ClickPoint0)\r
-        wxmpl.EVT_POINT(self, self.controls[1].GetId(), self.ClickPoint1)\r
-\r
-        #RUN PLUGIN-SPECIFIC INITIALIZATION\r
-        #make sure we execute _plug_init() for every command line plugin we import\r
-        for plugin_name in config['plugins']:\r
-            try:\r
-                hooke_module=__import__('hooke.plugin.'+plugin_name)\r
-                plugin = getattr(hooke_module.plugin, plugin_name)\r
-                try:\r
-                    eval('plugin.'+plugin_name+'Gui._plug_init(self)')\r
-                    pass\r
-                except AttributeError:\r
-                    pass\r
-            except ImportError:\r
-                pass\r
-\r
-\r
-\r
-    #WX-SPECIFIC FUNCTIONS\r
-    def sizer_dance(self):\r
-        '''\r
-            adjust size and placement of wxpython widgets.\r
-            '''\r
-        self.splittersizer = wx.BoxSizer(wx.VERTICAL)\r
-        self.splittersizer.Add(self.mainpanel.splitter, 1, wx.EXPAND)\r
-\r
-        self.plot1sizer = wx.BoxSizer()\r
-        self.plot1sizer.Add(self.controls[0], 1, wx.EXPAND)\r
-\r
-        self.plot2sizer = wx.BoxSizer()\r
-        self.plot2sizer.Add(self.controls[1], 1, wx.EXPAND)\r
-\r
-        self.panelsizer=wx.BoxSizer()\r
-        self.panelsizer.Add(self.mainpanel, -1, wx.EXPAND)\r
-\r
-        self.cpanels[0].SetSizer(self.plot1sizer)\r
-        self.cpanels[1].SetSizer(self.plot2sizer)\r
-\r
-        self.mainpanel.SetSizer(self.splittersizer)\r
-        self.SetSizer(self.panelsizer)\r
-\r
-    def binding_dance(self):\r
-        self.Bind(wx.EVT_MENU, self.OnOpenPlayMenu, self.menubar.menu_items['openplaymenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExitMenu, self.menubar.menu_items['exitmenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExportText, self.menubar.menu_items['exporttextmenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnExportImage, self.menubar.menu_items['exportimagemenu'])\r
-        self.Bind(wx.EVT_MENU, self.OnAboutMenu, self.menubar.menu_items['aboutmenu'])\r
-\r
-    # DOUBLE PLOT MANAGEMENT\r
-    #----------------------\r
-    def show_both(self):\r
-        '''\r
-            Shows both plots.\r
-            '''\r
-        self.mainpanel.splitter.SplitHorizontally(self.cpanels[0],self.cpanels[1])\r
-        self.mainpanel.splitter.SetSashGravity(0.5)\r
-        self.mainpanel.splitter.SetSashPosition(300) #FIXME: we should get it and restore it\r
-        self.mainpanel.splitter.UpdateSize()\r
-\r
-    def close_plot(self,plot):\r
-        '''\r
-            Closes one plot - only if it's open\r
-            '''\r
-        if not self.cpanels[plot].IsShown():\r
-            return\r
-        if plot != 0:\r
-            self.current_plot_dest = 0\r
-        else:\r
-            self.current_plot_dest = 1\r
-        self.cpanels[plot].Hide()\r
-        self.mainpanel.splitter.Unsplit(self.cpanels[plot])\r
-        self.mainpanel.splitter.UpdateSize()\r
-\r
-\r
-    def OnClosePlot(self,event):\r
-        self.close_plot(event.to_close)       \r
-\r
-    def OnShowPlots(self,event):\r
-        self.show_both()\r
-\r
-\r
-    #FILE MENU FUNCTIONS\r
-    #--------------------\r
-    def OnOpenPlayMenu(self, event):\r
-        pass \r
-\r
-    def OnExitMenu(self,event):\r
-        pass\r
-\r
-    def OnExportText(self,event):\r
-        pass\r
-\r
-    def OnExportImage(self,event):\r
-        pass\r
-\r
-    def OnAboutMenu(self,event):\r
-        pass\r
-\r
-    #PLOT INTERACTION    \r
-    #----------------                        \r
-    def PlotCurve(self,event):\r
-        '''\r
-            plots the current ext,ret curve.\r
-            '''\r
-        dest=0\r
-\r
-        #FIXME: BAD kludge following. There should be a well made plot queue mechanism, with replacements etc.\r
-        #---\r
-        #If we have only one plot in the event, we already have one in self.plots and this is a secondary plot,\r
-        #do not erase self.plots but append the new plot to it.\r
-        if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) == 1:\r
-            self.plots.append(event.plots[0])\r
-        #if we already have two plots and a new secondary plot comes, we substitute the previous\r
-        if len(event.plots) == 1 and event.plots[0].destination != 0 and len(self.plots) > 1:\r
-            self.plots[1] = event.plots[0]\r
-        else:\r
-            self.plots = event.plots\r
-\r
-        #FIXME. Should be in PlotObject, somehow\r
-        c=0\r
-        for plot in self.plots:\r
-            if self.plots[c].styles==[]:\r
-                self.plots[c].styles=[None for item in plot.vectors] \r
-            if self.plots[c].colors==[]:\r
-                self.plots[c].colors=[None for item in plot.vectors] \r
-\r
-        for plot in self.plots:\r
-            '''\r
-            MAIN LOOP FOR ALL PLOTS (now only 2 are allowed but...)\r
-            '''\r
-            if 'destination' in dir(plot):\r
-                dest=plot.destination\r
-\r
-            #if the requested panel is not shown, show it\r
-            if not ( self.cpanels[dest].IsShown() ):\r
-                self.show_both()\r
-\r
-            self.axes[dest].hold(False)\r
-            self.current_vectors=plot.vectors\r
-            self.current_title=plot.title\r
-            self.current_plot_dest=dest #let's try this way to take into account the destination plot...\r
-\r
-            c=0\r
-\r
-            if len(plot.colors)==0:\r
-                plot.colors=[None] * len(plot.vectors)\r
-            if len(plot.styles)==0:\r
-                plot.styles=[None] * len(plot.vectors)     \r
-\r
-            for vectors_to_plot in self.current_vectors: \r
-                if plot.styles[c]=='scatter':\r
-                    if plot.colors[c]==None:\r
-                        self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1])\r
-                    else:\r
-                        self.axes[dest].scatter(vectors_to_plot[0], vectors_to_plot[1],color=plot.colors[c])\r
-                else:\r
-                    if plot.colors[c]==None:\r
-                        self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1])\r
-                    else:\r
-                        self.axes[dest].plot(vectors_to_plot[0], vectors_to_plot[1], color=plot.colors[c])\r
-                self.axes[dest].hold(True)\r
-                c+=1\r
-\r
-            '''\r
-                for vectors_to_plot in self.current_vectors:\r
-                    if len(vectors_to_plot)==2: #3d plots are to come...\r
-                        if len(plot.styles) > 0 and plot.styles[c] == 'scatter':\r
-                            self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1])\r
-                        elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
-                            self.axes[dest].scatter(vectors_to_plot[0],vectors_to_plot[1],color='red')\r
-                        else:\r
-                            self.axes[dest].plot(vectors_to_plot[0],vectors_to_plot[1])\r
-\r
-                        self.axes[dest].hold(True)\r
-                        c+=1\r
-                    else:\r
-                        pass\r
-                '''               \r
-            #FIXME: tackles only 2d plots\r
-            self.axes[dest].set_xlabel(plot.units[0])\r
-            self.axes[dest].set_ylabel(plot.units[1])\r
-\r
-            #FIXME: set smaller fonts\r
-            self.axes[dest].set_title(plot.title)\r
-\r
-            if plot.xaxes: \r
-                #swap X axis\r
-                xlim=self.axes[dest].get_xlim()\r
-                self.axes[dest].set_xlim((xlim[1],xlim[0])) \r
-            if plot.yaxes:\r
-                #swap Y axis\r
-                ylim=self.axes[dest].get_ylim()        \r
-                self.axes[dest].set_ylim((ylim[1],ylim[0])) \r
-\r
-           for i in range(len(self.axes)):\r
-             self.axes[i].xaxis.set_major_formatter(EngrFormatter())\r
-             self.axes[i].yaxis.set_major_formatter(EngrFormatter(2))\r
-\r
-\r
-            self.controls[dest].draw()\r
-\r
-\r
-    def PlotContact(self,event):\r
-        '''\r
-            plots the contact point\r
-            DEPRECATED!\r
-            '''\r
-        self.axes[0].hold(True)\r
-        self.current_contact_index=event.contact_index\r
-\r
-        #now we fake a clicked point \r
-        self.clicked_points.append(ClickedPoint())\r
-        self.clicked_points[-1].absolute_coords=self.current_x_ret[dest][self.current_contact_index], self.current_y_ret[dest][self.current_contact_index]\r
-        self.clicked_points[-1].is_marker=True    \r
-\r
-        self._replot()\r
-        self.clicked_points=[]\r
-\r
-    def OnMeasurePoints(self,event):\r
-        '''\r
-            trigger flags to measure N points\r
-            '''\r
-        self.click_flags_functions['measure_points'][0]=True\r
-        if 'num_of_points' in dir(event):\r
-            self.num_of_points=event.num_of_points\r
-        if 'set' in dir(event):    \r
-            self.measure_set=event.set            \r
-\r
-    def ClickPoint0(self,event):\r
-        self.current_plot_dest=0\r
-        self.ClickPoint(event)\r
-    def ClickPoint1(self,event):\r
-        self.current_plot_dest=1\r
-        self.ClickPoint(event)\r
-\r
-    def ClickPoint(self,event):\r
-        '''\r
-            this function decides what to do when we receive a left click on the axes.\r
-            We trigger other functions:\r
-            - the action chosen by the CLI sends an event\r
-            - the event raises a flag : self.click_flags_functions['foo'][0]\r
-            - the raised flag wants the function in self.click_flags_functions[1] to be called after a click\r
-            '''\r
-        for key, value in self.click_flags_functions.items():\r
-            if value[0]:\r
-                eval('self.'+value[1]+'(event)')\r
-\r
-\r
-\r
-    def MeasurePoints(self,event,current_set=1):\r
-        dest=self.current_plot_dest\r
-        try:\r
-            current_set=self.measure_set\r
-        except AttributeError:\r
-            pass\r
-\r
-        #find the current plot matching the clicked destination\r
-        plot=self._plot_of_dest()\r
-        if len(plot.vectors)-1 < current_set: #what happens if current_set is 1 and we have only 1 vector?\r
-            current_set=current_set-len(plot.vectors)\r
-\r
-        xvector=plot.vectors[current_set][0]\r
-        yvector=plot.vectors[current_set][1]\r
-\r
-        self.clicked_points.append(ClickedPoint())            \r
-        self.clicked_points[-1].absolute_coords=event.xdata, event.ydata\r
-        self.clicked_points[-1].find_graph_coords(xvector,yvector)\r
-        self.clicked_points[-1].is_marker=True    \r
-        self.clicked_points[-1].is_line_edge=True\r
-        self.clicked_points[-1].dest=dest                \r
-\r
-        self._replot()\r
-\r
-        if len(self.clicked_points)==self.num_of_points:\r
-            self.events_from_gui.put(self.clicked_points)\r
-            #restore to default state:\r
-            self.clicked_points=[]\r
-            self.click_flags_functions['measure_points'][0]=False    \r
-\r
-\r
-    def OnGetDisplayedPlot(self,event):\r
-        if 'dest' in dir(event):\r
-            self.GetDisplayedPlot(event.dest)\r
-        else:\r
-            self.GetDisplayedPlot(self.current_plot_dest)\r
-\r
-    def GetDisplayedPlot(self,dest):\r
-        '''\r
-            returns to the CLI the currently displayed plot for the given destination\r
-            '''\r
-        displayed_plot=self._plot_of_dest(dest)\r
-        events_from_gui.put(displayed_plot)\r
-\r
-    def ExportImage(self,event):\r
-        '''\r
-            exports an image as a file.\r
-            Current supported file formats: png, eps\r
-            (matplotlib docs say that jpeg should be supported too, but with .jpg it doesn't work for me!)\r
-            '''\r
-        #dest=self.current_plot_dest\r
-        dest=event.dest\r
-        filename=event.name\r
-        self.figures[dest].savefig(filename)\r
-\r
-    '''\r
-        def _find_nearest_point(self, mypoint, dataset=1):\r
-\r
-            #Given a clicked point on the plot, finds the nearest point in the dataset (in X) that\r
-            #corresponds to the clicked point.\r
-\r
-            dest=self.current_plot_dest\r
-\r
-            xvector=plot.vectors[dataset][0]\r
-            yvector=plot.vectors[dataset][1]\r
-\r
-            #Ye Olde sorting algorithm...\r
-            #FIXME: is there a better solution?\r
-            index=0\r
-            best_index=0\r
-            best_diff=10^9 #hope we never go over this magic number :(\r
-            for point in xvector:\r
-                diff=abs(point-mypoint)\r
-                if diff<best_diff:\r
-                    best_index=index\r
-                    best_diff=diff\r
-                index+=1\r
-\r
-            return best_index,xvector[best_index],yvector[best_index]\r
-         '''   \r
-\r
-    def _plot_of_dest(self,dest=None):\r
-        '''\r
-            returns the plot that has the current destination\r
-            '''\r
-        if dest==None:\r
-            dest=self.current_plot_dest\r
-        try:\r
-          plot=None\r
-          for aplot in self.plots:\r
-              if aplot.destination == dest:\r
-                  plot=aplot\r
-          return plot\r
-        except:\r
-           print "No curve available"\r
-           return None\r
-\r
-    def _replot(self):\r
-        '''\r
-            this routine is needed for a fresh clean-and-replot of interface\r
-            otherwise, refreshing works very badly :(\r
-\r
-            thanks to Ken McIvor, wxmpl author!\r
-            '''\r
-        dest=self.current_plot_dest\r
-        #we get current zoom limits\r
-        xlim=self.axes[dest].get_xlim()\r
-        ylim=self.axes[dest].get_ylim()           \r
-        #clear axes\r
-        self.axes[dest].cla()\r
-\r
-        #Plot curve:         \r
-        #find the current plot matching the clicked destination\r
-        plot=self._plot_of_dest()\r
-        #plot all superimposed plots \r
-        c=0 \r
-        if len(plot.colors)==0:\r
-            plot.colors=[None] * len(plot.vectors)\r
-        if len(plot.styles)==0:\r
-            plot.styles=[None] * len(plot.vectors)     \r
-        for plotset in plot.vectors: \r
-            if plot.styles[c]=='scatter':\r
-                if plot.colors[c]==None:\r
-                    self.axes[dest].scatter(plotset[0], plotset[1])\r
-                else:\r
-                    self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
-            else:\r
-                if plot.colors[c]==None:\r
-                    self.axes[dest].plot(plotset[0], plotset[1])\r
-                else:\r
-                    self.axes[dest].plot(plotset[0], plotset[1], color=plot.colors[c])\r
-            '''    \r
-                if len(plot.styles) > 0 and plot.styles[c]=='scatter':\r
-                    self.axes[dest].scatter(plotset[0], plotset[1],color=plot.colors[c])\r
-                elif len(plot.styles) > 0 and plot.styles[c] == 'scatter_red':\r
-                    self.axes[dest].scatter(plotset[0],plotset[1],color='red')\r
-                else:\r
-                    self.axes[dest].plot(plotset[0], plotset[1])\r
-                '''\r
-            c+=1\r
-        #plot points we have clicked\r
-        for item in self.clicked_points:\r
-            if item.is_marker:\r
-                if item.graph_coords==(None,None): #if we have no graph coords, we display absolute coords\r
-                    self.axes[dest].scatter([item.absolute_coords[0]],[item.absolute_coords[1]])\r
-                else:\r
-                    self.axes[dest].scatter([item.graph_coords[0]],[item.graph_coords[1]])               \r
-\r
-        if self.plot_fit:\r
-            print 'DEBUGGING WARNING: use of self.plot_fit is deprecated!'\r
-            self.axes[dest].plot(self.plot_fit[0],self.plot_fit[1])\r
-\r
-        self.axes[dest].hold(True)      \r
-        #set old axes again\r
-        self.axes[dest].set_xlim(xlim)\r
-        self.axes[dest].set_ylim(ylim)\r
-        #set title and names again...\r
-        self.axes[dest].set_title(self.current_title)           \r
-        self.axes[dest].set_xlabel(plot.units[0])\r
-        self.axes[dest].set_ylabel(plot.units[1])\r
-        #and redraw!\r
-        self.controls[dest].draw()\r
-\r
-\r
-class MySplashScreen(wx.SplashScreen):\r
-    """\r
-    Create a splash screen widget.\r
-    That's just a fancy addition... every serious application has a splash screen!\r
-    """\r
-    def __init__(self, frame):\r
-        # This is a recipe to a the screen.\r
-        # Modify the following variables as necessary.\r
-        #aBitmap = wx.Image(name = "wxPyWiki.jpg").ConvertToBitmap()\r
-        aBitmap=wx.Image(name=os.path.join(\r
-                config['install']['docpath'],\r
-                'hooke.jpg')).ConvertToBitmap()\r
-        splashStyle = wx.SPLASH_CENTRE_ON_SCREEN | wx.SPLASH_TIMEOUT\r
-        splashDuration = 2000 # milliseconds\r
-        splashCallback = None\r
-        # Call the constructor with the above arguments in exactly the\r
-        # following order.\r
-        wx.SplashScreen.__init__(self, aBitmap, splashStyle,\r
-                                 splashDuration, None, -1)\r
-        wx.EVT_CLOSE(self, self.OnExit)\r
-        self.frame=frame\r
-        wx.Yield()\r
-\r
-    def OnExit(self, evt):\r
-        self.Hide()\r
-\r
-        self.frame.Show()\r
-        # The program will freeze without this line.\r
-        evt.Skip()  # Make sure the default handler runs too...\r
-\r
-\r
-#------------------------------------------------------------------------------\r
-\r
-def main():\r
-    app=wx.PySimpleApp()\r
-\r
-    def make_gui_class(*bases):\r
-        return type(MainWindow)("MainWindowPlugged", bases + (MainWindow,), {})\r
-\r
-    main_frame = make_gui_class(*GUI_PLUGINS)(None, -1, ('Hooke '+__version__))\r
-\r
-    #FIXME. The frame.Show() is called by the splashscreen here! Ugly as hell.\r
-\r
-    mysplash=MySplashScreen(main_frame)\r
-    mysplash.Show()\r
-\r
-    my_cmdline=CliThread(main_frame, list_of_events)\r
-    my_cmdline.start()\r
-\r
-    app.MainLoop()\r
-\r
-if __name__ == '__main__':\r
-    main()\r
+# Copyright (C) 2008-2010 Fabrizio Benedetti
+#                         Massimo Sandal <devicerandom@gmail.com>
+#                         Rolf Schmidt <rschmidt@alcor.concordia.ca>
+#                         W. Trevor King <wking@drexel.edu>
+#
+# This file is part of Hooke.
+#
+# Hooke is free software: you can redistribute it and/or modify it
+# under the terms of the GNU Lesser General Public License as
+# published by the Free Software Foundation, either version 3 of the
+# License, or (at your option) any later version.
+#
+# Hooke is distributed in the hope that it will be useful, but WITHOUT
+# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
+# or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General
+# Public License for more details.
+#
+# You should have received a copy of the GNU Lesser General Public
+# License along with Hooke.  If not, see
+# <http://www.gnu.org/licenses/>.
+
+"""Hooke - A force spectroscopy review & analysis tool.
+"""
+
+if False: # Queue pickle error debugging code
+    """The Hooke class is passed back from the CommandEngine process
+    to the main process via a :class:`multiprocessing.queues.Queue`,
+    which uses :mod:`pickle` for serialization.  There are a number of
+    objects that are unpicklable, and the error messages are not
+    always helpful.  This block of code hooks you into the Queue's
+    _feed method so you can print out useful tidbits to help find the
+    particular object that is gumming up the pickle works.
+    """
+    import multiprocessing.queues
+    import sys
+    feed = multiprocessing.queues.Queue._feed
+    def new_feed (buffer, notempty, send, writelock, close):
+        def s(obj):
+            print 'SEND:', obj, dir(obj)
+            for a in dir(obj):
+                attr = getattr(obj, a)
+                #print '  ', a, attr, type(attr)
+            if obj.__class__.__name__ == 'Hooke':
+                # Set suspect attributes to None until you resolve the
+                # PicklingError.  Then fix whatever is breaking the
+                # pickling.
+                #obj.commands = None
+                #obj.drivers = None
+                #obj.plugins = None
+                #obj.ui = None
+                pass
+            sys.stdout.flush()
+            send(obj)
+        feed(buffer, notempty, s, writelock, close)
+    multiprocessing.queues.Queue._feed = staticmethod(new_feed)
+
+from ConfigParser import NoSectionError
+import logging
+import logging.config
+import multiprocessing
+import optparse
+import os.path
+import Queue
+import unittest
+import StringIO
+import sys
+
+from . import version
+from . import engine
+from . import config as config_mod
+from . import playlist
+from . import plugin as plugin_mod
+from . import driver as driver_mod
+from . import ui
+
+
+class Hooke (object):
+    def __init__(self, config=None, debug=0):
+        self.debug = debug
+        default_settings = (config_mod.DEFAULT_SETTINGS
+                            + plugin_mod.default_settings()
+                            + driver_mod.default_settings()
+                            + ui.default_settings())
+        if config == None:
+            config = config_mod.HookeConfigParser(
+                paths=config_mod.DEFAULT_PATHS,
+                default_settings=default_settings)
+            config.read()
+        self.config = config
+        self.load_log()
+        self.load_plugins()
+        self.load_drivers()
+        self.load_ui()
+        self.engine = engine.CommandEngine()
+        self.playlists = playlist.NoteIndexList()
+
+    def load_log(self):
+        config_file = StringIO.StringIO()
+        self.config.write(config_file)
+        logging.config.fileConfig(StringIO.StringIO(config_file.getvalue()))
+        # Don't attach the logger because it contains an unpicklable
+        # thread.lock.  Instead, grab it directly every time you need it.
+        #self.log = logging.getLogger('hooke')
+
+    def load_plugins(self):
+        self.plugins = plugin_mod.load_graph(
+            plugin_mod.PLUGIN_GRAPH, self.config, include_section='plugins')
+        self.configure_plugins()
+        self.commands = []
+        for plugin in self.plugins:
+            self.commands.extend(plugin.commands())
+        self.command_by_name = dict(
+            [(c.name, c) for c in self.commands])
+
+    def load_drivers(self):
+        self.drivers = plugin_mod.load_graph(
+            driver_mod.DRIVER_GRAPH, self.config, include_section='drivers')
+        self.configure_drivers()
+
+    def load_ui(self):
+        self.ui = ui.load_ui(self.config)
+        self.configure_ui()
+
+    def configure_plugins(self):
+        for plugin in self.plugins:
+            self._configure_item(plugin)
+
+    def configure_drivers(self):
+        for driver in self.drivers:
+            self._configure_item(driver)
+
+    def configure_ui(self):
+        self._configure_item(self.ui)
+
+    def _configure_item(self, item):
+        conditions = self.config.items('conditions')
+        try:
+            item.config = dict(self.config.items(item.setting_section))
+        except NoSectionError:
+            item.config = {}
+        for key,value in conditions:
+            if key not in item.config:
+                item.config[key] = value
+
+    def close(self, save_config=False):
+        if save_config == True:
+            self.config.write()  # Does not preserve original comments
+
+    def run_command(self, command, arguments):
+        """Run the command named `command` with `arguments` using
+        :meth:`~hooke.engine.CommandEngine.run_command`.
+
+        Allows for running commands without spawning another process
+        as in :class:`HookeRunner`.
+        """
+        self.engine.run_command(self, command, arguments)
+
+
+class HookeRunner (object):
+    def run(self, hooke):
+        """Run Hooke's main execution loop.
+
+        Spawns a :class:`hooke.engine.CommandEngine` subprocess and
+        then runs the UI, rejoining the `CommandEngine` process after
+        the UI exits.
+        """
+        ui_to_command,command_to_ui,command = self._setup_run(hooke)
+        try:
+            hooke.ui.run(hooke.commands, ui_to_command, command_to_ui)
+        finally:
+            hooke = self._cleanup_run(ui_to_command, command_to_ui, command)
+        return hooke
+
+    def run_lines(self, hooke, lines):
+        """Run the pre-set commands `lines` with the "command line" UI.
+
+        Allows for non-interactive sessions that are otherwise
+        equivalent to :meth:'.run'.
+        """
+        cmdline = ui.load_ui(hooke.config, 'command line')
+        ui_to_command,command_to_ui,command = self._setup_run(hooke)
+        try:
+            cmdline.run_lines(
+                hooke.commands, ui_to_command, command_to_ui, lines)
+        finally:
+            hooke = self._cleanup_run(ui_to_command, command_to_ui, command)
+        return hooke
+
+    def _setup_run(self, hooke):
+        ui_to_command = multiprocessing.Queue()
+        command_to_ui = multiprocessing.Queue()
+        manager = multiprocessing.Manager()
+        command = multiprocessing.Process(name='command engine',
+            target=hooke.engine.run, args=(hooke, ui_to_command, command_to_ui))
+        command.start()
+        hooke.engine = None  # no more need for the UI-side version.
+        return (ui_to_command, command_to_ui, command)
+
+    def _cleanup_run(self, ui_to_command, command_to_ui, command):
+        log = logging.getLogger('hooke')
+        log.debug('cleanup sending CloseEngine')
+        ui_to_command.put(engine.CloseEngine())
+        hooke = None
+        while not isinstance(hooke, Hooke):
+            log.debug('cleanup waiting for Hooke instance from the engine.')
+            hooke = command_to_ui.get(block=True)
+            log.debug('cleanup got %s instance' % type(hooke))
+        command.join()
+        return hooke
+
+
+def main():
+    p = optparse.OptionParser()
+    p.add_option(
+        '--version', dest='version', default=False, action='store_true',
+        help="Print Hooke's version information and exit.")
+    p.add_option(
+        '-s', '--script', dest='script', metavar='FILE',
+        help='Script of command line Hooke commands to run.')
+    p.add_option(
+        '-c', '--command', dest='commands', metavar='COMMAND',
+        action='append', default=[],
+        help='Add a command line Hooke command to run.')
+    p.add_option(
+        '-p', '--persist', dest='persist', action='store_true', default=False,
+        help="Don't exit after running a script or commands.")
+    p.add_option(
+        '--save-config', dest='save_config',
+        action='store_true', default=False,
+        help="Automatically save a changed configuration on exit.")
+    p.add_option(
+        '--debug', dest='debug', action='store_true', default=False,
+        help="Enable debug logging.")
+    options,arguments = p.parse_args()
+    if len(arguments) > 0:
+        print >> sys.stderr, 'More than 0 arguments to %s: %s' \
+            % (sys.argv[0], arguments)
+        p.print_help(sys.stderr)
+        sys.exit(1)
+
+    hooke = Hooke(debug=__debug__)
+    runner = HookeRunner()
+
+    if options.version == True:
+        print version()
+        sys.exit(0)
+    if options.debug == True:
+        hooke.config.set(
+            section='handler_hand1', option='level', value='NOTSET')
+        hooke.load_log()
+    if options.script != None:
+        with open(os.path.expanduser(options.script), 'r') as f:
+            options.commands.extend(f.readlines())
+    if len(options.commands) > 0:
+        try:
+            hooke = runner.run_lines(hooke, options.commands)
+        finally:
+            if options.persist == False:
+                hooke.close(save_config=options.save_config)
+                sys.exit(0)
+
+    try:
+        hooke = runner.run(hooke)
+    finally:
+        hooke.close(save_config=options.save_config)