Collapse None entries for Argument.count == -1 in the GUI
[hooke.git] / hooke / ui / gui / __init__.py
index 720c364befaee1ef2c5d464cebe3b77f4ef138af..1c646f4396cc82429da7eb82cc55a601902b18f8 100644 (file)
-# Copyright\r
-\r
-"""Defines :class:`GUI` providing a wxWindows interface to Hooke.\r
-"""\r
-\r
-WX_GOOD=['2.8']\r
-\r
-import wxversion\r
-wxversion.select(WX_GOOD)\r
-\r
-import copy\r
-import os.path\r
-import platform\r
-import shutil\r
-import time\r
-\r
-import wx.html\r
-import wx.aui as aui\r
-import wx.lib.evtmgr as evtmgr\r
-\r
-\r
-# wxPropertyGrid included in wxPython >= 2.9.1, until then, see\r
-#   http://wxpropgrid.sourceforge.net/cgi-bin/index?page=download\r
-# until then, we'll avoid it because of the *nix build problems.\r
-#import wx.propgrid as wxpg\r
-\r
-from matplotlib.ticker import FuncFormatter\r
-\r
-from ... import version\r
-from ...command import CommandExit, Exit, Command, Argument, StoreValue\r
-from ...config import Setting\r
-from ...interaction import Request, BooleanRequest, ReloadUserInterfaceConfig\r
-from ...ui import UserInterface, CommandMessage\r
-from . import panel as panel\r
-from . import prettyformat as prettyformat\r
-\r
-\r
-class Notebook (aui.AuiNotebook):\r
-    def __init__(self, *args, **kwargs):\r
-        super(Notebook, self).__init__(*args, **kwargs)\r
-        self.SetArtProvider(aui.AuiDefaultTabArt())\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
-        self.AddPage(self._welcome_window(), 'Welcome')\r
-\r
-    def _welcome_window(self):\r
-        #TODO: move into panel.welcome\r
-        ctrl = wx.html.HtmlWindow(parent=self, size=wx.Size(400, 300))\r
-        lines = [\r
-            '<h1>Welcome to Hooke</h1>',\r
-            '<h3>Features</h3>',\r
-            '<ul>',\r
-            '<li>View, annotate, measure force files</li>',\r
-            '<li>Worm-like chain fit of force peaks</li>',\r
-            '<li>Automatic convolution-based filtering of empty files</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 through plugins and drivers</li>',\r
-            '</ul>',\r
-            '<p>See the <a href="%s">DocumentationIndex</a>'\r
-            % 'http://code.google.com/p/hooke/wiki/DocumentationIndex',\r
-            'for more information</p>',\r
-            ]\r
-        ctrl.SetPage('\n'.join(lines))\r
-        return ctrl\r
-\r
-\r
-class NavBar (wx.ToolBar):\r
-    def __init__(self, *args, **kwargs):\r
-        super(NavBar, self).__init__(*args, **kwargs)\r
-        self.SetToolBitmapSize(wx.Size(16,16))\r
-        self._c = {\r
-            'previous': self.AddLabelTool(\r
-                id=wx.ID_PREVIEW_PREVIOUS,\r
-                label='Previous',\r
-                bitmap=wx.ArtProvider_GetBitmap(\r
-                    wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16)),\r
-                shortHelp='Previous curve'),\r
-            'next': self.AddLabelTool(\r
-                id=wx.ID_PREVIEW_NEXT,\r
-                label='Next',\r
-                bitmap=wx.ArtProvider_GetBitmap(\r
-                    wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16)),\r
-                shortHelp='Next curve'),\r
-            }\r
-        self.Realize()\r
-\r
-\r
-class FileMenu (wx.Menu):\r
-    def __init__(self, *args, **kwargs):\r
-        super(FileMenu, self).__init__(*args, **kwargs)\r
-        self._c = {'exit': self.Append(wx.ID_EXIT)}\r
-\r
-\r
-class ViewMenu (wx.Menu):\r
-    def __init__(self, *args, **kwargs):\r
-        super(ViewMenu, self).__init__(*args, **kwargs)\r
-        self._c = {\r
-            'folders': self.AppendCheckItem(id=wx.ID_ANY, text='Folders\tF5'),\r
-            'playlist': self.AppendCheckItem(\r
-                id=wx.ID_ANY, text='Playlists\tF6'),\r
-            'commands': self.AppendCheckItem(\r
-                id=wx.ID_ANY, text='Commands\tF7'),\r
-            'assistant': self.AppendCheckItem(\r
-                id=wx.ID_ANY, text='Assistant\tF9'),\r
-            'properties': self.AppendCheckItem(\r
-                id=wx.ID_ANY, text='Properties\tF8'),\r
-            'results': self.AppendCheckItem(id=wx.ID_ANY, text='Results\tF10'),\r
-            'output': self.AppendCheckItem(id=wx.ID_ANY, text='Output\tF11'),\r
-            'note': self.AppendCheckItem(id=wx.ID_ANY, text='Note\tF12'),\r
-            }\r
-        for item in self._c.values():\r
-            item.Check()\r
-\r
-\r
-class PerspectiveMenu (wx.Menu):\r
-    def __init__(self, *args, **kwargs):\r
-        super(PerspectiveMenu, self).__init__(*args, **kwargs)\r
-        self._c = {}\r
-\r
-    def update(self, perspectives, selected, callback):\r
-        """Rebuild the perspectives menu.\r
-        """\r
-        for item in self.GetMenuItems():\r
-            self.UnBind(item)\r
-            self.DeleteItem(item)\r
-        self._c = {\r
-            'save': self.Append(id=wx.ID_ANY, text='Save Perspective'),\r
-            'delete': self.Append(id=wx.ID_ANY, text='Delete Perspective'),\r
-            }\r
-        self.AppendSeparator()\r
-        for label in perspectives:\r
-            self._c[label] = self.AppendRadioItem(id=wx.ID_ANY, text=label)\r
-            self.Bind(wx.EVT_MENU, callback, self._c[label])\r
-            if label == selected:\r
-                self._c[label].Check(True)\r
-            \r
-\r
-class HelpMenu (wx.Menu):\r
-    def __init__(self, *args, **kwargs):\r
-        super(HelpMenu, self).__init__(*args, **kwargs)\r
-        self._c = {'about':self.Append(id=wx.ID_ABOUT)}\r
-\r
-\r
-class MenuBar (wx.MenuBar):\r
-    def __init__(self, *args, **kwargs):\r
-        super(MenuBar, self).__init__(*args, **kwargs)\r
-        self._c = {\r
-            'file': FileMenu(),\r
-            'view': ViewMenu(),\r
-            'perspective': PerspectiveMenu(),\r
-            'help': HelpMenu(),\r
-            }\r
-        self.Append(self._c['file'], 'File')\r
-        self.Append(self._c['view'], 'View')\r
-        self.Append(self._c['perspective'], 'Perspective')\r
-        self.Append(self._c['help'], 'Help')\r
-\r
-\r
-class StatusBar (wx.StatusBar):\r
-    def __init__(self, *args, **kwargs):\r
-        super(StatusBar, self).__init__(*args, **kwargs)\r
-        self.SetStatusWidths([-2, -3])\r
-        self.SetStatusText('Ready', 0)\r
-        self.SetStatusText(u'Welcome to Hooke (version %s)' % version(), 1)\r
-\r
-\r
-class HookeFrame (wx.Frame):\r
-    def __init__(self, gui, commands, *args, **kwargs):\r
-        super(HookeFrame, self).__init__(*args, **kwargs)\r
-        self.gui = gui\r
-        self.commands = commands\r
-        self._perspectives = {}  # {name: perspective_str}\r
-        self._c = {}\r
-\r
-        self.SetIcon(wx.Icon(self.gui.config['icon image'], wx.BITMAP_TYPE_ICO))\r
-\r
-        # setup frame manager\r
-        self._c['manager'] = aui.AuiManager()\r
-        self._c['manager'].SetManagedWindow(self)\r
-\r
-        # set the gradient and drag styles\r
-        self._c['manager'].GetArtProvider().SetMetric(\r
-            aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)\r
-        self._c['manager'].SetFlags(\r
-            self._c['manager'].GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)\r
-\r
-        # Min size for the frame itself isn't completely done.  See\r
-        # the end of FrameManager::Update() for the test code. For\r
-        # now, just hard code a frame minimum size.\r
-        self.SetMinSize(wx.Size(500, 500))\r
-\r
-        self._setup_panels()\r
-        self._setup_toolbars()\r
-        self._c['manager'].Update()  # commit pending changes\r
-\r
-        # Create the menubar after the panes so that the default\r
-        # perspective is created with all panes open\r
-        self._c['menu bar'] = MenuBar(\r
-            )\r
-        self.SetMenuBar(self._c['menu bar'])\r
-\r
-        self._c['status bar'] = StatusBar(self, style=wx.ST_SIZEGRIP)\r
-\r
-        self._update_perspectives()\r
-        self._bind_events()\r
-\r
-        name = self.gui.config['active perspective']\r
-        return # TODO: cleanup\r
-        menu_item = self.GetPerspectiveMenuItem(name)\r
-        if menu_item is not None:\r
-            self._on_restore_perspective(menu_item)\r
-            #TODO: config setting to remember playlists from last session\r
-        self.playlists = self._c['playlists'].Playlists\r
-        self._displayed_plot = None\r
-        #load default list, if possible\r
-        self.do_loadlist(self.GetStringFromConfig('core', 'preferences', 'playlist'))\r
-\r
-    def _setup_panels(self):\r
-        client_size = self.GetClientSize()\r
-        for label,p,style in [\r
-            ('folders', wx.GenericDirCtrl(\r
-                    parent=self,\r
-                    dir=self.gui.config['folders-workdir'],\r
-                    size=(200, 250),\r
-                    style=wx.DIRCTRL_SHOW_FILTERS,\r
-                    filter=self.gui.config['folders-filters'],\r
-                    defaultFilter=int(self.gui.config['folders-filter-index'])), 'left'),  #HACK: config should convert\r
-            ('playlists', panel.playlist.Playlist(\r
-                    config=self.gui.config,\r
-                    callbacks={},\r
-                    parent=self,\r
-                    style=wx.WANTS_CHARS|wx.NO_BORDER,\r
-                    # WANTS_CHARS so the panel doesn't eat the Return key.\r
-                    size=(160, 200)), 'left'),\r
-            ('note', panel.note.Note(self), 'left'),\r
-            ('notebook', Notebook(\r
-                    parent=self,\r
-                    pos=wx.Point(client_size.x, client_size.y),\r
-                    size=wx.Size(430, 200),\r
-                    style=aui.AUI_NB_DEFAULT_STYLE\r
-                    | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER), 'center'),\r
-            ('commands', panel.commands.Commands(\r
-                    commands=self.commands,\r
-                    selected=self.gui.config['selected command'],\r
-                    callbacks={\r
-                        'execute': self.execute_command,\r
-                        'select_plugin': self.select_plugin,\r
-                        'select_command': self.select_command,\r
-#                        'selection_changed': self.panelProperties.select(self, method, command),  #SelectedTreeItem = selected_item,\r
-                        },\r
-                    parent=self,\r
-                    style=wx.WANTS_CHARS|wx.NO_BORDER,\r
-                    # WANTS_CHARS so the panel doesn't eat the Return key.\r
-                    size=(160, 200)), 'right'),\r
-            #('properties', panel.propertyeditor.PropertyEditor(self),'right'),\r
-            ('assistant', wx.TextCtrl(\r
-                    parent=self,\r
-                    pos=wx.Point(0, 0),\r
-                    size=wx.Size(150, 90),\r
-                    style=wx.NO_BORDER|wx.TE_MULTILINE), 'right'),\r
-            ('output', wx.TextCtrl(\r
-                    parent=self,\r
-                    pos=wx.Point(0, 0),\r
-                    size=wx.Size(150, 90),\r
-                    style=wx.NO_BORDER|wx.TE_MULTILINE), 'bottom'),\r
-            ('results', panel.results.Results(self), 'bottom'),\r
-            ]:\r
-            self._add_panel(label, p, style)\r
-        self._c['assistant'].SetEditable(False)\r
-\r
-    def _add_panel(self, label, panel, style):\r
-        self._c[label] = panel\r
-        cap_label = label.capitalize()\r
-        info = aui.AuiPaneInfo().Name(cap_label).Caption(cap_label)\r
-        if style == 'left':\r
-            info.Left().CloseButton(True).MaximizeButton(False)\r
-        elif style == 'center':\r
-            info.CenterPane().PaneBorder(False)\r
-        elif style == 'right':\r
-            info.Right().CloseButton(True).MaximizeButton(False)\r
-        else:\r
-            assert style == 'bottom', style\r
-            info.Bottom().CloseButton(True).MaximizeButton(False)\r
-        self._c['manager'].AddPane(panel, info)\r
-\r
-    def _setup_toolbars(self):\r
-        self._c['navbar'] = NavBar(self, style=wx.TB_FLAT | wx.TB_NODIVIDER)\r
-\r
-        self._c['manager'].AddPane(\r
-            self._c['navbar'],\r
-            aui.AuiPaneInfo().Name('Navigation').Caption('Navigation'\r
-                ).ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False\r
-                ).RightDockable(False))\r
-\r
-    def _bind_events(self):\r
-        # TODO: figure out if we can use the eventManager for menu\r
-        # ranges and events of 'self' without raising an assertion\r
-        # fail error.\r
-        self.Bind(wx.EVT_ERASE_BACKGROUND, self._on_erase_background)\r
-        self.Bind(wx.EVT_SIZE, self._on_size)\r
-        self.Bind(wx.EVT_CLOSE, self._on_close)\r
-        self.Bind(wx.EVT_MENU, self._on_close, id=wx.ID_EXIT)\r
-        self.Bind(wx.EVT_MENU, self._on_about, id=wx.ID_ABOUT)\r
-        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)\r
-        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self._on_notebook_page_close)\r
-\r
-        for value in self._c['menu bar']._c['view']._c.values():\r
-            self.Bind(wx.EVT_MENU_RANGE, self._on_view, value)\r
-\r
-        self.Bind(wx.EVT_MENU, self._on_save_perspective,\r
-                  self._c['menu bar']._c['perspective']._c['save'])\r
-        self.Bind(wx.EVT_MENU, self._on_delete_perspective,\r
-                  self._c['menu bar']._c['perspective']._c['delete'])\r
-\r
-        self.Bind(wx.EVT_TOOL, self._on_next, self._c['navbar']._c['next'])\r
-        self.Bind(wx.EVT_TOOL, self._on_previous,self._c['navbar']._c['previous'])\r
-\r
-        treeCtrl = self._c['folders'].GetTreeCtrl()\r
-        treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self._on_dir_ctrl_left_double_click)\r
-        \r
-        # TODO: playlist callbacks\r
-        return # TODO: cleanup\r
-        evtmgr.eventManager.Register(self.OnUpdateNote, wx.EVT_BUTTON, self.panelNote.UpdateButton)\r
-        #property editor\r
-        self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)\r
-        #results panel\r
-        self.panelResults.results_list.OnCheckItem = self.OnResultsCheck\r
-\r
-    def _GetActiveFileIndex(self):\r
-        lib.playlist.Playlist = self.GetActivePlaylist()\r
-        #get the selected item from the tree\r
-        selected_item = self._c['playlists']._c['tree'].GetSelection()\r
-        #test if a playlist or a curve was double-clicked\r
-        if self._c['playlists']._c['tree'].ItemHasChildren(selected_item):\r
-            return -1\r
-        else:\r
-            count = 0\r
-            selected_item = self._c['playlists']._c['tree'].GetPrevSibling(selected_item)\r
-            while selected_item.IsOk():\r
-                count += 1\r
-                selected_item = self._c['playlists']._c['tree'].GetPrevSibling(selected_item)\r
-            return count\r
-\r
-    def _GetPlaylistTab(self, name):\r
-        for index, page in enumerate(self._c['notebook']._tabs._pages):\r
-            if page.caption == name:\r
-                return index\r
-        return -1\r
-\r
-    def _restore_perspective(self, name):\r
-        # TODO: cleanup\r
-        self.gui.config['active perspective'] = name  # TODO: push to engine's Hooke\r
-        self._c['manager'].LoadPerspective(self._perspectives[name])\r
-        self._c['manager'].Update()\r
-        for pane in self._c['manager'].GetAllPanes():\r
-            if pane.name in self._c['menu bar']._c['view']._c.keys():\r
-                pane.Check(pane.window.IsShown())\r
-\r
-    def _SavePerspectiveToFile(self, name, perspective):\r
-        filename = ''.join([name, '.txt'])\r
-        filename = lh.get_file_path(filename, ['perspective'])\r
-        perspectivesFile = open(filename, 'w')\r
-        perspectivesFile.write(perspective)\r
-        perspectivesFile.close()\r
-\r
-    def execute_command(self, _class, method, command, args):\r
-        self.cmd.inqueue.put(CommandMessage(command, args))\r
-        while True:\r
-            msg = self.cmd.outqueue.get()\r
-            if isinstance(msg, Exit):\r
-                return True\r
-            elif isinstance(msg, CommandExit):\r
-                self.cmd.stdout.write(msg.__class__.__name__+'\n')\r
-                self.cmd.stdout.write(str(msg).rstrip()+'\n')\r
-                break\r
-            elif isinstance(msg, ReloadUserInterfaceConfig):\r
-                self.cmd.ui.reload_config(msg.config)\r
-                continue\r
-            elif isinstance(msg, Request):\r
-                self._handle_request(msg)\r
-                continue\r
-            self.cmd.stdout.write(str(msg).rstrip()+'\n')\r
-                #TODO: run the command\r
-                #command = ''.join(['self.do_', item_text, '()'])\r
-                #self.AppendToOutput(command + '\n')\r
-                #exec(command)\r
-\r
-    def select_plugin(self, _class, method, plugin):\r
-        for option in config[section]:\r
-            properties.append([option, config[section][option]])\r
-\r
-    def select_command(self, _class, method, command):\r
-        self.select_plugin(command.plugin)\r
-        plugin = self.GetItemText(selected_item)\r
-        if plugin != 'core':\r
-            doc_string = eval('plugins.' + plugin + '.' + plugin + 'Commands.__doc__')\r
-        else:\r
-            doc_string = 'The module "core" contains Hooke core functionality'\r
-        if doc_string is not None:\r
-            self.panelAssistant.ChangeValue(doc_string)\r
-        else:\r
-            self.panelAssistant.ChangeValue('')\r
-        panel.propertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)\r
-        self.gui.config['selected command'] = command\r
-\r
-    def AddPlaylistFromFiles(self, files=[], name='Untitled'):\r
-        if files:\r
-            playlist = lib.playlist.Playlist(self, 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.AddTayliss(playlist)\r
-\r
-    def AppendToOutput(self, text):\r
-        self.panelOutput.AppendText(''.join([text, '\n']))\r
-\r
-    def AppliesPlotmanipulator(self, name):\r
-        '''\r
-        Returns True if the plotmanipulator 'name' is applied, False otherwise\r
-        name does not contain 'plotmanip_', just the name of the plotmanipulator (e.g. 'flatten')\r
-        '''\r
-        return self.GetBoolFromConfig('core', 'plotmanipulators', name)\r
-\r
-    def ApplyPlotmanipulators(self, plot, plot_file):\r
-        '''\r
-        Apply all active plotmanipulators.\r
-        '''\r
-        if plot is not None and plot_file is not None:\r
-            manipulated_plot = copy.deepcopy(plot)\r
-            for plotmanipulator in self.plotmanipulators:\r
-                if self.GetBoolFromConfig('core', 'plotmanipulators', plotmanipulator.name):\r
-                    manipulated_plot = plotmanipulator.method(manipulated_plot, plot_file)\r
-            return manipulated_plot\r
-\r
-    def GetActiveFigure(self):\r
-        playlist_name = self.GetActivePlaylistName()\r
-        figure = self.playlists[playlist_name].figure\r
-        if figure is not None:\r
-            return figure\r
-        return None\r
-\r
-    def GetActiveFile(self):\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist is not None:\r
-            return playlist.get_active_file()\r
-        return None\r
-\r
-    def GetActivePlot(self):\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist is not None:\r
-            return playlist.get_active_file().plot\r
-        return None\r
-\r
-    def GetDisplayedPlot(self):\r
-        plot = copy.deepcopy(self.displayed_plot)\r
-        #plot.curves = []\r
-        #plot.curves = copy.deepcopy(plot.curves)\r
-        return plot\r
-\r
-    def GetDisplayedPlotCorrected(self):\r
-        plot = copy.deepcopy(self.displayed_plot)\r
-        plot.curves = []\r
-        plot.curves = copy.deepcopy(plot.corrected_curves)\r
-        return plot\r
-\r
-    def GetDisplayedPlotRaw(self):\r
-        plot = copy.deepcopy(self.displayed_plot)\r
-        plot.curves = []\r
-        plot.curves = copy.deepcopy(plot.raw_curves)\r
-        return plot\r
-\r
-    def GetDockArt(self):\r
-        return self._c['manager'].GetArtProvider()\r
-\r
-    def GetPlotmanipulator(self, name):\r
-        '''\r
-        Returns a plot manipulator function from its name\r
-        '''\r
-        for plotmanipulator in self.plotmanipulators:\r
-            if plotmanipulator.name == name:\r
-                return plotmanipulator\r
-        return None\r
-\r
-    def GetPerspectiveMenuItem(self, name):\r
-        if self._perspectives.has_key(name):\r
-            perspectives_list = [key for key, value in self._perspectives.iteritems()]\r
-            perspectives_list.sort()\r
-            index = perspectives_list.index(name)\r
-            perspective_Id = ID_FirstPerspective + index\r
-            menu_item = self.MenuBar.FindItemById(perspective_Id)\r
-            return menu_item\r
-        else:\r
-            return None\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.command == name:\r
-                return True\r
-        return False\r
-\r
-    def _on_about(self, event):\r
-        message = 'Hooke\n\n'+\\r
-            'A free, open source data analysis platform\n\n'+\\r
-            'Copyright 2006-2008 by Massimo Sandal\n'+\\r
-            'Copyright 2010 by Dr. Rolf Schmidt\n\n'+\\r
-            'Hooke is released under the GNU General Public License version 2.'\r
-        dialog = wx.MessageDialog(self, message, 'About Hooke', wx.OK | wx.ICON_INFORMATION)\r
-        dialog.ShowModal()\r
-        dialog.Destroy()\r
-\r
-    def _on_close(self, event):\r
-        # apply changes\r
-        self.gui.config['main height'] = str(self.GetSize().GetHeight())\r
-        self.gui.config['main left'] = str(self.GetPosition()[0])\r
-        self.gui.config['main top'] = str(self.GetPosition()[1])\r
-        self.gui.config['main width'] = str(self.GetSize().GetWidth())\r
-        # push changes back to Hooke.config?\r
-        self._c['manager'].UnInit()\r
-        del self._c['manager']\r
-        self.Destroy()\r
-\r
-    def _update_perspectives(self):\r
-        """Add perspectives to menubar and _perspectives.\r
-        """\r
-        self._perspectives = {\r
-            'Default': self._c['manager'].SavePerspective(),\r
-            }\r
-        path = self.gui.config['perspective path']\r
-        if os.path.isdir(path):\r
-            files = sorted(os.listdir(path))\r
-            for fname in files:\r
-                name, extension = os.path.splitext(fname)\r
-                if extension != '.txt':\r
-                    continue\r
-                fpath = os.path.join(path, fpath)\r
-                if not os.path.isfile(fpath):\r
-                    continue\r
-                perspective = None\r
-                with open(fpath, 'rU') as f:\r
-                    perspective = f.readline()\r
-                if perspective:\r
-                    self._perspectives[name] = perspective\r
-\r
-        selected_perspective = self.gui.config['active perspective']\r
-        if not self._perspectives.has_key(selected_perspective):\r
-            self.gui.config['active perspective'] = 'Default'  # TODO: push to engine's Hooke\r
-\r
-        self._update_perspective_menu()\r
-        self._restore_perspective(selected_perspective)\r
-\r
-    def _update_perspective_menu(self):\r
-        self._c['menu bar']._c['perspective'].update(\r
-            sorted(self._perspectives.keys()),\r
-            self.gui.config['active perspective'],\r
-            self._on_restore_perspective)\r
-\r
-    def _on_restore_perspective(self, event):\r
-        name = self.MenuBar.FindItemById(event.GetId()).GetLabel()\r
-        self._restore_perspective(name)\r
-\r
-    def _on_save_perspective(self, event):\r
-        def nameExists(name):\r
-            menu_position = self.MenuBar.FindMenu('Perspective')\r
-            menu = self.MenuBar.GetMenu(menu_position)\r
-            for item in 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._c['manager'].SavePerspective()\r
-        self._SavePerspectiveToFile(name, perspective)\r
-        self.gui.config['active perspectives'] = name\r
-        self._update_perspective_menu()\r
-#        if nameExists(name):\r
-#            #check the corresponding menu item\r
-#            menu_item = self.GetPerspectiveMenuItem(name)\r
-#            #replace the perspectiveStr in _pespectives\r
-#            self._perspectives[name] = perspective\r
-#        else:\r
-#            #because we deal with radio items, we need to do some extra work\r
-#            #delete all menu items from the perspectives menu\r
-#            for item in self._perspectives_menu.GetMenuItems():\r
-#                self._perspectives_menu.DeleteItem(item)\r
-#            #recreate the perspectives menu\r
-#            self._perspectives_menu.Append(ID_SavePerspective, 'Save Perspective')\r
-#            self._perspectives_menu.Append(ID_DeletePerspective, 'Delete Perspective')\r
-#            self._perspectives_menu.AppendSeparator()\r
-#            #convert the perspectives dictionary into a list\r
-#            # the list contains:\r
-#            #[0]: name of the perspective\r
-#            #[1]: perspective\r
-#            perspectives_list = [key for key, value in self._perspectives.iteritems()]\r
-#            perspectives_list.append(name)\r
-#            perspectives_list.sort()\r
-#            #add all previous perspectives\r
-#            for index, item in enumerate(perspectives_list):\r
-#                menu_item = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + index, item)\r
-#                if item == name:\r
-#                    menu_item.Check()\r
-#            #add the new perspective to _perspectives\r
-#            self._perspectives[name] = perspective\r
-\r
-    def _on_delete_perspective(self, event):\r
-        dialog = panel.selection.Selection(\r
-            options=sorted(os.listdir(self.gui.config['perspective path'])),\r
-            message="\nPlease check the perspectives\n\nyou want to delete and click 'Delete'.\n",\r
-            button_id=wx.ID_DELETE,\r
-            button_callback=self._on_delete_perspective,\r
-            parent=self,\r
-            label='Delete perspective(s)',\r
-            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)\r
-        dialog.CenterOnScreen()\r
-        dialog.ShowModal()\r
-        dialog.Destroy()\r
-        self._update_perspective_menu()\r
-        # Unfortunately, there is a bug in wxWidgets for win32 (Ticket #3258\r
-        #   http://trac.wxwidgets.org/ticket/3258 \r
-        # ) that makes the radio item indicator in the menu disappear.\r
-        # The code should be fine once this issue is fixed.\r
-\r
-    def _on_delete_perspective(self, event, items, selected_items):\r
-        for item in selected_items:\r
-            self._perspectives.remove(item)\r
-            if item == self.gui.config['active perspective']:\r
-                self.gui.config['active perspective'] = 'Default'\r
-            path = os.path.join(self.gui.config['perspective path'],\r
-                                item+'.txt')\r
-            remove(path)\r
-        self._update_perspective_menu()\r
-\r
-    def _on_dir_ctrl_left_double_click(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
-        event.Skip()\r
-\r
-    def _on_erase_background(self, event):\r
-        event.Skip()\r
-\r
-    def OnExit(self, event):\r
-        self.Close()\r
-\r
-    def _on_next(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._c['playlists']._c['tree'].GetSelection()\r
-        if self._c['playlists']._c['tree'].ItemHasChildren(selected_item):\r
-            #GetFirstChild returns a tuple\r
-            #we only need the first element\r
-            next_item = self._c['playlists']._c['tree'].GetFirstChild(selected_item)[0]\r
-        else:\r
-            next_item = self._c['playlists']._c['tree'].GetNextSibling(selected_item)\r
-            if not next_item.IsOk():\r
-                parent_item = self._c['playlists']._c['tree'].GetItemParent(selected_item)\r
-                #GetFirstChild returns a tuple\r
-                #we only need the first element\r
-                next_item = self._c['playlists']._c['tree'].GetFirstChild(parent_item)[0]\r
-        self._c['playlists']._c['tree'].SelectItem(next_item, True)\r
-        if not self._c['playlists']._c['tree'].ItemHasChildren(selected_item):\r
-            playlist = self.GetActivePlaylist()\r
-            if playlist.count > 1:\r
-                playlist.next()\r
-                self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-                self.UpdateNote()\r
-                self.UpdatePlot()\r
-\r
-    def _on_notebook_page_close(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 _on_previous(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._c['playlists']._c['tree'].GetSelection()\r
-        if self._c['playlists']._c['tree'].ItemHasChildren(selected_item):\r
-            previous_item = self._c['playlists']._c['tree'].GetLastChild(selected_item)\r
-        else:\r
-            previous_item = self._c['playlists']._c['tree'].GetPrevSibling(selected_item)\r
-            if not previous_item.IsOk():\r
-                parent_item = self._c['playlists']._c['tree'].GetItemParent(selected_item)\r
-                previous_item = self._c['playlists']._c['tree'].GetLastChild(parent_item)\r
-        self._c['playlists']._c['tree'].SelectItem(previous_item, True)\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist.count > 1:\r
-            playlist.previous()\r
-            self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-            self.UpdateNote()\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._c['commands']._c['tree'].GetItemParent(item_section)\r
-            plugin = self._c['commands']._c['tree'].GetItemText(item_plugin)\r
-            config = self.gui.config[plugin]\r
-            property_section = self._c['commands']._c['tree'].GetItemText(item_section)\r
-            property_key = prop.GetName()\r
-            property_value = prop.GetDisplayedString()\r
-\r
-            config[property_section][property_key]['value'] = property_value\r
-\r
-    def OnResultsCheck(self, index, flag):\r
-        results = self.GetActivePlot().results\r
-        if results.has_key(self.results_str):\r
-            results[self.results_str].results[index].visible = flag\r
-            results[self.results_str].update()\r
-            self.UpdatePlot()\r
-\r
-\r
-    def _on_size(self, event):\r
-        event.Skip()\r
-\r
-    def OnUpdateNote(self, event):\r
-        '''\r
-        Saves the note to the active file.\r
-        '''\r
-        active_file = self.GetActiveFile()\r
-        active_file.note = self.panelNote.Editor.GetValue()\r
-\r
-    def _on_view(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._c['manager'].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._c['manager'].Update()\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 = lib.clickedpoint.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
-    def _delta(self, message='Click 2 points', block=0):\r
-        '''\r
-        Calculates the difference between two clicked points\r
-        '''\r
-        clicked_points = self._measure_N_points(N=2, message=message, block=block)\r
-\r
-        plot = self.GetDisplayedPlotCorrected()\r
-        curve = plot.curves[block]\r
-\r
-        delta = lib.delta.Delta()\r
-        delta.point1.x = clicked_points[0].graph_coords[0]\r
-        delta.point1.y = clicked_points[0].graph_coords[1]\r
-        delta.point2.x = clicked_points[1].graph_coords[0]\r
-        delta.point2.y = clicked_points[1].graph_coords[1]\r
-        delta.units.x = curve.units.x\r
-        delta.units.y = curve.units.y\r
-\r
-        return delta\r
-\r
-    def _measure_N_points(self, N, message='', block=0):\r
-        '''\r
-        General helper function for N-points measurements\r
-        By default, measurements are done on the retraction\r
-        '''\r
-        if message:\r
-            dialog = wx.MessageDialog(None, message, 'Info', wx.OK)\r
-            dialog.ShowModal()\r
-\r
-        figure = self.GetActiveFigure()\r
-\r
-        xvector = self.displayed_plot.curves[block].x\r
-        yvector = self.displayed_plot.curves[block].y\r
-\r
-        clicked_points = figure.ginput(N, timeout=-1, show_clicks=True)\r
-\r
-        points = []\r
-        for clicked_point in clicked_points:\r
-            point = lib.clickedpoint.ClickedPoint()\r
-            point.absolute_coords = clicked_point[0], clicked_point[1]\r
-            point.dest = 0\r
-            #TODO: make this optional?\r
-            #so far, the clicked point is taken, not the corresponding data point\r
-            point.find_graph_coords(xvector, yvector)\r
-            point.is_line_edge = True\r
-            point.is_marker = True\r
-            points.append(point)\r
-        return points\r
-\r
-    def do_copylog(self):\r
-        '''\r
-        Copies all files in the current playlist that have a note to the destination folder.\r
-        destination: select folder where you want the files to be copied\r
-        use_LVDT_folder: when checked, the files will be copied to a folder called 'LVDT' in the destination folder (for MFP-1D files only)\r
-        '''\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist is not None:\r
-            destination = self.GetStringFromConfig('core', 'copylog', 'destination')\r
-            if not os.path.isdir(destination):\r
-                os.makedirs(destination)\r
-            for current_file in playlist.files:\r
-                if current_file.note:\r
-                    shutil.copy(current_file.filename, destination)\r
-                    if current_file.driver.filetype == 'mfp1d':\r
-                        filename = current_file.filename.replace('deflection', 'LVDT', 1)\r
-                        path, name = os.path.split(filename)\r
-                        filename = os.path.join(path, 'lvdt', name)\r
-                        use_LVDT_folder = self.GetBoolFromConfig('core', 'copylog', 'use_LVDT_folder')\r
-                        if use_LVDT_folder:\r
-                            destination = os.path.join(destination, 'LVDT')\r
-                        shutil.copy(filename, destination)\r
-\r
-    def do_plotmanipulators(self):\r
-        '''\r
-        Please select the plotmanipulators you would like to use\r
-        and define the order in which they will be applied to the data.\r
-\r
-        Click 'Execute' to apply your changes.\r
-        '''\r
-        self.UpdatePlot()\r
-\r
-    def do_preferences(self):\r
-        '''\r
-        Please set general preferences for Hooke here.\r
-        hide_curve_extension: hides the extension of the force curve files.\r
-                              not recommended for 'picoforce' files\r
-        '''\r
-        pass\r
-\r
-    def do_test(self):\r
-        '''\r
-        Use this command for testing purposes. You find do_test in hooke.py.\r
-        '''\r
-        pass\r
-\r
-    def do_version(self):\r
-        '''\r
-        VERSION\r
-        ------\r
-        Prints the current version and codename, plus library version. Useful for debugging.\r
-        '''\r
-        self.AppendToOutput('Hooke ' + __version__ + ' (' + __codename__ + ')')\r
-        self.AppendToOutput('Released on: ' + __releasedate__)\r
-        self.AppendToOutput('---')\r
-        self.AppendToOutput('Python version: ' + python_version)\r
-        self.AppendToOutput('WxPython version: ' + wx_version)\r
-        self.AppendToOutput('Matplotlib version: ' + mpl_version)\r
-        self.AppendToOutput('SciPy version: ' + scipy_version)\r
-        self.AppendToOutput('NumPy version: ' + numpy_version)\r
-        self.AppendToOutput('ConfigObj version: ' + configobj_version)\r
-        self.AppendToOutput('wxPropertyGrid version: ' + '.'.join([str(PROPGRID_MAJOR), str(PROPGRID_MINOR), str(PROPGRID_RELEASE)]))\r
-        self.AppendToOutput('---')\r
-        self.AppendToOutput('Platform: ' + str(platform.uname()))\r
-        self.AppendToOutput('******************************')\r
-        self.AppendToOutput('Loaded plugins')\r
-        self.AppendToOutput('---')\r
-\r
-        #sort the plugins into alphabetical order\r
-        plugins_list = [key for key, value in self.plugins.iteritems()]\r
-        plugins_list.sort()\r
-        for plugin in plugins_list:\r
-            self.AppendToOutput(plugin)\r
-\r
-    def UpdateNote(self):\r
-        #update the note for the active file\r
-        active_file = self.GetActiveFile()\r
-        if active_file is not None:\r
-            self.panelNote.Editor.SetValue(active_file.note)\r
-\r
-    def UpdatePlaylistsTreeSelection(self):\r
-        playlist = self.GetActivePlaylist()\r
-        if playlist is not None:\r
-            if playlist.index >= 0:\r
-                self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-                self.UpdateNote()\r
-                self.UpdatePlot()\r
-\r
-    def UpdatePlot(self, plot=None):\r
-\r
-        def add_to_plot(curve, set_scale=True):\r
-            if curve.visible and curve.x and curve.y:\r
-                #get the index of the subplot to use as destination\r
-                destination = (curve.destination.column - 1) * number_of_rows + curve.destination.row - 1\r
-                #set all parameters for the plot\r
-                axes_list[destination].set_title(curve.title)\r
-                if set_scale:\r
-                    axes_list[destination].set_xlabel(curve.prefix.x + curve.units.x)\r
-                    axes_list[destination].set_ylabel(curve.prefix.y + curve.units.y)\r
-                    #set the formatting details for the scale\r
-                    formatter_x = lib.curve.PrefixFormatter(curve.decimals.x, curve.prefix.x, use_zero)\r
-                    formatter_y = lib.curve.PrefixFormatter(curve.decimals.y, curve.prefix.y, use_zero)\r
-                    axes_list[destination].xaxis.set_major_formatter(formatter_x)\r
-                    axes_list[destination].yaxis.set_major_formatter(formatter_y)\r
-                if curve.style == 'plot':\r
-                    axes_list[destination].plot(curve.x, curve.y, color=curve.color, label=curve.label, lw=curve.linewidth, zorder=1)\r
-                if curve.style == 'scatter':\r
-                    axes_list[destination].scatter(curve.x, curve.y, color=curve.color, label=curve.label, s=curve.size, zorder=2)\r
-                #add the legend if necessary\r
-                if curve.legend:\r
-                    axes_list[destination].legend()\r
-\r
-        if plot is None:\r
-            active_file = self.GetActiveFile()\r
-            if not active_file.driver:\r
-                #the first time we identify a file, the following need to be set\r
-                active_file.identify(self.drivers)\r
-                for curve in active_file.plot.curves:\r
-                    curve.decimals.x = self.GetIntFromConfig('core', 'preferences', 'x_decimals')\r
-                    curve.decimals.y = self.GetIntFromConfig('core', 'preferences', 'y_decimals')\r
-                    curve.legend = self.GetBoolFromConfig('core', 'preferences', 'legend')\r
-                    curve.prefix.x = self.GetStringFromConfig('core', 'preferences', 'x_prefix')\r
-                    curve.prefix.y = self.GetStringFromConfig('core', 'preferences', 'y_prefix')\r
-            if active_file.driver is None:\r
-                self.AppendToOutput('Invalid file: ' + active_file.filename)\r
-                return\r
-            self.displayed_plot = copy.deepcopy(active_file.plot)\r
-            #add raw curves to plot\r
-            self.displayed_plot.raw_curves = copy.deepcopy(self.displayed_plot.curves)\r
-            #apply all active plotmanipulators\r
-            self.displayed_plot = self.ApplyPlotmanipulators(self.displayed_plot, active_file)\r
-            #add corrected curves to plot\r
-            self.displayed_plot.corrected_curves = copy.deepcopy(self.displayed_plot.curves)\r
-        else:\r
-            active_file = None\r
-            self.displayed_plot = copy.deepcopy(plot)\r
-\r
-        figure = self.GetActiveFigure()\r
-        figure.clear()\r
-\r
-        #use '0' instead of e.g. '0.00' for scales\r
-        use_zero = self.GetBoolFromConfig('core', 'preferences', 'use_zero')\r
-        #optionally remove the extension from the title of the plot\r
-        hide_curve_extension = self.GetBoolFromConfig('core', 'preferences', 'hide_curve_extension')\r
-        if hide_curve_extension:\r
-            title = lh.remove_extension(self.displayed_plot.title)\r
-        else:\r
-            title = self.displayed_plot.title\r
-        figure.suptitle(title, fontsize=14)\r
-        #create the list of all axes necessary (rows and columns)\r
-        axes_list =[]\r
-        number_of_columns = max([curve.destination.column for curve in self.displayed_plot.curves])\r
-        number_of_rows = max([curve.destination.row for curve in self.displayed_plot.curves])\r
-        for index in range(number_of_rows * number_of_columns):\r
-            axes_list.append(figure.add_subplot(number_of_rows, number_of_columns, index + 1))\r
-\r
-        #add all curves to the corresponding plots\r
-        for curve in self.displayed_plot.curves:\r
-            add_to_plot(curve)\r
-\r
-        #make sure the titles of 'subplots' do not overlap with the axis labels of the 'main plot'\r
-        figure.subplots_adjust(hspace=0.3)\r
-\r
-        #display results\r
-        self.panelResults.ClearResults()\r
-        if self.displayed_plot.results.has_key(self.results_str):\r
-            for curve in self.displayed_plot.results[self.results_str].results:\r
-                add_to_plot(curve, set_scale=False)\r
-            self.panelResults.DisplayResults(self.displayed_plot.results[self.results_str])\r
-        else:\r
-            self.panelResults.ClearResults()\r
-        #refresh the plot\r
-        figure.canvas.draw()\r
-\r
-    def _on_curve_select(self, playlist, curve):\r
-        #create the plot tab and add playlist to the dictionary\r
-        plotPanel = panel.plot.PlotPanel(self, ID_FirstPlot + len(self.playlists))\r
-        notebook_tab = self._c['notebook'].AddPage(plotPanel, playlist.name, True)\r
-        #tab_index = self._c['notebook'].GetSelection()\r
-        playlist.figure = plotPanel.get_figure()\r
-        self.playlists[playlist.name] = playlist\r
-        #self.playlists[playlist.name] = [playlist, figure]\r
-        self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-        self.UpdateNote()\r
-        self.UpdatePlot()\r
-\r
-\r
-    def _on_playlist_left_doubleclick(self):\r
-        index = self._c['notebook'].GetSelection()\r
-        current_playlist = self._c['notebook'].GetPageText(index)\r
-        if current_playlist != playlist_name:\r
-            index = self._GetPlaylistTab(playlist_name)\r
-            self._c['notebook'].SetSelection(index)\r
-        self.statusbar.SetStatusText(playlist.get_status_string(), 0)\r
-        self.UpdateNote()\r
-        self.UpdatePlot()\r
-\r
-    def _on_playlist_delete(self, playlist):\r
-        notebook = self.Parent.plotNotebook\r
-        index = self.Parent._GetPlaylistTab(playlist.name)\r
-        notebook.SetSelection(index)\r
-        notebook.DeletePage(notebook.GetSelection())\r
-        self.Parent.DeleteFromPlaylists(playlist_name)\r
-        \r
-\r
-class HookeApp (wx.App):\r
-    def __init__(self, gui, commands, inqueue, outqueue, *args, **kwargs):\r
-        self.gui = gui\r
-        self.commands = commands\r
-        self.inqueue = inqueue\r
-        self.outqueue = outqueue\r
-        super(HookeApp, self).__init__(*args, **kwargs)\r
-\r
-    def OnInit(self):\r
-        self.SetAppName('Hooke')\r
-        self.SetVendorName('')\r
-        self._setup_splash_screen()\r
-\r
-        height = int(self.gui.config['main height']) # HACK: config should convert\r
-        width = int(self.gui.config['main width'])\r
-        top = int(self.gui.config['main top'])\r
-        left = int(self.gui.config['main left'])\r
-\r
-        # Sometimes, the ini file gets confused and sets 'left' and\r
-        # 'top' to large negative numbers.  Here we catch and fix\r
-        # this.  Keep small negative numbers, the user might want\r
-        # those.\r
-        if left < -width:\r
-            left = 0\r
-        if top < -height:\r
-            top = 0\r
-\r
-        self._c = {\r
-            'frame': HookeFrame(\r
-                self.gui, self.commands, parent=None, title='Hooke',\r
-                pos=(left, top), size=(width, height),\r
-                style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN),\r
-            }\r
-        self._c['frame'].Show(True)\r
-        self.SetTopWindow(self._c['frame'])\r
-        return True\r
-\r
-    def _setup_splash_screen(self):\r
-        if self.gui.config['show splash screen']:\r
-            path = self.gui.config['splash screen image']\r
-            if os.path.isfile(path):\r
-                duration = int(self.gui.config['splash screen duration'])  # HACK: config should decode types\r
-                wx.SplashScreen(\r
-                    bitmap=wx.Image(path).ConvertToBitmap(),\r
-                    splashStyle=wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,\r
-                    milliseconds=duration,\r
-                    parent=None)\r
-                wx.Yield()\r
-                # For some reason splashDuration and sleep do not\r
-                # correspond to each other at least not on Windows.\r
-                # Maybe it's because duration is in milliseconds and\r
-                # sleep in seconds.  Thus we need to increase the\r
-                # sleep time a bit. A factor of 1.2 seems to work.\r
-                sleepFactor = 1.2\r
-                time.sleep(sleepFactor * duration / 1000)\r
-\r
-    def OnExit(self):\r
-        return True\r
-\r
-\r
-class GUI (UserInterface):\r
-    """wxWindows graphical user interface.\r
-    """\r
-    def __init__(self):\r
-        super(GUI, self).__init__(name='gui')\r
-\r
-    def default_settings(self):\r
-        """Return a list of :class:`hooke.config.Setting`\s for any\r
-        configurable UI settings.\r
-\r
-        The suggested section setting is::\r
-\r
-            Setting(section=self.setting_section, help=self.__doc__)\r
-        """\r
-        return [\r
-            Setting(section=self.setting_section, help=self.__doc__),\r
-            Setting(section=self.setting_section, option='icon image',\r
-                    value=os.path.join('doc', 'img', 'microscope.ico'),\r
-                    help='Path to the hooke icon image.'),\r
-            Setting(section=self.setting_section, option='show splash screen',\r
-                    value=True,\r
-                    help='Enable/disable the splash screen'),\r
-            Setting(section=self.setting_section, option='splash screen image',\r
-                    value=os.path.join('doc', 'img', 'hooke.jpg'),\r
-                    help='Path to the Hooke splash screen image.'),\r
-            Setting(section=self.setting_section, option='splash screen duration',\r
-                    value=1000,\r
-                    help='Duration of the splash screen in milliseconds.'),\r
-            Setting(section=self.setting_section, option='perspective path',\r
-                    value=os.path.join('resources', 'gui', 'perspective'),\r
-                    help='Directory containing perspective files.'), # TODO: allow colon separated list, like $PATH.\r
-            Setting(section=self.setting_section, option='hide extensions',\r
-                    value=False,\r
-                    help='Hide file extensions when displaying names.'),\r
-            Setting(section=self.setting_section, option='folders-workdir',\r
-                    value='.',\r
-                    help='This should probably go...'),\r
-            Setting(section=self.setting_section, option='folders-filters',\r
-                    value='.',\r
-                    help='This should probably go...'),\r
-            Setting(section=self.setting_section, option='active perspective',\r
-                    value='Default',\r
-                    help='Name of active perspective file (or "Default").'),\r
-            Setting(section=self.setting_section, option='folders-filter-index',\r
-                    value='0',\r
-                    help='This should probably go...'),\r
-            Setting(section=self.setting_section, option='main height',\r
-                    value=500,\r
-                    help='Height of main window in pixels.'),\r
-            Setting(section=self.setting_section, option='main width',\r
-                    value=500,\r
-                    help='Width of main window in pixels.'),\r
-            Setting(section=self.setting_section, option='main top',\r
-                    value=0,\r
-                    help='Pixels from screen top to top of main window.'),\r
-            Setting(section=self.setting_section, option='main left',\r
-                    value=0,\r
-                    help='Pixels from screen left to left of main window.'),            \r
-            Setting(section=self.setting_section, option='selected command',\r
-                    value='load playlist',\r
-                    help='Name of the initially selected command.'),\r
-            ]\r
-\r
-    def _app(self, commands, ui_to_command_queue, command_to_ui_queue):\r
-        redirect = True\r
-        if __debug__:\r
-            redirect=False\r
-        app = HookeApp(gui=self,\r
-                       commands=commands,\r
-                       inqueue=ui_to_command_queue,\r
-                       outqueue=command_to_ui_queue,\r
-                       redirect=redirect)\r
-        return app\r
-\r
-    def run(self, commands, ui_to_command_queue, command_to_ui_queue):\r
-        app = self._app(commands, ui_to_command_queue, command_to_ui_queue)\r
-        app.MainLoop()\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/>.
+
+"""Defines :class:`GUI` providing a wxWidgets interface to Hooke.
+
+"""
+
+WX_GOOD=['2.8']
+
+import wxversion
+wxversion.select(WX_GOOD)
+
+import copy
+import logging
+import os
+import os.path
+import platform
+import shutil
+import time
+
+import wx.html
+import wx.aui as aui
+import wx.lib.evtmgr as evtmgr
+# wxPropertyGrid is included in wxPython >= 2.9.1, see
+#   http://wxpropgrid.sourceforge.net/cgi-bin/index?page=download
+# until then, we'll avoid it because of the *nix build problems.
+#import wx.propgrid as wxpg
+
+from ...command import CommandExit, Exit, Success, Failure, Command, Argument
+from ...config import Setting
+from ...interaction import Request, BooleanRequest, ReloadUserInterfaceConfig
+from ...ui import UserInterface, CommandMessage
+from .dialog.selection import Selection as SelectionDialog
+from .dialog.save_file import select_save_file
+from . import menu as menu
+from . import navbar as navbar
+from . import panel as panel
+from .panel.propertyeditor import props_from_argument, props_from_setting
+from . import statusbar as statusbar
+
+
+class HookeFrame (wx.Frame):
+    """The main Hooke-interface window.    
+    """
+    def __init__(self, gui, commands, inqueue, outqueue, *args, **kwargs):
+        super(HookeFrame, self).__init__(*args, **kwargs)
+        self.log = logging.getLogger('hooke')
+        self.gui = gui
+        self.commands = commands
+        self.inqueue = inqueue
+        self.outqueue = outqueue
+        self._perspectives = {}  # {name: perspective_str}
+        self._c = {}
+
+        self.SetIcon(wx.Icon(self.gui.config['icon image'], wx.BITMAP_TYPE_ICO))
+
+        # setup frame manager
+        self._c['manager'] = aui.AuiManager()
+        self._c['manager'].SetManagedWindow(self)
+
+        # set the gradient and drag styles
+        self._c['manager'].GetArtProvider().SetMetric(
+            aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)
+        self._c['manager'].SetFlags(
+            self._c['manager'].GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)
+
+        # Min size for the frame itself isn't completely done.  See
+        # the end of FrameManager::Update() for the test code. For
+        # now, just hard code a frame minimum size.
+        #self.SetMinSize(wx.Size(500, 500))
+
+        self._setup_panels()
+        self._setup_toolbars()
+        self._c['manager'].Update()  # commit pending changes
+
+        # Create the menubar after the panes so that the default
+        # perspective is created with all panes open
+        panels = [p for p in self._c.values() if isinstance(p, panel.Panel)]
+        self._c['menu bar'] = menu.HookeMenuBar(
+            parent=self,
+            panels=panels,
+            callbacks={
+                'close': self._on_close,
+                'about': self._on_about,
+                'view_panel': self._on_panel_visibility,
+                'save_perspective': self._on_save_perspective,
+                'delete_perspective': self._on_delete_perspective,
+                'select_perspective': self._on_select_perspective,
+                })
+        self.SetMenuBar(self._c['menu bar'])
+
+        self._c['status bar'] = statusbar.StatusBar(
+            parent=self,
+            style=wx.ST_SIZEGRIP)
+        self.SetStatusBar(self._c['status bar'])
+
+        self._setup_perspectives()
+        self._bind_events()
+
+        self.execute_command(
+                command=self._command_by_name('load playlist'),
+                args={'input':'test/data/test'},#vclamp_picoforce/playlist'},
+                )
+        self.execute_command(
+                command=self._command_by_name('load playlist'),
+                args={'input':'test/data/vclamp_picoforce/playlist'},
+                )
+        self.execute_command(
+                command=self._command_by_name('polymer fit'),
+                args={'block':1, 'bounds':[918, 1103]},
+                )
+        return # TODO: cleanup
+        self.playlists = self._c['playlist'].Playlists
+        self._displayed_plot = None
+        #load default list, if possible
+        self.do_loadlist(self.GetStringFromConfig('core', 'preferences', 'playlists'))
+
+
+    # GUI maintenance
+
+    def _setup_panels(self):
+        client_size = self.GetClientSize()
+        for p,style in [
+#            ('folders', wx.GenericDirCtrl(
+#                    parent=self,
+#                    dir=self.gui.config['folders-workdir'],
+#                    size=(200, 250),
+#                    style=wx.DIRCTRL_SHOW_FILTERS,
+#                    filter=self.gui.config['folders-filters'],
+#                    defaultFilter=self.gui.config['folders-filter-index']), 'left'),
+            (panel.PANELS['playlist'](
+                    callbacks={
+                        'delete_playlist':self._on_user_delete_playlist,
+                        '_delete_playlist':self._on_delete_playlist,
+                        'delete_curve':self._on_user_delete_curve,
+                        '_delete_curve':self._on_delete_curve,
+                        '_on_set_selected_playlist':self._on_set_selected_playlist,
+                        '_on_set_selected_curve':self._on_set_selected_curve,
+                        },
+                    parent=self,
+                    style=wx.WANTS_CHARS|wx.NO_BORDER,
+                    # WANTS_CHARS so the panel doesn't eat the Return key.
+#                    size=(160, 200),
+                    ), 'left'),
+            (panel.PANELS['note'](
+                    callbacks = {
+                        '_on_update':self._on_update_note,
+                        },
+                    parent=self,
+                    style=wx.WANTS_CHARS|wx.NO_BORDER,
+#                    size=(160, 200),
+                    ), 'left'),
+#            ('notebook', Notebook(
+#                    parent=self,
+#                    pos=wx.Point(client_size.x, client_size.y),
+#                    size=wx.Size(430, 200),
+#                    style=aui.AUI_NB_DEFAULT_STYLE
+#                    | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER), 'center'),
+            (panel.PANELS['commands'](
+                    commands=self.commands,
+                    selected=self.gui.config['selected command'],
+                    callbacks={
+                        'execute': self.execute_command,
+                        'select_plugin': self.select_plugin,
+                        'select_command': self.select_command,
+#                        'selection_changed': self.panelProperties.select(self, method, command),  #SelectedTreeItem = selected_item,
+                        },
+                    parent=self,
+                    style=wx.WANTS_CHARS|wx.NO_BORDER,
+                    # WANTS_CHARS so the panel doesn't eat the Return key.
+#                    size=(160, 200),
+                    ), 'right'),
+            (panel.PANELS['propertyeditor'](
+                    callbacks={},
+                    parent=self,
+                    style=wx.WANTS_CHARS,
+                    # WANTS_CHARS so the panel doesn't eat the Return key.
+                    ), 'center'),
+            (panel.PANELS['plot'](
+                    callbacks={
+                        '_set_status_text': self._on_plot_status_text,
+                        },
+                    parent=self,
+                    style=wx.WANTS_CHARS|wx.NO_BORDER,
+                    # WANTS_CHARS so the panel doesn't eat the Return key.
+#                    size=(160, 200),
+                    ), 'center'),
+            (panel.PANELS['output'](
+                    parent=self,
+                    pos=wx.Point(0, 0),
+                    size=wx.Size(150, 90),
+                    style=wx.TE_READONLY|wx.NO_BORDER|wx.TE_MULTILINE),
+             'bottom'),
+#            ('results', panel.results.Results(self), 'bottom'),
+            ]:
+            self._add_panel(p, style)
+
+    def _add_panel(self, panel, style):
+        self._c[panel.name] = panel
+        m_name = panel.managed_name
+        info = aui.AuiPaneInfo().Name(m_name).Caption(m_name)
+        info.PaneBorder(False).CloseButton(True).MaximizeButton(False)
+        if style == 'top':
+            info.Top()
+        elif style == 'center':
+            info.CenterPane()
+        elif style == 'left':
+            info.Left()
+        elif style == 'right':
+            info.Right()
+        else:
+            assert style == 'bottom', style
+            info.Bottom()
+        self._c['manager'].AddPane(panel, info)
+
+    def _setup_toolbars(self):
+        self._c['navigation bar'] = navbar.NavBar(
+            callbacks={
+                'next': self._next_curve,
+                'previous': self._previous_curve,
+                },
+            parent=self,
+            style=wx.TB_FLAT | wx.TB_NODIVIDER)
+        self._c['manager'].AddPane(
+            self._c['navigation bar'],
+            aui.AuiPaneInfo().Name('Navigation').Caption('Navigation'
+                ).ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False
+                ).RightDockable(False))
+
+    def _bind_events(self):
+        # TODO: figure out if we can use the eventManager for menu
+        # ranges and events of 'self' without raising an assertion
+        # fail error.
+        self.Bind(wx.EVT_ERASE_BACKGROUND, self._on_erase_background)
+        self.Bind(wx.EVT_SIZE, self._on_size)
+        self.Bind(wx.EVT_CLOSE, self._on_close)
+        self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
+        self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self._on_notebook_page_close)
+
+        return # TODO: cleanup
+        treeCtrl = self._c['folders'].GetTreeCtrl()
+        treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self._on_dir_ctrl_left_double_click)
+        
+        #property editor
+        self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)
+        #results panel
+        self.panelResults.results_list.OnCheckItem = self.OnResultsCheck
+
+    def _on_about(self, *args):
+        dialog = wx.MessageDialog(
+            parent=self,
+            message=self.gui._splash_text(extra_info={
+                    'get-details':'click "Help -> License"'},
+                                          wrap=False),
+            caption='About Hooke',
+            style=wx.OK|wx.ICON_INFORMATION)
+        dialog.ShowModal()
+        dialog.Destroy()
+
+    def _on_close(self, *args):
+        self.log.info('closing GUI framework')
+        # apply changes
+        self.gui.config['main height'] = str(self.GetSize().GetHeight())
+        self.gui.config['main left'] = str(self.GetPosition()[0])
+        self.gui.config['main top'] = str(self.GetPosition()[1])
+        self.gui.config['main width'] = str(self.GetSize().GetWidth())
+        # push changes back to Hooke.config?
+        self._c['manager'].UnInit()
+        del self._c['manager']
+        self.Destroy()
+
+
+
+    # Panel utility functions
+
+    def _file_name(self, name):
+        """Cleanup names according to configured preferences.
+        """
+        if self.gui.config['hide extensions'] == True:
+            name,ext = os.path.splitext(name)
+        return name
+
+
+
+    # Command handling
+
+    def _command_by_name(self, name):
+        cs = [c for c in self.commands if c.name == name]
+        if len(cs) == 0:
+            raise KeyError(name)
+        elif len(cs) > 1:
+            raise Exception('Multiple commands named "%s"' % name)
+        return cs[0]
+
+    def execute_command(self, _class=None, method=None,
+                        command=None, args=None):
+        if args == None:
+            args = {}
+        if ('property editor' in self._c
+            and self.gui.config['selected command'] == command):
+            for name,value in self._c['property editor'].get_values().items():
+                arg = self._c['property editor']._argument_from_label.get(
+                    name, None)
+                if arg == None:
+                    continue
+                elif arg.count == 1:
+                    args[arg.name] = value
+                    continue
+                # deal with counted arguments
+                if arg.name not in args:
+                    args[arg.name] = {}
+                index = int(name[len(arg.name):])
+                args[arg.name][index] = value
+            for arg in command.arguments:
+                count = arg.count
+                if hasattr(arg, '_display_count'):  # support HACK in props_from_argument()
+                    count = arg._display_count
+                if count != 1 and arg.name in args:
+                    keys = sorted(args[arg.name].keys())
+                    assert keys == range(count), keys
+                    args[arg.name] = [args[arg.name][i]
+                                      for i in range(count)]
+                if arg.count == -1:
+                    while (len(args[arg.name]) > 0
+                           and args[arg.name][-1] == None):
+                        args[arg.name].pop()
+                    if len(args[arg.name]) == 0:
+                        args[arg.name] = arg.default
+        self.log.debug('executing %s with %s' % (command.name, args))
+        self.inqueue.put(CommandMessage(command, args))
+        results = []
+        while True:
+            msg = self.outqueue.get()
+            results.append(msg)
+            if isinstance(msg, Exit):
+                self._on_close()
+                break
+            elif isinstance(msg, CommandExit):
+                # TODO: display command complete
+                break
+            elif isinstance(msg, ReloadUserInterfaceConfig):
+                self.gui.reload_config(msg.config)
+                continue
+            elif isinstance(msg, Request):
+                h = handler.HANDLERS[msg.type]
+                h.run(self, msg)  # TODO: pause for response?
+                continue
+        pp = getattr(
+            self, '_postprocess_%s' % command.name.replace(' ', '_'),
+            self._postprocess_text)
+        pp(command=command, args=args, results=results)
+        return results
+
+    def _handle_request(self, msg):
+        """Repeatedly try to get a response to `msg`.
+        """
+        if prompt == None:
+            raise NotImplementedError('_%s_request_prompt' % msg.type)
+        prompt_string = prompt(msg)
+        parser = getattr(self, '_%s_request_parser' % msg.type, None)
+        if parser == None:
+            raise NotImplementedError('_%s_request_parser' % msg.type)
+        error = None
+        while True:
+            if error != None:
+                self.cmd.stdout.write(''.join([
+                        error.__class__.__name__, ': ', str(error), '\n']))
+            self.cmd.stdout.write(prompt_string)
+            value = parser(msg, self.cmd.stdin.readline())
+            try:
+                response = msg.response(value)
+                break
+            except ValueError, error:
+                continue
+        self.inqueue.put(response)
+
+
+
+    # Command-specific postprocessing
+
+    def _postprocess_text(self, command, args={}, results=[]):
+        """Print the string representation of the results to the Results window.
+
+        This is similar to :class:`~hooke.ui.commandline.DoCommand`'s
+        approach, except that :class:`~hooke.ui.commandline.DoCommand`
+        doesn't print some internally handled messages
+        (e.g. :class:`~hooke.interaction.ReloadUserInterfaceConfig`).
+        """
+        for result in results:
+            if isinstance(result, CommandExit):
+                self._c['output'].write(result.__class__.__name__+'\n')
+            self._c['output'].write(str(result).rstrip()+'\n')
+
+    def _postprocess_load_playlist(self, command, args={}, results=None):
+        """Update `self` to show the playlist.
+        """
+        if not isinstance(results[-1], Success):
+            self._postprocess_text(command, results=results)
+            return
+        assert len(results) == 2, results
+        playlist = results[0]
+        self._c['playlist']._c['tree'].add_playlist(playlist)
+
+    def _postprocess_get_playlist(self, command, args={}, results=[]):
+        if not isinstance(results[-1], Success):
+            self._postprocess_text(command, results=results)
+            return
+        assert len(results) == 2, results
+        playlist = results[0]
+        self._c['playlist']._c['tree'].update_playlist(playlist)
+
+    def _postprocess_get_curve(self, command, args={}, results=[]):
+        """Update `self` to show the curve.
+        """
+        if not isinstance(results[-1], Success):
+            self._postprocess_text(command, results=results)
+            return
+        assert len(results) == 2, results
+        curve = results[0]
+        if args.get('curve', None) == None:
+            # the command defaults to the current curve of the current playlist
+            results = self.execute_command(
+                command=self._command_by_name('get playlist'))
+            playlist = results[0]
+        else:
+            raise NotImplementedError()
+        if 'note' in self._c:
+            self._c['note'].set_text(curve.info['note'])
+        if 'playlist' in self._c:
+            self._c['playlist']._c['tree'].set_selected_curve(
+                playlist, curve)
+        if 'plot' in self._c:
+            self._c['plot'].set_curve(curve, config=self.gui.config)
+
+    def _postprocess_next_curve(self, command, args={}, results=[]):
+        """No-op.  Only call 'next curve' via `self._next_curve()`.
+        """
+        pass
+
+    def _postprocess_previous_curve(self, command, args={}, results=[]):
+        """No-op.  Only call 'previous curve' via `self._previous_curve()`.
+        """
+        pass
+
+    def _postprocess_zero_block_surface_contact_point(
+        self, command, args={}, results=[]):
+        """Update the curve, since the available columns may have changed.
+        """
+        if isinstance(results[-1], Success):
+            self.execute_command(
+                command=self._command_by_name('get curve'))
+    def _postprocess_add_block_force_array(
+        self, command, args={}, results=[]):
+        """Update the curve, since the available columns may have changed.
+        """
+        if isinstance(results[-1], Success):
+            self.execute_command(
+                command=self._command_by_name('get curve'))
+
+
+
+    # TODO: cruft
+
+    def _GetActiveFileIndex(self):
+        lib.playlist.Playlist = self.GetActivePlaylist()
+        #get the selected item from the tree
+        selected_item = self._c['playlist']._c['tree'].GetSelection()
+        #test if a playlist or a curve was double-clicked
+        if self._c['playlist']._c['tree'].ItemHasChildren(selected_item):
+            return -1
+        else:
+            count = 0
+            selected_item = self._c['playlist']._c['tree'].GetPrevSibling(selected_item)
+            while selected_item.IsOk():
+                count += 1
+                selected_item = self._c['playlist']._c['tree'].GetPrevSibling(selected_item)
+            return count
+
+    def _GetPlaylistTab(self, name):
+        for index, page in enumerate(self._c['notebook']._tabs._pages):
+            if page.caption == name:
+                return index
+        return -1
+
+    def select_plugin(self, _class=None, method=None, plugin=None):
+        pass
+
+    def AddPlaylistFromFiles(self, files=[], name='Untitled'):
+        if files:
+            playlist = lib.playlist.Playlist(self, self.drivers)
+            for item in files:
+                playlist.add_curve(item)
+        if playlist.count > 0:
+            playlist.name = self._GetUniquePlaylistName(name)
+            playlist.reset()
+            self.AddTayliss(playlist)
+
+    def AppliesPlotmanipulator(self, name):
+        '''
+        Returns True if the plotmanipulator 'name' is applied, False otherwise
+        name does not contain 'plotmanip_', just the name of the plotmanipulator (e.g. 'flatten')
+        '''
+        return self.GetBoolFromConfig('core', 'plotmanipulators', name)
+
+    def ApplyPlotmanipulators(self, plot, plot_file):
+        '''
+        Apply all active plotmanipulators.
+        '''
+        if plot is not None and plot_file is not None:
+            manipulated_plot = copy.deepcopy(plot)
+            for plotmanipulator in self.plotmanipulators:
+                if self.GetBoolFromConfig('core', 'plotmanipulators', plotmanipulator.name):
+                    manipulated_plot = plotmanipulator.method(manipulated_plot, plot_file)
+            return manipulated_plot
+
+    def GetActiveFigure(self):
+        playlist_name = self.GetActivePlaylistName()
+        figure = self.playlists[playlist_name].figure
+        if figure is not None:
+            return figure
+        return None
+
+    def GetActiveFile(self):
+        playlist = self.GetActivePlaylist()
+        if playlist is not None:
+            return playlist.get_active_file()
+        return None
+
+    def GetActivePlot(self):
+        playlist = self.GetActivePlaylist()
+        if playlist is not None:
+            return playlist.get_active_file().plot
+        return None
+
+    def GetDisplayedPlot(self):
+        plot = copy.deepcopy(self.displayed_plot)
+        #plot.curves = []
+        #plot.curves = copy.deepcopy(plot.curves)
+        return plot
+
+    def GetDisplayedPlotCorrected(self):
+        plot = copy.deepcopy(self.displayed_plot)
+        plot.curves = []
+        plot.curves = copy.deepcopy(plot.corrected_curves)
+        return plot
+
+    def GetDisplayedPlotRaw(self):
+        plot = copy.deepcopy(self.displayed_plot)
+        plot.curves = []
+        plot.curves = copy.deepcopy(plot.raw_curves)
+        return plot
+
+    def GetDockArt(self):
+        return self._c['manager'].GetArtProvider()
+
+    def GetPlotmanipulator(self, name):
+        '''
+        Returns a plot manipulator function from its name
+        '''
+        for plotmanipulator in self.plotmanipulators:
+            if plotmanipulator.name == name:
+                return plotmanipulator
+        return None
+
+    def HasPlotmanipulator(self, name):
+        '''
+        returns True if the plotmanipulator 'name' is loaded, False otherwise
+        '''
+        for plotmanipulator in self.plotmanipulators:
+            if plotmanipulator.command == name:
+                return True
+        return False
+
+
+    def _on_dir_ctrl_left_double_click(self, event):
+        file_path = self.panelFolders.GetPath()
+        if os.path.isfile(file_path):
+            if file_path.endswith('.hkp'):
+                self.do_loadlist(file_path)
+        event.Skip()
+
+    def _on_erase_background(self, event):
+        event.Skip()
+
+    def _on_notebook_page_close(self, event):
+        ctrl = event.GetEventObject()
+        playlist_name = ctrl.GetPageText(ctrl._curpage)
+        self.DeleteFromPlaylists(playlist_name)
+
+    def OnPaneClose(self, event):
+        event.Skip()
+
+    def OnPropGridChanged (self, event):
+        prop = event.GetProperty()
+        if prop:
+            item_section = self.panelProperties.SelectedTreeItem
+            item_plugin = self._c['commands']._c['tree'].GetItemParent(item_section)
+            plugin = self._c['commands']._c['tree'].GetItemText(item_plugin)
+            config = self.gui.config[plugin]
+            property_section = self._c['commands']._c['tree'].GetItemText(item_section)
+            property_key = prop.GetName()
+            property_value = prop.GetDisplayedString()
+
+            config[property_section][property_key]['value'] = property_value
+
+    def OnResultsCheck(self, index, flag):
+        results = self.GetActivePlot().results
+        if results.has_key(self.results_str):
+            results[self.results_str].results[index].visible = flag
+            results[self.results_str].update()
+            self.UpdatePlot()
+
+
+    def _on_size(self, event):
+        event.Skip()
+
+    def UpdatePlaylistsTreeSelection(self):
+        playlist = self.GetActivePlaylist()
+        if playlist is not None:
+            if playlist.index >= 0:
+                self._c['status bar'].set_playlist(playlist)
+                self.UpdateNote()
+                self.UpdatePlot()
+
+    def _on_curve_select(self, playlist, curve):
+        #create the plot tab and add playlist to the dictionary
+        plotPanel = panel.plot.PlotPanel(self, ID_FirstPlot + len(self.playlists))
+        notebook_tab = self._c['notebook'].AddPage(plotPanel, playlist.name, True)
+        #tab_index = self._c['notebook'].GetSelection()
+        playlist.figure = plotPanel.get_figure()
+        self.playlists[playlist.name] = playlist
+        #self.playlists[playlist.name] = [playlist, figure]
+        self._c['status bar'].set_playlist(playlist)
+        self.UpdateNote()
+        self.UpdatePlot()
+
+
+    def _on_playlist_left_doubleclick(self):
+        index = self._c['notebook'].GetSelection()
+        current_playlist = self._c['notebook'].GetPageText(index)
+        if current_playlist != playlist_name:
+            index = self._GetPlaylistTab(playlist_name)
+            self._c['notebook'].SetSelection(index)
+        self._c['status bar'].set_playlist(playlist)
+        self.UpdateNote()
+        self.UpdatePlot()
+
+    def _on_playlist_delete(self, playlist):
+        notebook = self.Parent.plotNotebook
+        index = self.Parent._GetPlaylistTab(playlist.name)
+        notebook.SetSelection(index)
+        notebook.DeletePage(notebook.GetSelection())
+        self.Parent.DeleteFromPlaylists(playlist_name)
+
+
+
+    # Command panel interface
+
+    def select_command(self, _class, method, command):
+        #self.select_plugin(plugin=command.plugin)
+        self._c['property editor'].clear()
+        self._c['property editor']._argument_from_label = {}
+        for argument in command.arguments:
+            if argument.name == 'help':
+                continue
+
+            results = self.execute_command(
+                command=self._command_by_name('playlists'))
+            if not isinstance(results[-1], Success):
+                self._postprocess_text(command, results=results)
+                playlists = []
+            else:
+                playlists = results[0]
+
+            results = self.execute_command(
+                command=self._command_by_name('playlist curves'))
+            if not isinstance(results[-1], Success):
+                self._postprocess_text(command, results=results)
+                curves = []
+            else:
+                curves = results[0]
+
+            ret = props_from_argument(
+                argument, curves=curves, playlists=playlists)
+            if ret == None:
+                continue  # property intentionally not handled (yet)
+            for label,p in ret:
+                self._c['property editor'].append_property(p)
+                self._c['property editor']._argument_from_label[label] = (
+                    argument)
+
+        self.gui.config['selected command'] = command  # TODO: push to engine
+
+
+
+    # Note panel interface
+
+    def _on_update_note(self, _class, method, text):
+        """Sets the note for the active curve.
+        """
+        self.execute_command(
+            command=self._command_by_name('set note'),
+            args={'note':text})
+
+
+
+    # Playlist panel interface
+
+    def _on_user_delete_playlist(self, _class, method, playlist):
+        pass
+
+    def _on_delete_playlist(self, _class, method, playlist):
+        if hasattr(playlist, 'path') and playlist.path != None:
+            os.remove(playlist.path)
+
+    def _on_user_delete_curve(self, _class, method, playlist, curve):
+        pass
+
+    def _on_delete_curve(self, _class, method, playlist, curve):
+        # TODO: execute_command 'remove curve from playlist'
+        os.remove(curve.path)
+
+    def _on_set_selected_playlist(self, _class, method, playlist):
+        """Call the `jump to playlist` command.
+        """
+        results = self.execute_command(
+            command=self._command_by_name('playlists'))
+        if not isinstance(results[-1], Success):
+            return
+        assert len(results) == 2, results
+        playlists = results[0]
+        matching = [p for p in playlists if p.name == playlist.name]
+        assert len(matching) == 1, matching
+        index = playlists.index(matching[0])
+        results = self.execute_command(
+            command=self._command_by_name('jump to playlist'),
+            args={'index':index})
+
+    def _on_set_selected_curve(self, _class, method, playlist, curve):
+        """Call the `jump to curve` command.
+        """
+        self._on_set_selected_playlist(_class, method, playlist)
+        index = playlist.index(curve)
+        results = self.execute_command(
+            command=self._command_by_name('jump to curve'),
+            args={'index':index})
+        if not isinstance(results[-1], Success):
+            return
+        #results = self.execute_command(
+        #    command=self._command_by_name('get playlist'))
+        #if not isinstance(results[-1], Success):
+        #    return
+        self.execute_command(
+            command=self._command_by_name('get curve'))
+
+
+
+    # Plot panel interface
+
+    def _on_plot_status_text(self, _class, method, text):
+        if 'status bar' in self._c:
+            self._c['status bar'].set_plot_text(text)
+
+
+
+    # Navbar interface
+
+    def _next_curve(self, *args):
+        """Call the `next curve` command.
+        """
+        results = self.execute_command(
+            command=self._command_by_name('next curve'))
+        if isinstance(results[-1], Success):
+            self.execute_command(
+                command=self._command_by_name('get curve'))
+
+    def _previous_curve(self, *args):
+        """Call the `previous curve` command.
+        """
+        results = self.execute_command(
+            command=self._command_by_name('previous curve'))
+        if isinstance(results[-1], Success):
+            self.execute_command(
+                command=self._command_by_name('get curve'))
+
+
+
+    # Panel display handling
+
+    def _on_panel_visibility(self, _class, method, panel_name, visible):
+        pane = self._c['manager'].GetPane(panel_name)
+        pane.Show(visible)
+        #if we don't do the following, the Folders pane does not resize properly on hide/show
+        if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():
+            #folders_size = pane.GetSize()
+            self.panelFolders.Fit()
+        self._c['manager'].Update()
+
+    def _setup_perspectives(self):
+        """Add perspectives to menubar and _perspectives.
+        """
+        self._perspectives = {
+            'Default': self._c['manager'].SavePerspective(),
+            }
+        path = self.gui.config['perspective path']
+        if os.path.isdir(path):
+            files = sorted(os.listdir(path))
+            for fname in files:
+                name, extension = os.path.splitext(fname)
+                if extension != self.gui.config['perspective extension']:
+                    continue
+                fpath = os.path.join(path, fname)
+                if not os.path.isfile(fpath):
+                    continue
+                perspective = None
+                with open(fpath, 'rU') as f:
+                    perspective = f.readline()
+                if perspective:
+                    self._perspectives[name] = perspective
+
+        selected_perspective = self.gui.config['active perspective']
+        if not self._perspectives.has_key(selected_perspective):
+            self.gui.config['active perspective'] = 'Default'  # TODO: push to engine's Hooke
+
+        self._restore_perspective(selected_perspective, force=True)
+        self._update_perspective_menu()
+
+    def _update_perspective_menu(self):
+        self._c['menu bar']._c['perspective'].update(
+            sorted(self._perspectives.keys()),
+            self.gui.config['active perspective'])
+
+    def _save_perspective(self, perspective, perspective_dir, name,
+                          extension=None):
+        path = os.path.join(perspective_dir, name)
+        if extension != None:
+            path += extension
+        if not os.path.isdir(perspective_dir):
+            os.makedirs(perspective_dir)
+        with open(path, 'w') as f:
+            f.write(perspective)
+        self._perspectives[name] = perspective
+        self._restore_perspective(name)
+        self._update_perspective_menu()
+
+    def _delete_perspectives(self, perspective_dir, names,
+                             extension=None):
+        self.log.debug('remove perspectives %s from %s'
+                       % (names, perspective_dir))
+        for name in names:
+            path = os.path.join(perspective_dir, name)
+            if extension != None:
+                path += extension
+            os.remove(path)
+            del(self._perspectives[name])
+        self._update_perspective_menu()
+        if self.gui.config['active perspective'] in names:
+            self._restore_perspective('Default')
+        # TODO: does this bug still apply?
+        # Unfortunately, there is a bug in wxWidgets for win32 (Ticket #3258
+        #   http://trac.wxwidgets.org/ticket/3258 
+        # ) that makes the radio item indicator in the menu disappear.
+        # The code should be fine once this issue is fixed.
+
+    def _restore_perspective(self, name, force=False):
+        if name != self.gui.config['active perspective'] or force == True:
+            self.log.debug('restore perspective %s' % name)
+            self.gui.config['active perspective'] = name  # TODO: push to engine's Hooke
+            self._c['manager'].LoadPerspective(self._perspectives[name])
+            self._c['manager'].Update()
+            for pane in self._c['manager'].GetAllPanes():
+                view = self._c['menu bar']._c['view']
+                if pane.name in view._c.keys():
+                    view._c[pane.name].Check(pane.window.IsShown())
+
+    def _on_save_perspective(self, *args):
+        perspective = self._c['manager'].SavePerspective()
+        name = self.gui.config['active perspective']
+        if name == 'Default':
+            name = 'New perspective'
+        name = select_save_file(
+            directory=self.gui.config['perspective path'],
+            name=name,
+            extension=self.gui.config['perspective extension'],
+            parent=self,
+            message='Enter a name for the new perspective:',
+            caption='Save perspective')
+        if name == None:
+            return
+        self._save_perspective(
+            perspective, self.gui.config['perspective path'], name=name,
+            extension=self.gui.config['perspective extension'])
+
+    def _on_delete_perspective(self, *args, **kwargs):
+        options = sorted([p for p in self._perspectives.keys()
+                          if p != 'Default'])
+        dialog = SelectionDialog(
+            options=options,
+            message="\nPlease check the perspectives\n\nyou want to delete and click 'Delete'.\n",
+            button_id=wx.ID_DELETE,
+            selection_style='multiple',
+            parent=self,
+            title='Delete perspective(s)',
+            style=wx.DEFAULT_DIALOG_STYLE | wx.RESIZE_BORDER)
+        dialog.CenterOnScreen()
+        dialog.ShowModal()
+        if dialog.canceled == True:
+            return
+        names = [options[i] for i in dialog.selected]
+        dialog.Destroy()
+        self._delete_perspectives(
+            self.gui.config['perspective path'], names=names,
+            extension=self.gui.config['perspective extension'])
+
+    def _on_select_perspective(self, _class, method, name):
+        self._restore_perspective(name)
+
+
+
+class HookeApp (wx.App):
+    """A :class:`wx.App` wrapper around :class:`HookeFrame`.
+
+    Tosses up a splash screen and then loads :class:`HookeFrame` in
+    its own window.
+    """
+    def __init__(self, gui, commands, inqueue, outqueue, *args, **kwargs):
+        self.gui = gui
+        self.commands = commands
+        self.inqueue = inqueue
+        self.outqueue = outqueue
+        super(HookeApp, self).__init__(*args, **kwargs)
+
+    def OnInit(self):
+        self.SetAppName('Hooke')
+        self.SetVendorName('')
+        self._setup_splash_screen()
+
+        height = self.gui.config['main height']
+        width = self.gui.config['main width']
+        top = self.gui.config['main top']
+        left = self.gui.config['main left']
+
+        # Sometimes, the ini file gets confused and sets 'left' and
+        # 'top' to large negative numbers.  Here we catch and fix
+        # this.  Keep small negative numbers, the user might want
+        # those.
+        if left < -width:
+            left = 0
+        if top < -height:
+            top = 0
+
+        self._c = {
+            'frame': HookeFrame(
+                self.gui, self.commands, self.inqueue, self.outqueue,
+                parent=None, title='Hooke',
+                pos=(left, top), size=(width, height),
+                style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN),
+            }
+        self._c['frame'].Show(True)
+        self.SetTopWindow(self._c['frame'])
+        return True
+
+    def _setup_splash_screen(self):
+        if self.gui.config['show splash screen'] == True:
+            path = self.gui.config['splash screen image']
+            if os.path.isfile(path):
+                duration = self.gui.config['splash screen duration']
+                wx.SplashScreen(
+                    bitmap=wx.Image(path).ConvertToBitmap(),
+                    splashStyle=wx.SPLASH_CENTRE_ON_SCREEN|wx.SPLASH_TIMEOUT,
+                    milliseconds=duration,
+                    parent=None)
+                wx.Yield()
+                # For some reason splashDuration and sleep do not
+                # correspond to each other at least not on Windows.
+                # Maybe it's because duration is in milliseconds and
+                # sleep in seconds.  Thus we need to increase the
+                # sleep time a bit. A factor of 1.2 seems to work.
+                sleepFactor = 1.2
+                time.sleep(sleepFactor * duration / 1000)
+
+
+class GUI (UserInterface):
+    """wxWindows graphical user interface.
+    """
+    def __init__(self):
+        super(GUI, self).__init__(name='gui')
+
+    def default_settings(self):
+        """Return a list of :class:`hooke.config.Setting`\s for any
+        configurable UI settings.
+
+        The suggested section setting is::
+
+            Setting(section=self.setting_section, help=self.__doc__)
+        """
+        return [
+            Setting(section=self.setting_section, help=self.__doc__),
+            Setting(section=self.setting_section, option='icon image',
+                    value=os.path.join('doc', 'img', 'microscope.ico'),
+                    type='file',
+                    help='Path to the hooke icon image.'),
+            Setting(section=self.setting_section, option='show splash screen',
+                    value=True, type='bool',
+                    help='Enable/disable the splash screen'),
+            Setting(section=self.setting_section, option='splash screen image',
+                    value=os.path.join('doc', 'img', 'hooke.jpg'),
+                    type='file',
+                    help='Path to the Hooke splash screen image.'),
+            Setting(section=self.setting_section,
+                    option='splash screen duration',
+                    value=1000, type='int',
+                    help='Duration of the splash screen in milliseconds.'),
+            Setting(section=self.setting_section, option='perspective path',
+                    value=os.path.join('resources', 'gui', 'perspective'),
+                    help='Directory containing perspective files.'), # TODO: allow colon separated list, like $PATH.
+            Setting(section=self.setting_section, option='perspective extension',
+                    value='.txt',
+                    help='Extension for perspective files.'),
+            Setting(section=self.setting_section, option='hide extensions',
+                    value=False, type='bool',
+                    help='Hide file extensions when displaying names.'),
+            Setting(section=self.setting_section, option='plot legend',
+                    value=True, type='bool',
+                    help='Enable/disable the plot legend.'),
+            Setting(section=self.setting_section, option='plot SI format',
+                    value='True', type='bool',
+                    help='Enable/disable SI plot axes numbering.'),
+            Setting(section=self.setting_section, option='plot decimals',
+                    value=2, type='int',
+                    help='Number of decimal places to show if "plot SI format" is enabled.'),
+            Setting(section=self.setting_section, option='folders-workdir',
+                    value='.', type='path',
+                    help='This should probably go...'),
+            Setting(section=self.setting_section, option='folders-filters',
+                    value='.', type='path',
+                    help='This should probably go...'),
+            Setting(section=self.setting_section, option='active perspective',
+                    value='Default',
+                    help='Name of active perspective file (or "Default").'),
+            Setting(section=self.setting_section,
+                    option='folders-filter-index',
+                    value=0, type='int',
+                    help='This should probably go...'),
+            Setting(section=self.setting_section, option='main height',
+                    value=450, type='int',
+                    help='Height of main window in pixels.'),
+            Setting(section=self.setting_section, option='main width',
+                    value=800, type='int',
+                    help='Width of main window in pixels.'),
+            Setting(section=self.setting_section, option='main top',
+                    value=0, type='int',
+                    help='Pixels from screen top to top of main window.'),
+            Setting(section=self.setting_section, option='main left',
+                    value=0, type='int',
+                    help='Pixels from screen left to left of main window.'),
+            Setting(section=self.setting_section, option='selected command',
+                    value='load playlist',
+                    help='Name of the initially selected command.'),
+            ]
+
+    def _app(self, commands, ui_to_command_queue, command_to_ui_queue):
+        redirect = True
+        if __debug__:
+            redirect=False
+        app = HookeApp(gui=self,
+                       commands=commands,
+                       inqueue=ui_to_command_queue,
+                       outqueue=command_to_ui_queue,
+                       redirect=redirect)
+        return app
+
+    def run(self, commands, ui_to_command_queue, command_to_ui_queue):
+        app = self._app(commands, ui_to_command_queue, command_to_ui_queue)
+        app.MainLoop()