Added hooke.plugin.playlist.ApplyCommandStack and related changes.
[hooke.git] / hooke / hooke.py
index 3662b51ba2219151a76f4c47751b5178c3fc1996..c475d3acb756d42bdff14328f84990f20659fa02 100644 (file)
-#!/usr/bin/env python\r
-\r
-'''\r
-HOOKE - A force spectroscopy review & analysis tool\r
-\r
-Copyright (C) 2008-2010 Massimo Sandal (University of Bologna, Italy).\r
-                        Rolf Schmidt (Concordia University, Canada).\r
-\r
-This program is released under the GNU General Public License version 2.\r
-'''\r
-\r
-from libhooke import WX_GOOD\r
-\r
-import wxversion\r
-wxversion.select(WX_GOOD)\r
-import copy\r
-import cStringIO\r
-import os\r
-import os.path\r
-import sys\r
-import glob\r
-import time\r
-\r
-import imp\r
-import wx\r
-import wx.html\r
-import wx.aui\r
-import wxmpl\r
-import wx.lib.agw.aui as aui\r
-import wx.propgrid as wxpg\r
-\r
-import libhooke as lh\r
-from config import config\r
-import drivers\r
-import plugins\r
-import hookecommands\r
-import hookeplaylist\r
-import hookepropertyeditor\r
-import hookeresults\r
-import playlist\r
-\r
-global __version__\r
-\r
-__version__ = lh.HOOKE_VERSION[0]\r
-__release_name__ = lh.HOOKE_VERSION[1]\r
-\r
-#TODO: order menu items, get rid of all unused IDs\r
-ID_ExportText = wx.NewId()\r
-ID_ExportImage = wx.NewId()\r
-ID_Config = wx.NewId()\r
-ID_About = wx.NewId()\r
-ID_Next = wx.NewId()\r
-ID_Previous = wx.NewId()\r
-\r
-ID_ViewAssistant = wx.NewId()\r
-ID_ViewCommands = wx.NewId()\r
-ID_ViewFolders = wx.NewId()\r
-ID_ViewOutput = wx.NewId()\r
-ID_ViewPlaylists = wx.NewId()\r
-ID_ViewProperties = wx.NewId()\r
-ID_ViewResults = wx.NewId()\r
-\r
-ID_CommandsList = wx.NewId()\r
-ID_CommandsListBox = wx.NewId()\r
-\r
-ID_TextContent = wx.NewId()\r
-ID_TreeContent = wx.NewId()\r
-ID_HTMLContent = wx.NewId()\r
-ID_SizeReportContent = wx.NewId()\r
-ID_DeletePerspective = wx.NewId()\r
-ID_SavePerspective = wx.NewId()\r
-\r
-ID_FirstPerspective = ID_SavePerspective + 1000\r
-#I hope we'll never have more than 1000 perspectives\r
-ID_FirstPlot = ID_SavePerspective + 2000\r
-\r
-class Hooke(wx.App):\r
-\r
-    def OnInit(self):\r
-        self.SetAppName('Hooke')\r
-        self.SetVendorName('')\r
-\r
-        #set the Hooke directory\r
-        lh.hookeDir = os.path.abspath(os.path.dirname(__file__))\r
-\r
-        windowPosition = (config['main']['left'], config['main']['top'])\r
-        windowSize = (config['main']['width'], config['main']['height'])\r
-\r
-        #setup the splashscreen\r
-        if config['splashscreen']['show']:\r
-            filename = lh.get_file_path('hooke.jpg', ['resources'])\r
-            if os.path.isfile(filename):\r
-                bitmap = wx.Image(filename).ConvertToBitmap()\r
-                splashStyle = wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT\r
-                splashDuration = config['splashscreen']['duration']\r
-                wx.SplashScreen(bitmap, splashStyle, splashDuration, None, -1)\r
-                wx.Yield()\r
-                '''\r
-                we need for the splash screen to disappear\r
-                for whatever reason splashDuration and sleep do not correspond to each other\r
-                at least not on Windows\r
-                maybe it's because duration is in milliseconds and sleep in seconds\r
-                thus we need to increase the sleep time a bit\r
-                a factor of 1.2 seems to work quite well\r
-                '''\r
-                sleepFactor = 1.2\r
-                time.sleep(sleepFactor * splashDuration / 1000)\r
-\r
-        plugin_objects = []\r
-        for plugin in config['plugins']:\r
-            if config['plugins'][plugin]:\r
-                filename = ''.join([plugin, '.py'])\r
-                path = lh.get_file_path(filename, ['plugins'])\r
-                if os.path.isfile(path):\r
-                    #get the corresponding filename and path\r
-                    plugin_name = ''.join(['plugins.', plugin])\r
-                    module = __import__(plugin_name)\r
-                    #get the file that contains the plugin\r
-                    class_file = getattr(plugins, plugin)\r
-                    #get the class that contains the commands\r
-                    class_object = getattr(class_file, plugin + 'Commands')\r
-                    plugin_objects.append(class_object)\r
-\r
-        def make_command_class(*bases):\r
-            #create metaclass with plugins and plotmanipulators\r
-            return type(HookeFrame)("HookeFramePlugged", bases + (HookeFrame,), {})\r
-        frame = make_command_class(*plugin_objects)(parent=None, id=wx.ID_ANY, title='Hooke', pos=windowPosition, size=windowSize)\r
-        frame.Show(True)\r
-        self.SetTopWindow(frame)\r
-\r
-        return True\r
-\r
-    def OnExit(self):\r
-        #TODO: write values to ini file if necessary\r
-        return True\r
-\r
-\r
-class HookeFrame(wx.Frame):\r
-\r
-    def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN):\r
-        #call parent constructor\r
-        wx.Frame.__init__(self, parent, id, title, pos, size, style)\r
-        self.config = config\r
-        self.CreateApplicationIcon()\r
-        #self.configs contains: {the name of the Commands file: corresponding ConfigObj}\r
-        self.configs = {}\r
-        ##self.playlists contains: {the name of the playlist: [playlist, tabIndex, plotID]}\r
-        #self.playlists = {}\r
-        #self.plugins contains: {the name of the plugin: [caption, function]}\r
-        self.plugins = {}\r
-        #self.plotmanipulators list contains: [the name of the plotmanip, function, name of the module]\r
-        self.plotmanipulators = []\r
-\r
-        #tell FrameManager to manage this frame\r
-        self._mgr = aui.AuiManager()\r
-        self._mgr.SetManagedWindow(self)\r
-        #set the gradient style\r
-        self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)\r
-        #set transparent drag\r
-        self._mgr.SetFlags(self._mgr.GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)\r
-\r
-        # set up default notebook style\r
-        self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER\r
-        self._notebook_theme = 0\r
-\r
-        #holds the perspectives: {name, [index, perspectiveStr]}\r
-        self._perspectives = {}\r
-\r
-        # min size for the frame itself isn't completely done.\r
-        # see the end up FrameManager::Update() for the test\r
-        # code. For now, just hard code a frame minimum size\r
-        self.SetMinSize(wx.Size(400, 300))\r
-        #create panels here\r
-        self.panelAssistant = self.CreatePanelAssistant()\r
-        self.panelCommands = self.CreatePanelCommands()\r
-        self.panelFolders = self.CreatePanelFolders()\r
-        self.panelPlaylists = self.CreatePanelPlaylists()\r
-        self.panelProperties = self.CreatePanelProperties()\r
-        self.panelOutput = self.CreatePanelOutput()\r
-        self.panelResults = self.CreatePanelResults()\r
-        self.plotNotebook = self.CreateNotebook()\r
-        #self.textCtrlCommandLine=self.CreateCommandLine()\r
-\r
-        # add panes\r
-        self._mgr.AddPane(self.panelFolders, aui.AuiPaneInfo().Name('Folders').Caption('Folders').Left().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.panelPlaylists, aui.AuiPaneInfo().Name('Playlists').Caption('Playlists').Left().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.plotNotebook, aui.AuiPaneInfo().Name('Plots').CenterPane().PaneBorder(False))\r
-        self._mgr.AddPane(self.panelCommands, aui.AuiPaneInfo().Name('Commands').Caption('Settings and commands').Right().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.panelProperties, aui.AuiPaneInfo().Name('Properties').Caption('Properties').Right().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.panelAssistant, aui.AuiPaneInfo().Name('Assistant').Caption('Assistant').Right().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.panelOutput, aui.AuiPaneInfo().Name('Output').Caption('Output').Bottom().CloseButton(True).MaximizeButton(False))\r
-        self._mgr.AddPane(self.panelResults, aui.AuiPaneInfo().Name('Results').Caption('Results').Bottom().CloseButton(True).MaximizeButton(False))\r
-        #self._mgr.AddPane(self.textCtrlCommandLine, aui.AuiPaneInfo().Name('CommandLine').CaptionVisible(False).Fixed().Bottom().Layer(2).CloseButton(False).MaximizeButton(False))\r
-        #self._mgr.AddPane(panelBottom, aui.AuiPaneInfo().Name("panelCommandLine").Bottom().Position(1).CloseButton(False).MaximizeButton(False))\r
-\r
-        # add the toolbars to the manager\r
-        self.toolbar=self.CreateToolBar()\r
-        self.toolbarNavigation=self.CreateToolBarNavigation()\r
-        self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Name('toolbar').Caption('Toolbar').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))\r
-        self._mgr.AddPane(self.toolbarNavigation, aui.AuiPaneInfo().Name('toolbarNavigation').Caption('Navigation').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))\r
-        # "commit" all changes made to FrameManager\r
-        self._mgr.Update()\r
-        #create the menubar after the panes so that the default perspective\r
-        #is created with all panes open\r
-        self.CreateMenuBar()\r
-        self.statusbar = self.CreateStatusBar()\r
-        self._BindEvents()\r
-        #TODO: select item on startup (whatever item)\r
-        #self.listCtrlCommands.Select(0)\r
-        #self.OnListboxSelect(None)\r
-        name = self.config['perspectives']['active']\r
-        menu_item = self.GetPerspectiveMenuItem(name)\r
-        self.OnRestorePerspective(menu_item)\r
-        self.playlists = self.panelPlaylists.Playlists\r
-        #define the list of active drivers\r
-        self.drivers = []\r
-        for driver in self.config['drivers']:\r
-            if self.config['drivers'][driver]:\r
-                #get the corresponding filename and path\r
-                filename = ''.join([driver, '.py'])\r
-                path = lh.get_file_path(filename, ['drivers'])\r
-                #the driver is active for driver[1] == 1\r
-                if os.path.isfile(path):\r
-                    #driver files are located in the 'drivers' subfolder\r
-                    driver_name = ''.join(['drivers.', driver])\r
-                    module = __import__(driver_name)\r
-                    class_file = getattr(drivers, driver)\r
-                    for command in dir(class_file):\r
-                        if command.endswith('Driver'):\r
-                            self.drivers.append(getattr(class_file, command))\r
-        #import all active plugins and plotmanips\r
-        #the plotmanip_functions contains: {the name of the plotmanip: [method, class_object]}\r
-        plotmanip_functions = {}\r
-        #add 'general.ini' to self.configs (this is not a plugin and thus must be imported seperately)\r
-        ini_path = lh.get_file_path('general.ini', ['plugins'])\r
-        plugin_config = ConfigObj(ini_path)\r
-        #self.config.merge(plugin_config)\r
-        self.configs['general'] = plugin_config\r
-        #make sure we execute _plug_init() for every command line plugin we import\r
-        for plugin in self.config['plugins']:\r
-            if self.config['plugins'][plugin]:\r
-                filename = ''.join([plugin, '.py'])\r
-                path = lh.get_file_path(filename, ['plugins'])\r
-                if os.path.isfile(path):\r
-                    #get the corresponding filename and path\r
-                    plugin_name = ''.join(['plugins.', plugin])\r
-                    try:\r
-                        #import the module\r
-                        module = __import__(plugin_name)\r
-                        #prepare the ini file for inclusion\r
-                        ini_path = path.replace('.py', '.ini')\r
-                        #include ini file\r
-                        plugin_config = ConfigObj(ini_path)\r
-                        #self.config.merge(plugin_config)\r
-                        self.configs[plugin] = plugin_config\r
-                        #add to plugins\r
-                        commands = eval('dir(module.' + plugin+ '.' + plugin + 'Commands)')\r
-                        #keep only commands (ie names that start with 'do_')\r
-                        commands = [command for command in commands if command.startswith('do_')]\r
-                        if commands:\r
-                            self.plugins[plugin] = commands\r
-                        try:\r
-                            #initialize the plugin\r
-                            eval('module.' + plugin+ '.' + plugin + 'Commands._plug_init(self)')\r
-                        except AttributeError:\r
-                            pass\r
-                    except ImportError:\r
-                        pass\r
-        #initialize the commands tree\r
-        commands = dir(HookeFrame)\r
-        commands = [command for command in commands if command.startswith('do_')]\r
-        if commands:\r
-            self.plugins['general'] = commands\r
-        self.panelCommands.Initialize(self.plugins)\r
-        for command in dir(self):\r
-            if command.startswith('plotmanip_'):\r
-                plotmanip_functions[command] = [command, getattr(self, command)]\r
-        for name in self.config['plotmanipulators']['names']:\r
-            if self.config['plotmanipulators'].as_bool(name):\r
-                command_name = ''.join(['plotmanip_', name])\r
-                if command_name in plotmanip_functions:\r
-                    self.plotmanipulators.append(plotmanip_functions[command_name])\r
-        #load default list, if possible\r
-        self.do_loadlist(self.config['general']['list'])\r
-\r
-    def _BindEvents(self):\r
-        self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)\r
-        self.Bind(wx.EVT_SIZE, self.OnSize)\r
-        self.Bind(wx.EVT_CLOSE, self.OnClose)\r
-        # Show How To Use The Closing Panes Event\r
-        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)\r
-        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnNotebookPageClose)\r
-        #menu\r
-        self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)\r
-        self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)\r
-        #view\r
-        self.Bind(wx.EVT_MENU_RANGE, self.OnView, id=ID_ViewAssistant, id2=ID_ViewResults)\r
-        #perspectives\r
-        self.Bind(wx.EVT_MENU, self.OnDeletePerspective, id=ID_DeletePerspective)\r
-        self.Bind(wx.EVT_MENU, self.OnSavePerspective, id=ID_SavePerspective)\r
-        self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, id2=ID_FirstPerspective+1000)\r
-        #toolbar\r
-        self.Bind(wx.EVT_TOOL, self.OnExportImage, id=ID_ExportImage)\r
-        self.Bind(wx.EVT_TOOL, self.OnNext, id=ID_Next)\r
-        self.Bind(wx.EVT_TOOL, self.OnPrevious, id=ID_Previous)\r
-        #self.Bind(.EVT_AUITOOLBAR_TOOL_DROPDOWN, self.OnDropDownToolbarItem, id=ID_DropDownToolbarItem)\r
-        #dir control\r
-        treeCtrl = self.panelFolders.GetTreeCtrl()\r
-        #tree.Bind(wx.EVT_LEFT_UP, self.OnDirCtrl1LeftUp)\r
-        #tree.Bind(wx.EVT_LEFT_DOWN, self.OnGenericDirCtrl1LeftDown)\r
-        treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self.OnDirCtrlLeftDclick)\r
-        #playlist tree\r
-        self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DOWN, self.OnPlaylistsLeftDown)\r
-        self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DCLICK, self.OnPlaylistsLeftDclick)\r
-        #commands tree\r
-        self.panelCommands.ExecuteButton.Bind(wx.EVT_BUTTON, self.OnExecute)\r
-        self.panelCommands.CommandsTree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeCtrlCommandsLeftDown)\r
-        #property editor\r
-        self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)\r
-        self.panelProperties.pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)\r
-        #results panel\r
-        self.panelResults.results_list.OnCheckItem = self.OnResultsCheck\r
-\r
-    def _GetActiveCurveIndex(self):\r
-        playlist = self.GetActivePlaylist()\r
-        #get the selected item from the tree\r
-        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-        #test if a playlist or a curve was double-clicked\r
-        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
-            return -1\r
-        else:\r
-            count = 0\r
-            selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
-            while selected_item.IsOk():\r
-                count += 1\r
-                selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
-            return count\r
-\r
-    def _GetActivePlaylistName(self):\r
-        #get the selected item from the tree\r
-        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-        #test if a playlist or a curve was double-clicked\r
-        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
-            playlist_item = selected_item\r
-        else:\r
-            #get the name of the playlist\r
-            playlist_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
-        #now we have a playlist\r
-        return self.panelPlaylists.PlaylistsTree.GetItemText(playlist_item)\r
-\r
-    def _GetPlaylistTab(self, name):\r
-        for index, page in enumerate(self.plotNotebook._tabs._pages):\r
-            if page.caption == name:\r
-                return index\r
-        return -1\r
-\r
-    def _GetUniquePlaylistName(self, name):\r
-        playlist_name = name\r
-        count = 1\r
-        while playlist_name in self.playlists:\r
-            playlist_name = ''.join([name, str(count)])\r
-            count += 1\r
-        return playlist_name\r
-\r
-    def _SavePerspectiveToFile(self, name, perspective):\r
-        filename = ''.join([name, '.txt'])\r
-        filename = lh.get_file_path(filename, ['perspectives'])\r
-        perspectivesFile = open(filename, 'w')\r
-        perspectivesFile.write(perspective)\r
-        perspectivesFile.close()\r
-\r
-    def AddPlaylist(self, playlist=None, name='Untitled'):\r
-        #TODO: change cursor or progressbar (maybe in statusbar)\r
-        #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
-        if playlist and playlist.count > 0:\r
-            playlist.name = self._GetUniquePlaylistName(name)\r
-            playlist.reset()\r
-            self.AddToPlaylists(playlist)\r
-\r
-    def AddPlaylistFromFiles(self, files=[], name='Untitled'):\r
-        #TODO: change cursor or progressbar (maybe in statusbar)\r
-        #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
-        if files:\r
-            playlist = Playlist.Playlist(self.drivers)\r
-            for item in files:\r
-                playlist.add_curve(item)\r
-        if playlist.count > 0:\r
-            playlist.name = self._GetUniquePlaylistName(name)\r
-            playlist.reset()\r
-            self.AddToPlaylists(playlist)\r
-\r
-    def AddToPlaylists(self, playlist):\r
-        if playlist.has_curves:\r
-            #setup the playlist in the Playlist tree\r
-            tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
-            playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)\r
-            #add all curves to the Playlist tree\r
-            curves = {}\r
-            for index, curve in enumerate(playlist.curves):\r
-                ##remove the extension from the name of the curve\r
-                ##TODO: optional?\r
-                #item_text, extension = os.path.splitext(curve.name)\r
-                #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)\r
-                curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)\r
-                if index == playlist.index:\r
-                    self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)\r
-            playlist.reset()\r
-            #create the plot tab and add playlist to the dictionary\r
-            plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))\r
-            notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)\r
-            tab_index = self.plotNotebook.GetSelection()\r
-            figure = plotPanel.get_figure()\r
-            self.playlists[playlist.name] = [playlist, figure]\r
-            self.panelPlaylists.PlaylistsTree.Expand(playlist_root)\r
-            self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-            self.UpdatePlot()\r
-\r
-    def AppendToOutput(self, text):\r
-        self.panelOutput.AppendText(''.join([text, '\n']))\r
-\r
-    def CreateApplicationIcon(self):\r
-        iconFile = 'resources' + os.sep + 'microscope.ico'\r
-        icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)\r
-        self.SetIcon(icon)\r
-\r
-    def CreateCommandLine(self):\r
-        return wx.TextCtrl(self, -1, '', style=wx.NO_BORDER|wx.EXPAND)\r
-\r
-    def CreatePanelAssistant(self):\r
-        panel = wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)\r
-        panel.SetEditable(False)\r
-        return panel\r
-\r
-    def CreatePanelCommands(self):\r
-        return hookecommands.Commands(self)\r
-\r
-    def CreatePanelFolders(self):\r
-        #set file filters\r
-        filters = self.config['folders']['filters']\r
-        index = self.config['folders'].as_int('filterindex')\r
-        #set initial directory\r
-        folder = self.config['general']['workdir']\r
-        return wx.GenericDirCtrl(self, -1, dir=folder, size=(200, 250), style=wx.DIRCTRL_SHOW_FILTERS, filter=filters, defaultFilter=index)\r
-\r
-    def CreatePanelOutput(self):\r
-        return wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)\r
-\r
-    def CreatePanelPlaylists(self):\r
-        return hookeplaylist.Playlists(self)\r
-\r
-    def CreatePanelProperties(self):\r
-        return hookepropertyeditor.PropertyEditor(self)\r
-\r
-    def CreatePanelResults(self):\r
-        return hookeresults.Results(self)\r
-\r
-    def CreatePanelWelcome(self):\r
-        ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))\r
-        introStr = '<h1>Welcome to Hooke</h1>' + \\r
-                 '<h3>Features</h3>' + \\r
-                 '<ul>' + \\r
-                 '<li>View, annotate, measure force curves</li>' + \\r
-                 '<li>Worm-like chain fit of force peaks</li>' + \\r
-                 '<li>Automatic convolution-based filtering of empty curves</li>' + \\r
-                 '<li>Automatic fit and measurement of multiple force peaks</li>' + \\r
-                 '<li>Handles force-clamp force experiments (experimental)</li>' + \\r
-                 '<li>It is extensible by users by means of plugins and drivers</li>' + \\r
-                 '</ul>' + \\r
-                 '<p>See the <a href="/p/hooke/wiki/DocumentationIndex">DocumentationIndex</a> for more information</p>'\r
-        ctrl.SetPage(introStr)\r
-        return ctrl\r
-\r
-    def CreateMenuBar(self):\r
-        menu_bar = wx.MenuBar()\r
-        #file\r
-        file_menu = wx.Menu()\r
-        file_menu.Append(wx.ID_OPEN, '&Open playlist\tCtrl-O')\r
-        file_menu.Append(wx.ID_SAVE, 'Save playlist\tCtrl-S')\r
-        file_menu.AppendSeparator()\r
-        file_menu.Append(wx.ID_EXIT, 'Exit\tCtrl-Q')\r
-        #edit\r
-        edit_menu = wx.Menu()\r
-        edit_menu.Append(ID_ExportText, 'Export text...')\r
-        edit_menu.Append(ID_ExportImage, 'Export image...')\r
-        edit_menu.AppendSeparator();\r
-        edit_menu.Append(ID_Config, 'Preferences')\r
-        #view\r
-        view_menu = wx.Menu()\r
-        view_menu.AppendCheckItem(ID_ViewFolders, 'Folders\tF5')\r
-        view_menu.AppendCheckItem(ID_ViewPlaylists, 'Playlists\tF6')\r
-        view_menu.AppendCheckItem(ID_ViewCommands, 'Commands\tF7')\r
-        view_menu.AppendCheckItem(ID_ViewProperties, 'Properties\tF8')\r
-        view_menu.AppendCheckItem(ID_ViewAssistant, 'Assistant\tF9')\r
-        view_menu.AppendCheckItem(ID_ViewResults, 'Results\tF10')\r
-        view_menu.AppendCheckItem(ID_ViewOutput, 'Output\tF11')\r
-        #perspectives\r
-        self._perspectives_menu = self.CreatePerspectivesMenu()\r
-        #help\r
-        help_menu = wx.Menu()\r
-        help_menu.Append(wx.ID_ABOUT, 'About Hooke')\r
-        #put it all together\r
-        menu_bar.Append(file_menu, 'File')\r
-        menu_bar.Append(edit_menu, 'Edit')\r
-        menu_bar.Append(view_menu, 'View')\r
-        menu_bar.Append(self._perspectives_menu, "Perspectives")\r
-        menu_bar.Append(help_menu, 'Help')\r
-\r
-        self.SetMenuBar(menu_bar)\r
-\r
-    def CreateNotebook(self):\r
-        # create the notebook off-window to avoid flicker\r
-        client_size = self.GetClientSize()\r
-        ctrl = aui.AuiNotebook(self, -1, wx.Point(client_size.x, client_size.y), wx.Size(430, 200), self._notebook_style)\r
-        arts = [aui.AuiDefaultTabArt, aui.AuiSimpleTabArt, aui.VC71TabArt, aui.FF2TabArt, aui.VC8TabArt, aui.ChromeTabArt]\r
-        art = arts[self._notebook_theme]()\r
-        ctrl.SetArtProvider(art)\r
-        #uncomment if we find a nice icon\r
-        #page_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))\r
-        ctrl.AddPage(self.CreatePanelWelcome(), "Welcome", False)\r
-        return ctrl\r
-\r
-    def CreatePerspectivesMenu(self):\r
-        menu = wx.Menu()\r
-        menu.Append(ID_SavePerspective, "Save Perspective")\r
-        menu.Append(ID_DeletePerspective, "Delete Perspective")\r
-        menu.AppendSeparator()\r
-        #add perspectives to menubar and _perspectives\r
-        perspectivesDirectory = os.path.join(lh.hookeDir, 'perspectives')\r
-        if os.path.isdir(perspectivesDirectory):\r
-            perspectiveFileNames = os.listdir(perspectivesDirectory)\r
-            for perspectiveFilename in perspectiveFileNames:\r
-                filename = lh.get_file_path(perspectiveFilename, ['perspectives'])\r
-                if os.path.isfile(filename):\r
-                    perspectiveFile = open(filename, 'rU')\r
-                    perspective = perspectiveFile.readline()\r
-                    perspectiveFile.close()\r
-                    if perspective != '':\r
-                        name, extension = os.path.splitext(perspectiveFilename)\r
-                        if extension == '.txt':\r
-                            menuItem = menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)\r
-                            self._perspectives[name] = [len(self._perspectives), perspective]\r
-                            if self.config['perspectives']['active'] == name:\r
-                                menuItem.Check()\r
-        #in case there are no perspectives\r
-        if not self._perspectives:\r
-            perspective = self._mgr.SavePerspective()\r
-            self.config['perspectives']['default'] = 'Default'\r
-            self._perspectives['Default'] = [0, perspective]\r
-            menuItem = menu.AppendRadioItem(ID_FirstPerspective, 'Default')\r
-            menuItem.Check()\r
-            self._SavePerspectiveToFile('Default', perspective)\r
-        return menu\r
-\r
-    def CreateStatusbar(self):\r
-        statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)\r
-        statusbar.SetStatusWidths([-2, -3])\r
-        statusbar.SetStatusText('Ready', 0)\r
-        welcomeString=u'Welcome to Hooke (version '+__version__+', '+__release_name__+')!'\r
-        statusbar.SetStatusText(welcomeString, 1)\r
-        return statusbar\r
-\r
-    def CreateToolBar(self):\r
-        toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)\r
-        toolbar.SetToolBitmapSize(wx.Size(16,16))\r
-        toolbar_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar_bmpOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar_bmpSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar_bmpExportText = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar_bmpExportImage = wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar.AddLabelTool(101, 'Open', toolbar_bmpOpen)\r
-        toolbar.AddLabelTool(102, 'Save', toolbar_bmpSave)\r
-        toolbar.AddSeparator()\r
-        toolbar.AddLabelTool(ID_ExportText, 'Export text...', toolbar_bmpExportText)\r
-        toolbar.AddLabelTool(ID_ExportImage, 'Export image...', toolbar_bmpExportImage)\r
-        toolbar.Realize()\r
-        return toolbar\r
-\r
-    def CreateToolBarNavigation(self):\r
-        toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)\r
-        toolbar.SetToolBitmapSize(wx.Size(16,16))\r
-        toolbar_bmpBack = wx.ArtProvider_GetBitmap(wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar_bmpForward = wx.ArtProvider_GetBitmap(wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16))\r
-        toolbar.AddLabelTool(ID_Previous, 'Previous', toolbar_bmpBack, shortHelp='Previous curve')\r
-        toolbar.AddLabelTool(ID_Next, 'Next', toolbar_bmpForward, shortHelp='Next curve')\r
-        toolbar.Realize()\r
-        return toolbar\r
-\r
-    def DeleteFromPlaylists(self, name):\r
-        if name in self.playlists:\r
-            del self.playlists[name]\r
-        tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
-        item, cookie = self.panelPlaylists.PlaylistsTree.GetFirstChild(tree_root)\r
-        while item.IsOk():\r
-            playlist_name = self.panelPlaylists.PlaylistsTree.GetItemText(item)\r
-            if playlist_name == name:\r
-                try:\r
-                    self.panelPlaylists.PlaylistsTree.Delete(item)\r
-                except:\r
-                    pass\r
-            item = self.panelPlaylists.PlaylistsTree.GetNextSibling(item)\r
-        self.OnPlaylistsLeftDclick(None)\r
-\r
-    def DeletePlotPage(self, name):\r
-        index = self._GetPlaylistTab(name)\r
-        plot = self.playlists[name][1]\r
-        plot = None\r
-        self.plotNotebook.RemovePage(index)\r
-        self.DeleteFromPlaylists(name)\r
-\r
-    def GetActiveCurve(self):\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist is not None:\r
-            return playlist.get_active_curve()\r
-        return None\r
-\r
-    def GetActivePlaylist(self):\r
-        playlist_name = self._GetActivePlaylistName()\r
-        if playlist_name in self.playlists:\r
-            return self.playlists[playlist_name][0]\r
-        return None\r
-\r
-    def GetActivePlot(self):\r
-        curve = self.GetActiveCurve()\r
-        if curve is not None:\r
-            return curve.plots[0]\r
-        return None\r
-\r
-    def GetDockArt(self):\r
-        return self._mgr.GetArtProvider()\r
-\r
-    def GetBoolFromConfig(self, *args):\r
-        if len(args) == 2:\r
-            plugin = args[0]\r
-            section = args[0]\r
-            key = args[1]\r
-        elif len(args) == 3:\r
-            plugin = args[0]\r
-            section = args[1]\r
-            key = args[2]\r
-        if self.configs.has_key(plugin):\r
-            config = self.configs[plugin]\r
-            return config[section][key].as_bool('value')\r
-        return None\r
-\r
-    def GetFloatFromConfig(self, *args):\r
-        if len(args) == 2:\r
-            plugin = args[0]\r
-            section = args[0]\r
-            key = args[1]\r
-        elif len(args) == 3:\r
-            plugin = args[0]\r
-            section = args[1]\r
-            key = args[2]\r
-        if self.configs.has_key(plugin):\r
-            config = self.configs[plugin]\r
-            return config[section][key].as_float('value')\r
-        return None\r
-\r
-    def GetIntFromConfig(self, *args):\r
-        if len(args) == 2:\r
-            plugin = args[0]\r
-            section = args[0]\r
-            key = args[1]\r
-        elif len(args) == 3:\r
-            plugin = args[0]\r
-            section = args[1]\r
-            key = args[2]\r
-        if self.configs.has_key(plugin):\r
-            config = self.configs[plugin]\r
-            return config[section][key].as_int('value')\r
-        return None\r
-\r
-    def GetStringFromConfig(self, *args):\r
-        if len(args) == 2:\r
-            plugin = args[0]\r
-            section = args[0]\r
-            key = args[1]\r
-        elif len(args) == 3:\r
-            plugin = args[0]\r
-            section = args[1]\r
-            key = args[2]\r
-        if self.configs.has_key(plugin):\r
-            config = self.configs[plugin]\r
-            return config[section][key]['value']\r
-        return None\r
-\r
-    def GetPerspectiveMenuItem(self, name):\r
-        index = self._perspectives[name][0]\r
-        perspective_Id = ID_FirstPerspective + index\r
-        menu_item = self.MenuBar.FindItemById(perspective_Id)\r
-        return menu_item\r
-\r
-    def HasPlotmanipulator(self, name):\r
-        '''\r
-        returns True if the plotmanipulator 'name' is loaded, False otherwise\r
-        '''\r
-        for plotmanipulator in self.plotmanipulators:\r
-            if plotmanipulator[0] == name:\r
-                return True\r
-        return False\r
-\r
-    def OnAbout(self, event):\r
-        msg = 'Hooke\n\n'+\\r
-            'A free, open source data analysis platform\n'+\\r
-            '(c) 2006-2008 Massimo Sandal\n\n'+\\r
-            '(c) 2009 Dr. Rolf Schmidt\n\n'+\\r
-            'Released under the GNU GPL v2'\r
-        dialog = wx.MessageDialog(self, msg, "About Hooke", wx.OK | wx.ICON_INFORMATION)\r
-        dialog.ShowModal()\r
-        dialog.Destroy()\r
-\r
-    def OnClose(self, event):\r
-        #apply changes\r
-        self.config['main']['height'] = str(self.GetSize().GetHeight())\r
-        self.config['main']['left'] = str(self.GetPosition()[0])\r
-        self.config['main']['top'] = str(self.GetPosition()[1])\r
-        self.config['main']['width'] = str(self.GetSize().GetWidth())\r
-        # Writing the configuration file to 'hooke.ini'\r
-        self.config.write()\r
-        self._mgr.UnInit()\r
-        del self._mgr\r
-        self.Destroy()\r
-\r
-    def OnDeletePerspective(self, event):\r
-        pass\r
-\r
-    def OnDirCtrlLeftDclick(self, event):\r
-        file_path = self.panelFolders.GetPath()\r
-        if os.path.isfile(file_path):\r
-            if file_path.endswith('.hkp'):\r
-                self.do_loadlist(file_path)\r
-            else:\r
-                pass\r
-        event.Skip()\r
-\r
-    def OnEraseBackground(self, event):\r
-        event.Skip()\r
-\r
-    def OnExecute(self, event):\r
-        item = self.panelCommands.CommandsTree.GetSelection()\r
-        if item.IsOk():\r
-            if self.panelCommands.CommandsTree.ItemHasChildren(item):\r
-                pass\r
-            else:\r
-                #get the plugin\r
-                parent = self.panelCommands.CommandsTree.GetItemParent(item)\r
-            if not self.panelCommands.CommandsTree.ItemHasChildren(item):\r
-                parent_text = self.panelCommands.CommandsTree.GetItemText(parent)\r
-                item_text = self.panelCommands.CommandsTree.GetItemText(item)\r
-                if item_text in ['genlist', 'loadlist', 'savelist']:\r
-                    property_values = self.panelProperties.GetPropertyValues()\r
-                    arg_str = ''\r
-                    for item in property_values:\r
-                        arg_str = ''.join([arg_str, item, '=r"', str(property_values[item]), '", '])\r
-                    command = ''.join(['self.do_', item_text, '(', arg_str, ')'])\r
-                else:\r
-                    command = ''.join(['self.do_', item_text, '()'])\r
-                exec(command)\r
-        pass\r
-\r
-    def OnExit(self, event):\r
-        self.Close()\r
-\r
-    def OnExportImage(self, event):\r
-        pass\r
-\r
-    def OnNext(self, event):\r
-        '''\r
-        NEXT\r
-        Go to the next curve in the playlist.\r
-        If we are at the last curve, we come back to the first.\r
-        -----\r
-        Syntax: next, n\r
-        '''\r
-        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
-            #GetFirstChild returns a tuple\r
-            #we only need the first element\r
-            next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(selected_item)[0]\r
-        else:\r
-            next_item = self.panelPlaylists.PlaylistsTree.GetNextSibling(selected_item)\r
-            if not next_item.IsOk():\r
-                parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
-                #GetFirstChild returns a tuple\r
-                #we only need the first element\r
-                next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(parent_item)[0]\r
-        self.panelPlaylists.PlaylistsTree.SelectItem(next_item, True)\r
-        playlist = self.playlists[self._GetActivePlaylistName()][0]\r
-        if playlist.count > 1:\r
-            playlist.next()\r
-            self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-            self.UpdatePlot()\r
-\r
-    def OnNotebookPageClose(self, event):\r
-        ctrl = event.GetEventObject()\r
-        playlist_name = ctrl.GetPageText(ctrl._curpage)\r
-        self.DeleteFromPlaylists(playlist_name)\r
-\r
-    def OnPaneClose(self, event):\r
-        event.Skip()\r
-\r
-    def OnPlaylistsLeftDclick(self, event):\r
-        playlist_name = self._GetActivePlaylistName()\r
-        #if that playlist already exists\r
-        #we check if it is the active playlist (ie selected in panelPlaylists)\r
-        #and switch to it if necessary\r
-        if playlist_name in self.playlists:\r
-            index = self.plotNotebook.GetSelection()\r
-            current_playlist = self.plotNotebook.GetPageText(index)\r
-            #new_playlist = self.playlists[playlist_name][0]\r
-            #if current_playlist != new_playlist:\r
-            if current_playlist != playlist_name:\r
-                index = self._GetPlaylistTab(playlist_name)\r
-                self.plotNotebook.SetSelection(index)\r
-            #if a curve was double-clicked\r
-            item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-            #TODO: fix with get_active_curve\r
-            if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):\r
-                index = self._GetActiveCurveIndex()\r
-            else:\r
-                index = 0\r
-            if index >= 0:\r
-                playlist = self.playlists[playlist_name][0]\r
-                playlist.index = index\r
-                self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-                self.UpdatePlot()\r
-        #if you uncomment the following line, the tree will collapse/expand as well\r
-        #event.Skip()\r
-\r
-    def OnPlaylistsLeftDown(self, event):\r
-        hit_item, hit_flags = self.panelPlaylists.PlaylistsTree.HitTest(event.GetPosition())\r
-        if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:\r
-            #self.SetFocus()\r
-            self.panelPlaylists.PlaylistsTree.SelectItem(hit_item)\r
-            playlist_name = self._GetActivePlaylistName()\r
-            playlist = self.playlists[playlist_name][0]\r
-            #if a curve was clicked\r
-            item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-            if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):\r
-                #TODO: fix with get_active_curve\r
-                index = self._GetActiveCurveIndex()\r
-                if index >= 0:\r
-                    #playlist = self.playlists[playlist_name][0]\r
-                    playlist.index = index\r
-                    #self.playlists[playlist_name][0].index = index\r
-            #else:\r
-                ##self.playlists[playlist_name][0].index = 0\r
-                #playlist.index = index\r
-            self.playlists[playlist_name][0] = playlist\r
-        event.Skip()\r
-\r
-    def OnPrevious(self, event):\r
-        '''\r
-        PREVIOUS\r
-        Go to the previous curve in the playlist.\r
-        If we are at the first curve, we jump to the last.\r
-        -------\r
-        Syntax: previous, p\r
-        '''\r
-        #playlist = self.playlists[self._GetActivePlaylistName()][0]\r
-        #select the previous curve and tell the user if we wrapped around\r
-        #self.AppendToOutput(playlist.previous())\r
-        selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()\r
-        if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):\r
-            previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(selected_item)\r
-        else:\r
-            previous_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)\r
-            if not previous_item.IsOk():\r
-                parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)\r
-                previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(parent_item)\r
-        self.panelPlaylists.PlaylistsTree.SelectItem(previous_item, True)\r
-        playlist = self.playlists[self._GetActivePlaylistName()][0]\r
-        if playlist.count > 1:\r
-            playlist.previous()\r
-            self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-            self.UpdatePlot()\r
-\r
-    def OnPropGridChanged (self, event):\r
-        prop = event.GetProperty()\r
-        if prop:\r
-            item_section = self.panelProperties.SelectedTreeItem\r
-            item_plugin = self.panelCommands.CommandsTree.GetItemParent(item_section)\r
-            plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)\r
-            config = self.configs[plugin]\r
-            property_section = self.panelCommands.CommandsTree.GetItemText(item_section)\r
-            property_key = prop.GetName()\r
-            property_value = prop.GetValue()\r
-            config[property_section][property_key]['value'] = property_value\r
-\r
-    def OnPropGridSelect(self, event):\r
-        pass\r
-\r
-    def OnRestorePerspective(self, event):\r
-        name = self.MenuBar.FindItemById(event.GetId()).GetLabel()\r
-        self._mgr.LoadPerspective(self._perspectives[name][1])\r
-        self.config['perspectives']['active'] = name\r
-        self._mgr.Update()\r
-        all_panes = self._mgr.GetAllPanes()\r
-        for pane in all_panes:\r
-            if not pane.name.startswith('toolbar'):\r
-                if pane.name == 'Assistant':\r
-                    self.MenuBar.FindItemById(ID_ViewAssistant).Check(pane.window.IsShown())\r
-                if pane.name == 'Folders':\r
-                    self.MenuBar.FindItemById(ID_ViewFolders).Check(pane.window.IsShown())\r
-                if pane.name == 'Playlists':\r
-                    self.MenuBar.FindItemById(ID_ViewPlaylists).Check(pane.window.IsShown())\r
-                if pane.name == 'Commands':\r
-                    self.MenuBar.FindItemById(ID_ViewCommands).Check(pane.window.IsShown())\r
-                if pane.name == 'Properties':\r
-                    self.MenuBar.FindItemById(ID_ViewProperties).Check(pane.window.IsShown())\r
-                if pane.name == 'Output':\r
-                    self.MenuBar.FindItemById(ID_ViewOutput).Check(pane.window.IsShown())\r
-                if pane.name == 'Results':\r
-                    self.MenuBar.FindItemById(ID_ViewResults).Check(pane.window.IsShown())\r
-\r
-    def OnResultsCheck(self, index, flag):\r
-        curve = self.GetActiveCurve()\r
-        result = curve.data['results'][index]['visible'] = flag\r
-        self.UpdatePlot()\r
-\r
-    def OnSavePerspective(self, event):\r
-        def nameExists(name):\r
-            for item in self._perspectives_menu.GetMenuItems():\r
-                if item.GetText() == name:\r
-                    return True\r
-            return False\r
-\r
-        done = False\r
-        while not done:\r
-            dialog = wx.TextEntryDialog(self, 'Enter a name for the new perspective:', 'Save perspective')\r
-            dialog.SetValue('New perspective')\r
-            if dialog.ShowModal() != wx.ID_OK:\r
-                return\r
-            else:\r
-                name = dialog.GetValue()\r
-\r
-            if nameExists(name):\r
-                dialogConfirm = wx.MessageDialog(self, 'A file with this name already exists.\n\nDo you want to replace it?', 'Confirm', wx.YES_NO|wx.ICON_QUESTION|wx.CENTER)\r
-                if dialogConfirm.ShowModal() == wx.ID_YES:\r
-                    done = True\r
-            else:\r
-                done = True\r
-\r
-        perspective = self._mgr.SavePerspective()\r
-\r
-        if nameExists(name):\r
-            #check the corresponding menu item\r
-            menuItem = self.GetPerspectiveMenuItem(name)\r
-            #replace the perspectiveStr in _pespectives\r
-            index = self._perspectives[name][0]\r
-            self._perspectives[name] = [index, perspective]\r
-        else:\r
-            #simply add the new perspective to _perspectives\r
-            index = len(self._perspectives)\r
-            self._perspectives[name] = [len(self._perspectives), perspective]\r
-            menuItem = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)\r
-\r
-        menuItem.Check()\r
-        self._SavePerspectiveToFile(name, perspective)\r
-        #uncheck all perspective menu items\r
-        #as these are radio items, one item has to be checked at all times\r
-        #the line 'menuItem.Check()' above actually checks a second item\r
-        #but does not toggle\r
-        #so we need to uncheck all other items afterwards\r
-        #weirdly enough, menuitem.Toggle() doesn't do this properly either\r
-        for item in self._perspectives_menu.GetMenuItems():\r
-            if item.IsCheckable():\r
-                if item.GetLabel() != name:\r
-                    item.Check(False)\r
-\r
-    def OnView(self, event):\r
-        menu_id = event.GetId()\r
-        menu_item = self.MenuBar.FindItemById(menu_id)\r
-        menu_label = menu_item.GetLabel()\r
-\r
-        pane = self._mgr.GetPane(menu_label)\r
-        pane.Show(not pane.IsShown())\r
-        #if we don't do the following, the Folders pane does not resize properly on hide/show\r
-        if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():\r
-            #folders_size = pane.GetSize()\r
-            self.panelFolders.Fit()\r
-        self._mgr.Update()\r
-\r
-    def OnSize(self, event):\r
-        event.Skip()\r
-\r
-    def OnTreeCtrlCommandsLeftDown(self, event):\r
-        hit_item, hit_flags = self.panelCommands.CommandsTree.HitTest(event.GetPosition())\r
-        if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:\r
-            self.panelCommands.CommandsTree.SelectItem(hit_item)\r
-            self.panelProperties.SelectedTreeItem = hit_item\r
-            #if a command was clicked\r
-            properties = []\r
-            if not self.panelCommands.CommandsTree.ItemHasChildren(hit_item):\r
-                item_plugin = self.panelCommands.CommandsTree.GetItemParent(hit_item)\r
-                plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)\r
-                if self.configs.has_key(plugin):\r
-                    #config = self.panelCommands.CommandsTree.GetPyData(item_plugin)\r
-                    config = self.configs[plugin]\r
-                    section = self.panelCommands.CommandsTree.GetItemText(hit_item)\r
-                    #display docstring in help window\r
-                    doc_string = eval('self.do_' + section + '.__doc__')\r
-                    if section in config:\r
-                        for option in config[section]:\r
-                            properties.append([option, config[section][option]])\r
-            else:\r
-                module = self.panelCommands.CommandsTree.GetItemText(hit_item)\r
-                if module != 'general':\r
-                    doc_string = eval('plugins.' + module + '.' + module + 'Commands.__doc__')\r
-                else:\r
-                    doc_string = 'The module "general" contains Hooke core functionality'\r
-            if doc_string is not None:\r
-                self.panelAssistant.ChangeValue(doc_string)\r
-            hookepropertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)\r
-        event.Skip()\r
-\r
-    def UpdatePlaylists(self):\r
-        #setup the playlist in the Playlist tree\r
-        tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()\r
-        playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)\r
-        #add all curves to the Playlist tree\r
-        curves = {}\r
-        for index, curve in enumerate(playlist.curves):\r
-            ##remove the extension from the name of the curve\r
-            ##TODO: optional?\r
-            #item_text, extension = os.path.splitext(curve.name)\r
-            #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)\r
-            curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)\r
-            if index == playlist.index:\r
-                self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)\r
-        #create the plot tab and add playlist to the dictionary\r
-        plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))\r
-        notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)\r
-        #tab_index = self.plotNotebook.GetSelection()\r
-        figure = plotPanel.get_figure()\r
-        #self.playlists[playlist.name] = [playlist, tab_index, figure]\r
-        self.playlists[playlist.name] = [playlist, figure]\r
-        self.panelPlaylists.PlaylistsTree.Expand(playlist_root)\r
-        self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-        self.UpdatePlot()\r
-\r
-#HELPER FUNCTIONS\r
-#Everything sending an event should be here\r
-    def _measure_N_points(self, N, whatset=1):\r
-        '''\r
-        general helper function for N-points measures\r
-        '''\r
-        wx.PostEvent(self.frame,self.list_of_events['measure_points'](num_of_points=N, set=whatset))\r
-        while 1:\r
-            try:\r
-                points=self.frame.events_from_gui.get()\r
-                break\r
-            except Empty:\r
-                pass\r
-        return points\r
-\r
-    def _clickize(self, xvector, yvector, index):\r
-        '''\r
-        returns a ClickedPoint() object from an index and vectors of x, y coordinates\r
-        '''\r
-        point = lh.ClickedPoint()\r
-        point.index = index\r
-        point.absolute_coords = xvector[index], yvector[index]\r
-        point.find_graph_coords(xvector, yvector)\r
-        return point\r
-\r
-#PLAYLIST INTERACTION COMMANDS\r
-#-------------------------------\r
-    def do_genlist(self, folder=lh.hookeDir, filemask='*.*'):\r
-        '''\r
-        GENLIST\r
-        Generates a file playlist.\r
-        Note it doesn't *save* it: see savelist for this.\r
-\r
-        If [input files] is a directory, it will use all files in the directory for playlist.\r
-        So:\r
-        genlist dir\r
-        genlist dir/\r
-        genlist dir/*.*\r
-\r
-        are all equivalent syntax.\r
-        ------------\r
-        Syntax: genlist [input files]\r
-        '''\r
-        #args list is: input folder, file mask\r
-        if os.path.isdir(folder):\r
-            path = os.path.join(folder, filemask)\r
-            #expanding correctly the input list with the glob module :)\r
-            files = glob.glob(path)\r
-            files.sort()\r
-            #TODO: change cursor or progressbar (maybe in statusbar)\r
-            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
-            playlist = playlist.Playlist(self.drivers)\r
-            for item in files:\r
-                curve = playlist.add_curve(item)\r
-                plot = copy.deepcopy(curve.plots[0])\r
-                #add the 'raw' data\r
-                curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
-                curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
-                #apply all active plotmanipulators and add the 'manipulated' data\r
-                for plotmanipulator in self.plotmanipulators:\r
-                    plot = plotmanipulator[1](plot, curve)\r
-                    curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
-                    curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
-            if playlist.count > 0:\r
-                playlist.name = self._GetUniquePlaylistName(os.path.basename(folder))\r
-                playlist.reset()\r
-                self.AddToPlaylists(playlist)\r
-            self.AppendToOutput(playlist.get_status_string())\r
-        else:\r
-            self.AppendToOutput(''.join(['Cannot find folder ', folder]))\r
-\r
-    def do_loadlist(self, filename):\r
-        '''\r
-        LOADLIST\r
-        Loads a file playlist\r
-        -----------\r
-        Syntax: loadlist [playlist file]\r
-        '''\r
-        #TODO: check for duplicate playlists, ask the user for a unique name\r
-        #if self.playlist_name in self.playlists:\r
-\r
-        #add hkp extension if necessary\r
-        if not filename.endswith('.hkp'):\r
-            filename = ''.join([filename, '.hkp'])\r
-        #prefix with 'hookeDir' if just a filename or a relative path\r
-        filename = lh.get_file_path(filename)\r
-        if os.path.isfile(filename):\r
-            #TODO: change cursor\r
-            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
-            playlist_new = playlist.Playlist(self.drivers)\r
-            playlist_new.load(filename)\r
-            if playlist_new.count > 0:\r
-                for curve in playlist_new.curves:\r
-                    plot = copy.deepcopy(curve.plots[0])\r
-                    for plotmanip in self.plotmanipulators:\r
-                        #to_plot = plotmanip[1](to_plot, curve)\r
-                        plot = plotmanip[1](plot, curve)\r
-                        curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')\r
-                        curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')\r
-                self.AddToPlaylists(playlist_new)\r
-            #else:\r
-                ##TODO: display dialog\r
-            self.AppendToOutput(playlist_new.get_status_string())\r
-            #TODO: change cursor\r
-            #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))\r
-        else:\r
-            #TODO: display dialog\r
-            self.AppendToOutput(''.join['File ', filename, ' not found.\n'])\r
-        pass\r
-\r
-    def do_savelist(self, filename):\r
-        '''\r
-        SAVELIST\r
-        Saves the current file playlist on disk.\r
-        ------------\r
-        Syntax: savelist [filename]\r
-        '''\r
-\r
-        #self.playlist_generics['pointer'] = self._GetActiveCurveIndex\r
-        pointer = self._GetActiveCurveIndex()\r
-        #autocomplete filename if not specified\r
-        if not filename.endswith('.hkp'):\r
-            filename = filename.join(['.hkp'])\r
-\r
-        playlist = self.GetActivePlaylist()\r
-        playlist.set_XML()\r
-        playlist.save(filename)\r
-\r
-#PLOT INTERACTION COMMANDS\r
-#-------------------------------\r
-    def UpdatePlot(self):\r
-        def add_plot(plot):\r
-            if plot['visible'] and plot['x'] and plot['y']:\r
-                color = plot['color']\r
-                style = plot['style']\r
-                if style == 'plot':\r
-                    axes.plot(plot['x'], plot['y'], color=color, zorder=1)\r
-                if style == 'scatter':\r
-                    axes.scatter(plot['x'], plot['y'], color=color, s=0.5, zorder=2)\r
-\r
-        def add_plot2(plot):\r
-            if plot.visible and plot.x and plot.y:\r
-                if plot.style == 'plot':\r
-                    axes.plot(plot.x, plot.y, color=plot.color, zorder=1)\r
-                if plot.style == 'scatter':\r
-                    axes.scatter(plot.x, plot.y, color=plot.color, s=0.5, zorder=2)\r
-\r
-        playlist_name = self._GetActivePlaylistName()\r
-        index = self._GetActiveCurveIndex()\r
-        playlist = self.playlists[playlist_name][0]\r
-        curve = playlist.get_active_curve()\r
-        plot = playlist.get_active_plot()\r
-        figure = self.playlists[playlist_name][1]\r
-\r
-        figure.clf()\r
-        exclude = None\r
-        if curve.data.has_key('manipulated'):\r
-            exclude = 'raw'\r
-        elif curve.data.has_key('raw'):\r
-            exclude = 'manipulated'\r
-\r
-        if exclude is not None:\r
-            #TODO: what is this good for?\r
-            if not hasattr(self, 'subplot'):\r
-                axes = figure.add_subplot(111)\r
-\r
-            axes.set_title(plot.title)\r
-            axes.set_xlabel(plot.units[0])\r
-            axes.set_ylabel(plot.units[1])\r
-\r
-            for set_of_plots in curve.data:\r
-                if set_of_plots != exclude:\r
-                    plots = curve.data[set_of_plots]\r
-                    for each_plot in plots:\r
-                        add_plot(each_plot)\r
-\r
-            #TODO: add multiple results support\r
-            #for fit in curve.fits:\r
-            if curve.fits.has_key('wlc'):\r
-                for plot in curve.fits['wlc'].results:\r
-                    add_plot2(plot)\r
-                self.panelResults.DisplayResults(curve.fits['wlc'])\r
-            else:\r
-                self.panelResults.ClearResults()\r
-\r
-            axes.figure.canvas.draw()\r
-        else:\r
-            self.AppendToOutput('Not able to plot.')\r
-\r
-\r
-ID_PaneBorderSize = wx.ID_HIGHEST + 1\r
-ID_SashSize = ID_PaneBorderSize + 1\r
-ID_CaptionSize = ID_PaneBorderSize + 2\r
-ID_BackgroundColor = ID_PaneBorderSize + 3\r
-ID_SashColor = ID_PaneBorderSize + 4\r
-ID_InactiveCaptionColor =  ID_PaneBorderSize + 5\r
-ID_InactiveCaptionGradientColor = ID_PaneBorderSize + 6\r
-ID_InactiveCaptionTextColor = ID_PaneBorderSize + 7\r
-ID_ActiveCaptionColor = ID_PaneBorderSize + 8\r
-ID_ActiveCaptionGradientColor = ID_PaneBorderSize + 9\r
-ID_ActiveCaptionTextColor = ID_PaneBorderSize + 10\r
-ID_BorderColor = ID_PaneBorderSize + 11\r
-ID_GripperColor = ID_PaneBorderSize + 12\r
-\r
-\r
-#----------------------------------------------------------------------\r
-\r
-if __name__ == '__main__':\r
-\r
-    ## now, silence a deprecation warning for py2.3\r
-    #import warnings\r
-    #warnings.filterwarnings("ignore", "integer", DeprecationWarning, "wxPython.gdi")\r
-\r
-    redirect=True\r
-    if __debug__:\r
-        redirect=False\r
-    app = Hooke(redirect=redirect)\r
-\r
-    app.MainLoop()\r
-\r
-\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)
+
+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
+from .compat import forking as forking  # dynamically patch multiprocessing.forking
+
+
+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.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')
+
+    def load_ui(self):
+        self.ui = ui.load_ui(self.config)
+
+    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)