Added inclusion logic to hooke.plugin
[hooke.git] / hooke / hooke.py
1 #!/usr/bin/env python
2
3 '''
4 Hooke - A force spectroscopy review & analysis tool.
5
6 COPYRIGHT
7 '''
8
9 import Queue as queue
10 import multiprocessing
11
12 from . import config as config_mod
13 from . import plugin as plugin_mod
14 from . import driver as driver_mod
15
16 import copy
17 import cStringIO
18 import os
19 import os.path
20 import sys
21 import glob
22 import time
23
24 #import libhooke as lh
25 #import drivers
26 #import plugins
27 #import hookecommands
28 #import hookeplaylist
29 #import hookepropertyeditor
30 #import hookeresults
31 #import playlist
32
33 class Hooke(object):
34     def __init__(self, config=None, debug=0):
35         self.debug = debug
36         config_mod.DEFAULTS.extend(plugin_mod.default_settings())
37         config_mod.DEFAULTS.extend(driver_mod.default_settings())
38         if config == None:
39             config = config_mod.HookeConfigParser(
40                 paths=config_mod.DEFAULT_PATHS,
41                 default_settings=config_mod.DEFAULT_SETTINGS)
42             config.read_configs()
43         self.config = config
44         self.load_plugins()
45         self.load_drivers()
46
47     def driver_default_settings(self):
48         settings = []
49         for driver in driver_mod.drivers:
50             settings.extend(driver_mod.default_settings(driver))
51         return settings
52
53     def load_plugins(self):
54         for plugin,value in self.config[plugins].items():
55         
56     def load_drivers(self)
57         pass
58
59     def close(self):
60         if self.config.changed:
61             self.config.write() # Does not preserve original comments
62
63 class HookeFrame(wx.Frame):
64
65     def __init__(self, parent, id=-1, title='', pos=wx.DefaultPosition, size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE|wx.SUNKEN_BORDER|wx.CLIP_CHILDREN):
66         #call parent constructor
67         wx.Frame.__init__(self, parent, id, title, pos, size, style)
68         self.config = config
69         self.CreateApplicationIcon()
70         #self.configs contains: {the name of the Commands file: corresponding ConfigObj}
71         self.configs = {}
72         ##self.playlists contains: {the name of the playlist: [playlist, tabIndex, plotID]}
73         #self.playlists = {}
74         #self.plugins contains: {the name of the plugin: [caption, function]}
75         self.plugins = {}
76         #self.plotmanipulators list contains: [the name of the plotmanip, function, name of the module]
77         self.plotmanipulators = []
78
79         #tell FrameManager to manage this frame
80         self._mgr = aui.AuiManager()
81         self._mgr.SetManagedWindow(self)
82         #set the gradient style
83         self._mgr.GetArtProvider().SetMetric(aui.AUI_DOCKART_GRADIENT_TYPE, aui.AUI_GRADIENT_NONE)
84         #set transparent drag
85         self._mgr.SetFlags(self._mgr.GetFlags() ^ aui.AUI_MGR_TRANSPARENT_DRAG)
86
87         # set up default notebook style
88         self._notebook_style = aui.AUI_NB_DEFAULT_STYLE | aui.AUI_NB_TAB_EXTERNAL_MOVE | wx.NO_BORDER
89         self._notebook_theme = 0
90
91         #holds the perspectives: {name, [index, perspectiveStr]}
92         self._perspectives = {}
93
94         # min size for the frame itself isn't completely done.
95         # see the end up FrameManager::Update() for the test
96         # code. For now, just hard code a frame minimum size
97         self.SetMinSize(wx.Size(400, 300))
98         #create panels here
99         self.panelAssistant = self.CreatePanelAssistant()
100         self.panelCommands = self.CreatePanelCommands()
101         self.panelFolders = self.CreatePanelFolders()
102         self.panelPlaylists = self.CreatePanelPlaylists()
103         self.panelProperties = self.CreatePanelProperties()
104         self.panelOutput = self.CreatePanelOutput()
105         self.panelResults = self.CreatePanelResults()
106         self.plotNotebook = self.CreateNotebook()
107         #self.textCtrlCommandLine=self.CreateCommandLine()
108
109         # add panes
110         self._mgr.AddPane(self.panelFolders, aui.AuiPaneInfo().Name('Folders').Caption('Folders').Left().CloseButton(True).MaximizeButton(False))
111         self._mgr.AddPane(self.panelPlaylists, aui.AuiPaneInfo().Name('Playlists').Caption('Playlists').Left().CloseButton(True).MaximizeButton(False))
112         self._mgr.AddPane(self.plotNotebook, aui.AuiPaneInfo().Name('Plots').CenterPane().PaneBorder(False))
113         self._mgr.AddPane(self.panelCommands, aui.AuiPaneInfo().Name('Commands').Caption('Settings and commands').Right().CloseButton(True).MaximizeButton(False))
114         self._mgr.AddPane(self.panelProperties, aui.AuiPaneInfo().Name('Properties').Caption('Properties').Right().CloseButton(True).MaximizeButton(False))
115         self._mgr.AddPane(self.panelAssistant, aui.AuiPaneInfo().Name('Assistant').Caption('Assistant').Right().CloseButton(True).MaximizeButton(False))
116         self._mgr.AddPane(self.panelOutput, aui.AuiPaneInfo().Name('Output').Caption('Output').Bottom().CloseButton(True).MaximizeButton(False))
117         self._mgr.AddPane(self.panelResults, aui.AuiPaneInfo().Name('Results').Caption('Results').Bottom().CloseButton(True).MaximizeButton(False))
118         #self._mgr.AddPane(self.textCtrlCommandLine, aui.AuiPaneInfo().Name('CommandLine').CaptionVisible(False).Fixed().Bottom().Layer(2).CloseButton(False).MaximizeButton(False))
119         #self._mgr.AddPane(panelBottom, aui.AuiPaneInfo().Name("panelCommandLine").Bottom().Position(1).CloseButton(False).MaximizeButton(False))
120
121         # add the toolbars to the manager
122         self.toolbar=self.CreateToolBar()
123         self.toolbarNavigation=self.CreateToolBarNavigation()
124         self._mgr.AddPane(self.toolbar, aui.AuiPaneInfo().Name('toolbar').Caption('Toolbar').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
125         self._mgr.AddPane(self.toolbarNavigation, aui.AuiPaneInfo().Name('toolbarNavigation').Caption('Navigation').ToolbarPane().Top().Layer(1).Row(1).LeftDockable(False).RightDockable(False))
126         # "commit" all changes made to FrameManager
127         self._mgr.Update()
128         #create the menubar after the panes so that the default perspective
129         #is created with all panes open
130         self.CreateMenuBar()
131         self.statusbar = self.CreateStatusBar()
132         self._BindEvents()
133         #TODO: select item on startup (whatever item)
134         #self.listCtrlCommands.Select(0)
135         #self.OnListboxSelect(None)
136         name = self.config['perspectives']['active']
137         menu_item = self.GetPerspectiveMenuItem(name)
138         self.OnRestorePerspective(menu_item)
139         self.playlists = self.panelPlaylists.Playlists
140         #define the list of active drivers
141         self.drivers = []
142         for driver in self.config['drivers']:
143             if self.config['drivers'][driver]:
144                 #get the corresponding filename and path
145                 filename = ''.join([driver, '.py'])
146                 path = lh.get_file_path(filename, ['drivers'])
147                 #the driver is active for driver[1] == 1
148                 if os.path.isfile(path):
149                     #driver files are located in the 'drivers' subfolder
150                     driver_name = ''.join(['drivers.', driver])
151                     module = __import__(driver_name)
152                     class_file = getattr(drivers, driver)
153                     for command in dir(class_file):
154                         if command.endswith('Driver'):
155                             self.drivers.append(getattr(class_file, command))
156         #import all active plugins and plotmanips
157         #the plotmanip_functions contains: {the name of the plotmanip: [method, class_object]}
158         plotmanip_functions = {}
159         #add 'general.ini' to self.configs (this is not a plugin and thus must be imported seperately)
160         ini_path = lh.get_file_path('general.ini', ['plugins'])
161         plugin_config = ConfigObj(ini_path)
162         #self.config.merge(plugin_config)
163         self.configs['general'] = plugin_config
164         #make sure we execute _plug_init() for every command line plugin we import
165         for plugin in self.config['plugins']:
166             if self.config['plugins'][plugin]:
167                 filename = ''.join([plugin, '.py'])
168                 path = lh.get_file_path(filename, ['plugins'])
169                 if os.path.isfile(path):
170                     #get the corresponding filename and path
171                     plugin_name = ''.join(['plugins.', plugin])
172                     try:
173                         #import the module
174                         module = __import__(plugin_name)
175                         #prepare the ini file for inclusion
176                         ini_path = path.replace('.py', '.ini')
177                         #include ini file
178                         plugin_config = ConfigObj(ini_path)
179                         #self.config.merge(plugin_config)
180                         self.configs[plugin] = plugin_config
181                         #add to plugins
182                         commands = eval('dir(module.' + plugin+ '.' + plugin + 'Commands)')
183                         #keep only commands (ie names that start with 'do_')
184                         commands = [command for command in commands if command.startswith('do_')]
185                         if commands:
186                             self.plugins[plugin] = commands
187                         try:
188                             #initialize the plugin
189                             eval('module.' + plugin+ '.' + plugin + 'Commands._plug_init(self)')
190                         except AttributeError:
191                             pass
192                     except ImportError:
193                         pass
194         #initialize the commands tree
195         commands = dir(HookeFrame)
196         commands = [command for command in commands if command.startswith('do_')]
197         if commands:
198             self.plugins['general'] = commands
199         self.panelCommands.Initialize(self.plugins)
200         for command in dir(self):
201             if command.startswith('plotmanip_'):
202                 plotmanip_functions[command] = [command, getattr(self, command)]
203         for name in self.config['plotmanipulators']['names']:
204             if self.config['plotmanipulators'].as_bool(name):
205                 command_name = ''.join(['plotmanip_', name])
206                 if command_name in plotmanip_functions:
207                     self.plotmanipulators.append(plotmanip_functions[command_name])
208         #load default list, if possible
209         self.do_loadlist(self.config['general']['list'])
210
211     def _BindEvents(self):
212         self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
213         self.Bind(wx.EVT_SIZE, self.OnSize)
214         self.Bind(wx.EVT_CLOSE, self.OnClose)
215         # Show How To Use The Closing Panes Event
216         self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
217         self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnNotebookPageClose)
218         #menu
219         self.Bind(wx.EVT_MENU, self.OnClose, id=wx.ID_EXIT)
220         self.Bind(wx.EVT_MENU, self.OnAbout, id=wx.ID_ABOUT)
221         #view
222         self.Bind(wx.EVT_MENU_RANGE, self.OnView, id=ID_ViewAssistant, id2=ID_ViewResults)
223         #perspectives
224         self.Bind(wx.EVT_MENU, self.OnDeletePerspective, id=ID_DeletePerspective)
225         self.Bind(wx.EVT_MENU, self.OnSavePerspective, id=ID_SavePerspective)
226         self.Bind(wx.EVT_MENU_RANGE, self.OnRestorePerspective, id=ID_FirstPerspective, id2=ID_FirstPerspective+1000)
227         #toolbar
228         self.Bind(wx.EVT_TOOL, self.OnExportImage, id=ID_ExportImage)
229         self.Bind(wx.EVT_TOOL, self.OnNext, id=ID_Next)
230         self.Bind(wx.EVT_TOOL, self.OnPrevious, id=ID_Previous)
231         #self.Bind(.EVT_AUITOOLBAR_TOOL_DROPDOWN, self.OnDropDownToolbarItem, id=ID_DropDownToolbarItem)
232         #dir control
233         treeCtrl = self.panelFolders.GetTreeCtrl()
234         #tree.Bind(wx.EVT_LEFT_UP, self.OnDirCtrl1LeftUp)
235         #tree.Bind(wx.EVT_LEFT_DOWN, self.OnGenericDirCtrl1LeftDown)
236         treeCtrl.Bind(wx.EVT_LEFT_DCLICK, self.OnDirCtrlLeftDclick)
237         #playlist tree
238         self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DOWN, self.OnPlaylistsLeftDown)
239         self.panelPlaylists.PlaylistsTree.Bind(wx.EVT_LEFT_DCLICK, self.OnPlaylistsLeftDclick)
240         #commands tree
241         self.panelCommands.ExecuteButton.Bind(wx.EVT_BUTTON, self.OnExecute)
242         self.panelCommands.CommandsTree.Bind(wx.EVT_LEFT_DOWN, self.OnTreeCtrlCommandsLeftDown)
243         #property editor
244         self.panelProperties.pg.Bind(wxpg.EVT_PG_CHANGED, self.OnPropGridChanged)
245         self.panelProperties.pg.Bind(wxpg.EVT_PG_SELECTED, self.OnPropGridSelect)
246         #results panel
247         self.panelResults.results_list.OnCheckItem = self.OnResultsCheck
248
249     def _GetActiveCurveIndex(self):
250         playlist = self.GetActivePlaylist()
251         #get the selected item from the tree
252         selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
253         #test if a playlist or a curve was double-clicked
254         if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
255             return -1
256         else:
257             count = 0
258             selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
259             while selected_item.IsOk():
260                 count += 1
261                 selected_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
262             return count
263
264     def _GetActivePlaylistName(self):
265         #get the selected item from the tree
266         selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
267         #test if a playlist or a curve was double-clicked
268         if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
269             playlist_item = selected_item
270         else:
271             #get the name of the playlist
272             playlist_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
273         #now we have a playlist
274         return self.panelPlaylists.PlaylistsTree.GetItemText(playlist_item)
275
276     def _GetPlaylistTab(self, name):
277         for index, page in enumerate(self.plotNotebook._tabs._pages):
278             if page.caption == name:
279                 return index
280         return -1
281
282     def _GetUniquePlaylistName(self, name):
283         playlist_name = name
284         count = 1
285         while playlist_name in self.playlists:
286             playlist_name = ''.join([name, str(count)])
287             count += 1
288         return playlist_name
289
290     def _SavePerspectiveToFile(self, name, perspective):
291         filename = ''.join([name, '.txt'])
292         filename = lh.get_file_path(filename, ['perspectives'])
293         perspectivesFile = open(filename, 'w')
294         perspectivesFile.write(perspective)
295         perspectivesFile.close()
296
297     def AddPlaylist(self, playlist=None, name='Untitled'):
298         #TODO: change cursor or progressbar (maybe in statusbar)
299         #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
300         if playlist and playlist.count > 0:
301             playlist.name = self._GetUniquePlaylistName(name)
302             playlist.reset()
303             self.AddToPlaylists(playlist)
304
305     def AddPlaylistFromFiles(self, files=[], name='Untitled'):
306         #TODO: change cursor or progressbar (maybe in statusbar)
307         #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
308         if files:
309             playlist = Playlist.Playlist(self.drivers)
310             for item in files:
311                 playlist.add_curve(item)
312         if playlist.count > 0:
313             playlist.name = self._GetUniquePlaylistName(name)
314             playlist.reset()
315             self.AddToPlaylists(playlist)
316
317     def AddToPlaylists(self, playlist):
318         if playlist.has_curves:
319             #setup the playlist in the Playlist tree
320             tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
321             playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
322             #add all curves to the Playlist tree
323             curves = {}
324             for index, curve in enumerate(playlist.curves):
325                 ##remove the extension from the name of the curve
326                 ##TODO: optional?
327                 #item_text, extension = os.path.splitext(curve.name)
328                 #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
329                 curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
330                 if index == playlist.index:
331                     self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
332             playlist.reset()
333             #create the plot tab and add playlist to the dictionary
334             plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
335             notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
336             tab_index = self.plotNotebook.GetSelection()
337             figure = plotPanel.get_figure()
338             self.playlists[playlist.name] = [playlist, figure]
339             self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
340             self.statusbar.SetStatusText(playlist.get_status_string(), 0)
341             self.UpdatePlot()
342
343     def AppendToOutput(self, text):
344         self.panelOutput.AppendText(''.join([text, '\n']))
345
346     def CreateApplicationIcon(self):
347         iconFile = 'resources' + os.sep + 'microscope.ico'
348         icon = wx.Icon(iconFile, wx.BITMAP_TYPE_ICO)
349         self.SetIcon(icon)
350
351     def CreateCommandLine(self):
352         return wx.TextCtrl(self, -1, '', style=wx.NO_BORDER|wx.EXPAND)
353
354     def CreatePanelAssistant(self):
355         panel = wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
356         panel.SetEditable(False)
357         return panel
358
359     def CreatePanelCommands(self):
360         return hookecommands.Commands(self)
361
362     def CreatePanelFolders(self):
363         #set file filters
364         filters = self.config['folders']['filters']
365         index = self.config['folders'].as_int('filterindex')
366         #set initial directory
367         folder = self.config['general']['workdir']
368         return wx.GenericDirCtrl(self, -1, dir=folder, size=(200, 250), style=wx.DIRCTRL_SHOW_FILTERS, filter=filters, defaultFilter=index)
369
370     def CreatePanelOutput(self):
371         return wx.TextCtrl(self, -1, '', wx.Point(0, 0), wx.Size(150, 90), wx.NO_BORDER|wx.TE_MULTILINE)
372
373     def CreatePanelPlaylists(self):
374         return hookeplaylist.Playlists(self)
375
376     def CreatePanelProperties(self):
377         return hookepropertyeditor.PropertyEditor(self)
378
379     def CreatePanelResults(self):
380         return hookeresults.Results(self)
381
382     def CreatePanelWelcome(self):
383         ctrl = wx.html.HtmlWindow(self, -1, wx.DefaultPosition, wx.Size(400, 300))
384         introStr = '<h1>Welcome to Hooke</h1>' + \
385                  '<h3>Features</h3>' + \
386                  '<ul>' + \
387                  '<li>View, annotate, measure force curves</li>' + \
388                  '<li>Worm-like chain fit of force peaks</li>' + \
389                  '<li>Automatic convolution-based filtering of empty curves</li>' + \
390                  '<li>Automatic fit and measurement of multiple force peaks</li>' + \
391                  '<li>Handles force-clamp force experiments (experimental)</li>' + \
392                  '<li>It is extensible by users by means of plugins and drivers</li>' + \
393                  '</ul>' + \
394                  '<p>See the <a href="/p/hooke/wiki/DocumentationIndex">DocumentationIndex</a> for more information</p>'
395         ctrl.SetPage(introStr)
396         return ctrl
397
398     def CreateMenuBar(self):
399         menu_bar = wx.MenuBar()
400         #file
401         file_menu = wx.Menu()
402         file_menu.Append(wx.ID_OPEN, '&Open playlist\tCtrl-O')
403         file_menu.Append(wx.ID_SAVE, 'Save playlist\tCtrl-S')
404         file_menu.AppendSeparator()
405         file_menu.Append(wx.ID_EXIT, 'Exit\tCtrl-Q')
406         #edit
407         edit_menu = wx.Menu()
408         edit_menu.Append(ID_ExportText, 'Export text...')
409         edit_menu.Append(ID_ExportImage, 'Export image...')
410         edit_menu.AppendSeparator();
411         edit_menu.Append(ID_Config, 'Preferences')
412         #view
413         view_menu = wx.Menu()
414         view_menu.AppendCheckItem(ID_ViewFolders, 'Folders\tF5')
415         view_menu.AppendCheckItem(ID_ViewPlaylists, 'Playlists\tF6')
416         view_menu.AppendCheckItem(ID_ViewCommands, 'Commands\tF7')
417         view_menu.AppendCheckItem(ID_ViewProperties, 'Properties\tF8')
418         view_menu.AppendCheckItem(ID_ViewAssistant, 'Assistant\tF9')
419         view_menu.AppendCheckItem(ID_ViewResults, 'Results\tF10')
420         view_menu.AppendCheckItem(ID_ViewOutput, 'Output\tF11')
421         #perspectives
422         self._perspectives_menu = self.CreatePerspectivesMenu()
423         #help
424         help_menu = wx.Menu()
425         help_menu.Append(wx.ID_ABOUT, 'About Hooke')
426         #put it all together
427         menu_bar.Append(file_menu, 'File')
428         menu_bar.Append(edit_menu, 'Edit')
429         menu_bar.Append(view_menu, 'View')
430         menu_bar.Append(self._perspectives_menu, "Perspectives")
431         menu_bar.Append(help_menu, 'Help')
432
433         self.SetMenuBar(menu_bar)
434
435     def CreateNotebook(self):
436         # create the notebook off-window to avoid flicker
437         client_size = self.GetClientSize()
438         ctrl = aui.AuiNotebook(self, -1, wx.Point(client_size.x, client_size.y), wx.Size(430, 200), self._notebook_style)
439         arts = [aui.AuiDefaultTabArt, aui.AuiSimpleTabArt, aui.VC71TabArt, aui.FF2TabArt, aui.VC8TabArt, aui.ChromeTabArt]
440         art = arts[self._notebook_theme]()
441         ctrl.SetArtProvider(art)
442         #uncomment if we find a nice icon
443         #page_bmp = wx.ArtProvider.GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
444         ctrl.AddPage(self.CreatePanelWelcome(), "Welcome", False)
445         return ctrl
446
447     def CreatePerspectivesMenu(self):
448         menu = wx.Menu()
449         menu.Append(ID_SavePerspective, "Save Perspective")
450         menu.Append(ID_DeletePerspective, "Delete Perspective")
451         menu.AppendSeparator()
452         #add perspectives to menubar and _perspectives
453         perspectivesDirectory = os.path.join(lh.hookeDir, 'perspectives')
454         if os.path.isdir(perspectivesDirectory):
455             perspectiveFileNames = os.listdir(perspectivesDirectory)
456             for perspectiveFilename in perspectiveFileNames:
457                 filename = lh.get_file_path(perspectiveFilename, ['perspectives'])
458                 if os.path.isfile(filename):
459                     perspectiveFile = open(filename, 'rU')
460                     perspective = perspectiveFile.readline()
461                     perspectiveFile.close()
462                     if perspective != '':
463                         name, extension = os.path.splitext(perspectiveFilename)
464                         if extension == '.txt':
465                             menuItem = menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
466                             self._perspectives[name] = [len(self._perspectives), perspective]
467                             if self.config['perspectives']['active'] == name:
468                                 menuItem.Check()
469         #in case there are no perspectives
470         if not self._perspectives:
471             perspective = self._mgr.SavePerspective()
472             self.config['perspectives']['default'] = 'Default'
473             self._perspectives['Default'] = [0, perspective]
474             menuItem = menu.AppendRadioItem(ID_FirstPerspective, 'Default')
475             menuItem.Check()
476             self._SavePerspectiveToFile('Default', perspective)
477         return menu
478
479     def CreateStatusbar(self):
480         statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
481         statusbar.SetStatusWidths([-2, -3])
482         statusbar.SetStatusText('Ready', 0)
483         welcomeString=u'Welcome to Hooke (version '+__version__+', '+__release_name__+')!'
484         statusbar.SetStatusText(welcomeString, 1)
485         return statusbar
486
487     def CreateToolBar(self):
488         toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
489         toolbar.SetToolBitmapSize(wx.Size(16,16))
490         toolbar_bmp1 = wx.ArtProvider_GetBitmap(wx.ART_QUESTION, wx.ART_OTHER, wx.Size(16, 16))
491         toolbar_bmpOpen = wx.ArtProvider_GetBitmap(wx.ART_FILE_OPEN, wx.ART_OTHER, wx.Size(16, 16))
492         toolbar_bmpSave = wx.ArtProvider_GetBitmap(wx.ART_FILE_SAVE, wx.ART_OTHER, wx.Size(16, 16))
493         toolbar_bmpExportText = wx.ArtProvider_GetBitmap(wx.ART_NORMAL_FILE, wx.ART_OTHER, wx.Size(16, 16))
494         toolbar_bmpExportImage = wx.ArtProvider_GetBitmap(wx.ART_MISSING_IMAGE, wx.ART_OTHER, wx.Size(16, 16))
495         toolbar.AddLabelTool(101, 'Open', toolbar_bmpOpen)
496         toolbar.AddLabelTool(102, 'Save', toolbar_bmpSave)
497         toolbar.AddSeparator()
498         toolbar.AddLabelTool(ID_ExportText, 'Export text...', toolbar_bmpExportText)
499         toolbar.AddLabelTool(ID_ExportImage, 'Export image...', toolbar_bmpExportImage)
500         toolbar.Realize()
501         return toolbar
502
503     def CreateToolBarNavigation(self):
504         toolbar = wx.ToolBar(self, -1, wx.DefaultPosition, wx.DefaultSize, wx.TB_FLAT | wx.TB_NODIVIDER)
505         toolbar.SetToolBitmapSize(wx.Size(16,16))
506         toolbar_bmpBack = wx.ArtProvider_GetBitmap(wx.ART_GO_BACK, wx.ART_OTHER, wx.Size(16, 16))
507         toolbar_bmpForward = wx.ArtProvider_GetBitmap(wx.ART_GO_FORWARD, wx.ART_OTHER, wx.Size(16, 16))
508         toolbar.AddLabelTool(ID_Previous, 'Previous', toolbar_bmpBack, shortHelp='Previous curve')
509         toolbar.AddLabelTool(ID_Next, 'Next', toolbar_bmpForward, shortHelp='Next curve')
510         toolbar.Realize()
511         return toolbar
512
513     def DeleteFromPlaylists(self, name):
514         if name in self.playlists:
515             del self.playlists[name]
516         tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
517         item, cookie = self.panelPlaylists.PlaylistsTree.GetFirstChild(tree_root)
518         while item.IsOk():
519             playlist_name = self.panelPlaylists.PlaylistsTree.GetItemText(item)
520             if playlist_name == name:
521                 try:
522                     self.panelPlaylists.PlaylistsTree.Delete(item)
523                 except:
524                     pass
525             item = self.panelPlaylists.PlaylistsTree.GetNextSibling(item)
526         self.OnPlaylistsLeftDclick(None)
527
528     def DeletePlotPage(self, name):
529         index = self._GetPlaylistTab(name)
530         plot = self.playlists[name][1]
531         plot = None
532         self.plotNotebook.RemovePage(index)
533         self.DeleteFromPlaylists(name)
534
535     def GetActiveCurve(self):
536         playlist = self.GetActivePlaylist()
537         if playlist is not None:
538             return playlist.get_active_curve()
539         return None
540
541     def GetActivePlaylist(self):
542         playlist_name = self._GetActivePlaylistName()
543         if playlist_name in self.playlists:
544             return self.playlists[playlist_name][0]
545         return None
546
547     def GetActivePlot(self):
548         curve = self.GetActiveCurve()
549         if curve is not None:
550             return curve.plots[0]
551         return None
552
553     def GetDockArt(self):
554         return self._mgr.GetArtProvider()
555
556     def GetBoolFromConfig(self, *args):
557         if len(args) == 2:
558             plugin = args[0]
559             section = args[0]
560             key = args[1]
561         elif len(args) == 3:
562             plugin = args[0]
563             section = args[1]
564             key = args[2]
565         if self.configs.has_key(plugin):
566             config = self.configs[plugin]
567             return config[section][key].as_bool('value')
568         return None
569
570     def GetFloatFromConfig(self, *args):
571         if len(args) == 2:
572             plugin = args[0]
573             section = args[0]
574             key = args[1]
575         elif len(args) == 3:
576             plugin = args[0]
577             section = args[1]
578             key = args[2]
579         if self.configs.has_key(plugin):
580             config = self.configs[plugin]
581             return config[section][key].as_float('value')
582         return None
583
584     def GetIntFromConfig(self, *args):
585         if len(args) == 2:
586             plugin = args[0]
587             section = args[0]
588             key = args[1]
589         elif len(args) == 3:
590             plugin = args[0]
591             section = args[1]
592             key = args[2]
593         if self.configs.has_key(plugin):
594             config = self.configs[plugin]
595             return config[section][key].as_int('value')
596         return None
597
598     def GetStringFromConfig(self, *args):
599         if len(args) == 2:
600             plugin = args[0]
601             section = args[0]
602             key = args[1]
603         elif len(args) == 3:
604             plugin = args[0]
605             section = args[1]
606             key = args[2]
607         if self.configs.has_key(plugin):
608             config = self.configs[plugin]
609             return config[section][key]['value']
610         return None
611
612     def GetPerspectiveMenuItem(self, name):
613         index = self._perspectives[name][0]
614         perspective_Id = ID_FirstPerspective + index
615         menu_item = self.MenuBar.FindItemById(perspective_Id)
616         return menu_item
617
618     def HasPlotmanipulator(self, name):
619         '''
620         returns True if the plotmanipulator 'name' is loaded, False otherwise
621         '''
622         for plotmanipulator in self.plotmanipulators:
623             if plotmanipulator[0] == name:
624                 return True
625         return False
626
627     def OnAbout(self, event):
628         msg = 'Hooke\n\n'+\
629             'A free, open source data analysis platform\n'+\
630             '(c) 2006-2008 Massimo Sandal\n\n'+\
631             '(c) 2009 Dr. Rolf Schmidt\n\n'+\
632             'Released under the GNU GPL v2'
633         dialog = wx.MessageDialog(self, msg, "About Hooke", wx.OK | wx.ICON_INFORMATION)
634         dialog.ShowModal()
635         dialog.Destroy()
636
637     def OnClose(self, event):
638         #apply changes
639         self.config['main']['height'] = str(self.GetSize().GetHeight())
640         self.config['main']['left'] = str(self.GetPosition()[0])
641         self.config['main']['top'] = str(self.GetPosition()[1])
642         self.config['main']['width'] = str(self.GetSize().GetWidth())
643         # Writing the configuration file to 'hooke.ini'
644         self.config.write()
645         self._mgr.UnInit()
646         del self._mgr
647         self.Destroy()
648
649     def OnDeletePerspective(self, event):
650         pass
651
652     def OnDirCtrlLeftDclick(self, event):
653         file_path = self.panelFolders.GetPath()
654         if os.path.isfile(file_path):
655             if file_path.endswith('.hkp'):
656                 self.do_loadlist(file_path)
657             else:
658                 pass
659         event.Skip()
660
661     def OnEraseBackground(self, event):
662         event.Skip()
663
664     def OnExecute(self, event):
665         item = self.panelCommands.CommandsTree.GetSelection()
666         if item.IsOk():
667             if self.panelCommands.CommandsTree.ItemHasChildren(item):
668                 pass
669             else:
670                 #get the plugin
671                 parent = self.panelCommands.CommandsTree.GetItemParent(item)
672             if not self.panelCommands.CommandsTree.ItemHasChildren(item):
673                 parent_text = self.panelCommands.CommandsTree.GetItemText(parent)
674                 item_text = self.panelCommands.CommandsTree.GetItemText(item)
675                 if item_text in ['genlist', 'loadlist', 'savelist']:
676                     property_values = self.panelProperties.GetPropertyValues()
677                     arg_str = ''
678                     for item in property_values:
679                         arg_str = ''.join([arg_str, item, '=r"', str(property_values[item]), '", '])
680                     command = ''.join(['self.do_', item_text, '(', arg_str, ')'])
681                 else:
682                     command = ''.join(['self.do_', item_text, '()'])
683                 exec(command)
684         pass
685
686     def OnExit(self, event):
687         self.Close()
688
689     def OnExportImage(self, event):
690         pass
691
692     def OnNext(self, event):
693         '''
694         NEXT
695         Go to the next curve in the playlist.
696         If we are at the last curve, we come back to the first.
697         -----
698         Syntax: next, n
699         '''
700         selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
701         if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
702             #GetFirstChild returns a tuple
703             #we only need the first element
704             next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(selected_item)[0]
705         else:
706             next_item = self.panelPlaylists.PlaylistsTree.GetNextSibling(selected_item)
707             if not next_item.IsOk():
708                 parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
709                 #GetFirstChild returns a tuple
710                 #we only need the first element
711                 next_item = self.panelPlaylists.PlaylistsTree.GetFirstChild(parent_item)[0]
712         self.panelPlaylists.PlaylistsTree.SelectItem(next_item, True)
713         playlist = self.playlists[self._GetActivePlaylistName()][0]
714         if playlist.count > 1:
715             playlist.next()
716             self.statusbar.SetStatusText(playlist.get_status_string(), 0)
717             self.UpdatePlot()
718
719     def OnNotebookPageClose(self, event):
720         ctrl = event.GetEventObject()
721         playlist_name = ctrl.GetPageText(ctrl._curpage)
722         self.DeleteFromPlaylists(playlist_name)
723
724     def OnPaneClose(self, event):
725         event.Skip()
726
727     def OnPlaylistsLeftDclick(self, event):
728         playlist_name = self._GetActivePlaylistName()
729         #if that playlist already exists
730         #we check if it is the active playlist (ie selected in panelPlaylists)
731         #and switch to it if necessary
732         if playlist_name in self.playlists:
733             index = self.plotNotebook.GetSelection()
734             current_playlist = self.plotNotebook.GetPageText(index)
735             #new_playlist = self.playlists[playlist_name][0]
736             #if current_playlist != new_playlist:
737             if current_playlist != playlist_name:
738                 index = self._GetPlaylistTab(playlist_name)
739                 self.plotNotebook.SetSelection(index)
740             #if a curve was double-clicked
741             item = self.panelPlaylists.PlaylistsTree.GetSelection()
742             #TODO: fix with get_active_curve
743             if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
744                 index = self._GetActiveCurveIndex()
745             else:
746                 index = 0
747             if index >= 0:
748                 playlist = self.playlists[playlist_name][0]
749                 playlist.index = index
750                 self.statusbar.SetStatusText(playlist.get_status_string(), 0)
751                 self.UpdatePlot()
752         #if you uncomment the following line, the tree will collapse/expand as well
753         #event.Skip()
754
755     def OnPlaylistsLeftDown(self, event):
756         hit_item, hit_flags = self.panelPlaylists.PlaylistsTree.HitTest(event.GetPosition())
757         if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
758             #self.SetFocus()
759             self.panelPlaylists.PlaylistsTree.SelectItem(hit_item)
760             playlist_name = self._GetActivePlaylistName()
761             playlist = self.playlists[playlist_name][0]
762             #if a curve was clicked
763             item = self.panelPlaylists.PlaylistsTree.GetSelection()
764             if not self.panelPlaylists.PlaylistsTree.ItemHasChildren(item):
765                 #TODO: fix with get_active_curve
766                 index = self._GetActiveCurveIndex()
767                 if index >= 0:
768                     #playlist = self.playlists[playlist_name][0]
769                     playlist.index = index
770                     #self.playlists[playlist_name][0].index = index
771             #else:
772                 ##self.playlists[playlist_name][0].index = 0
773                 #playlist.index = index
774             self.playlists[playlist_name][0] = playlist
775         event.Skip()
776
777     def OnPrevious(self, event):
778         '''
779         PREVIOUS
780         Go to the previous curve in the playlist.
781         If we are at the first curve, we jump to the last.
782         -------
783         Syntax: previous, p
784         '''
785         #playlist = self.playlists[self._GetActivePlaylistName()][0]
786         #select the previous curve and tell the user if we wrapped around
787         #self.AppendToOutput(playlist.previous())
788         selected_item = self.panelPlaylists.PlaylistsTree.GetSelection()
789         if self.panelPlaylists.PlaylistsTree.ItemHasChildren(selected_item):
790             previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(selected_item)
791         else:
792             previous_item = self.panelPlaylists.PlaylistsTree.GetPrevSibling(selected_item)
793             if not previous_item.IsOk():
794                 parent_item = self.panelPlaylists.PlaylistsTree.GetItemParent(selected_item)
795                 previous_item = self.panelPlaylists.PlaylistsTree.GetLastChild(parent_item)
796         self.panelPlaylists.PlaylistsTree.SelectItem(previous_item, True)
797         playlist = self.playlists[self._GetActivePlaylistName()][0]
798         if playlist.count > 1:
799             playlist.previous()
800             self.statusbar.SetStatusText(playlist.get_status_string(), 0)
801             self.UpdatePlot()
802
803     def OnPropGridChanged (self, event):
804         prop = event.GetProperty()
805         if prop:
806             item_section = self.panelProperties.SelectedTreeItem
807             item_plugin = self.panelCommands.CommandsTree.GetItemParent(item_section)
808             plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
809             config = self.configs[plugin]
810             property_section = self.panelCommands.CommandsTree.GetItemText(item_section)
811             property_key = prop.GetName()
812             property_value = prop.GetValue()
813             config[property_section][property_key]['value'] = property_value
814
815     def OnPropGridSelect(self, event):
816         pass
817
818     def OnRestorePerspective(self, event):
819         name = self.MenuBar.FindItemById(event.GetId()).GetLabel()
820         self._mgr.LoadPerspective(self._perspectives[name][1])
821         self.config['perspectives']['active'] = name
822         self._mgr.Update()
823         all_panes = self._mgr.GetAllPanes()
824         for pane in all_panes:
825             if not pane.name.startswith('toolbar'):
826                 if pane.name == 'Assistant':
827                     self.MenuBar.FindItemById(ID_ViewAssistant).Check(pane.window.IsShown())
828                 if pane.name == 'Folders':
829                     self.MenuBar.FindItemById(ID_ViewFolders).Check(pane.window.IsShown())
830                 if pane.name == 'Playlists':
831                     self.MenuBar.FindItemById(ID_ViewPlaylists).Check(pane.window.IsShown())
832                 if pane.name == 'Commands':
833                     self.MenuBar.FindItemById(ID_ViewCommands).Check(pane.window.IsShown())
834                 if pane.name == 'Properties':
835                     self.MenuBar.FindItemById(ID_ViewProperties).Check(pane.window.IsShown())
836                 if pane.name == 'Output':
837                     self.MenuBar.FindItemById(ID_ViewOutput).Check(pane.window.IsShown())
838                 if pane.name == 'Results':
839                     self.MenuBar.FindItemById(ID_ViewResults).Check(pane.window.IsShown())
840
841     def OnResultsCheck(self, index, flag):
842         curve = self.GetActiveCurve()
843         result = curve.data['results'][index]['visible'] = flag
844         self.UpdatePlot()
845
846     def OnSavePerspective(self, event):
847         def nameExists(name):
848             for item in self._perspectives_menu.GetMenuItems():
849                 if item.GetText() == name:
850                     return True
851             return False
852
853         done = False
854         while not done:
855             dialog = wx.TextEntryDialog(self, 'Enter a name for the new perspective:', 'Save perspective')
856             dialog.SetValue('New perspective')
857             if dialog.ShowModal() != wx.ID_OK:
858                 return
859             else:
860                 name = dialog.GetValue()
861
862             if nameExists(name):
863                 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)
864                 if dialogConfirm.ShowModal() == wx.ID_YES:
865                     done = True
866             else:
867                 done = True
868
869         perspective = self._mgr.SavePerspective()
870
871         if nameExists(name):
872             #check the corresponding menu item
873             menuItem = self.GetPerspectiveMenuItem(name)
874             #replace the perspectiveStr in _pespectives
875             index = self._perspectives[name][0]
876             self._perspectives[name] = [index, perspective]
877         else:
878             #simply add the new perspective to _perspectives
879             index = len(self._perspectives)
880             self._perspectives[name] = [len(self._perspectives), perspective]
881             menuItem = self._perspectives_menu.AppendRadioItem(ID_FirstPerspective + len(self._perspectives), name)
882
883         menuItem.Check()
884         self._SavePerspectiveToFile(name, perspective)
885         #uncheck all perspective menu items
886         #as these are radio items, one item has to be checked at all times
887         #the line 'menuItem.Check()' above actually checks a second item
888         #but does not toggle
889         #so we need to uncheck all other items afterwards
890         #weirdly enough, menuitem.Toggle() doesn't do this properly either
891         for item in self._perspectives_menu.GetMenuItems():
892             if item.IsCheckable():
893                 if item.GetLabel() != name:
894                     item.Check(False)
895
896     def OnView(self, event):
897         menu_id = event.GetId()
898         menu_item = self.MenuBar.FindItemById(menu_id)
899         menu_label = menu_item.GetLabel()
900
901         pane = self._mgr.GetPane(menu_label)
902         pane.Show(not pane.IsShown())
903         #if we don't do the following, the Folders pane does not resize properly on hide/show
904         if pane.caption == 'Folders' and pane.IsShown() and pane.IsDocked():
905             #folders_size = pane.GetSize()
906             self.panelFolders.Fit()
907         self._mgr.Update()
908
909     def OnSize(self, event):
910         event.Skip()
911
912     def OnTreeCtrlCommandsLeftDown(self, event):
913         hit_item, hit_flags = self.panelCommands.CommandsTree.HitTest(event.GetPosition())
914         if (hit_flags & wx.TREE_HITTEST_ONITEM) != 0:
915             self.panelCommands.CommandsTree.SelectItem(hit_item)
916             self.panelProperties.SelectedTreeItem = hit_item
917             #if a command was clicked
918             properties = []
919             if not self.panelCommands.CommandsTree.ItemHasChildren(hit_item):
920                 item_plugin = self.panelCommands.CommandsTree.GetItemParent(hit_item)
921                 plugin = self.panelCommands.CommandsTree.GetItemText(item_plugin)
922                 if self.configs.has_key(plugin):
923                     #config = self.panelCommands.CommandsTree.GetPyData(item_plugin)
924                     config = self.configs[plugin]
925                     section = self.panelCommands.CommandsTree.GetItemText(hit_item)
926                     #display docstring in help window
927                     doc_string = eval('self.do_' + section + '.__doc__')
928                     if section in config:
929                         for option in config[section]:
930                             properties.append([option, config[section][option]])
931             else:
932                 module = self.panelCommands.CommandsTree.GetItemText(hit_item)
933                 if module != 'general':
934                     doc_string = eval('plugins.' + module + '.' + module + 'Commands.__doc__')
935                 else:
936                     doc_string = 'The module "general" contains Hooke core functionality'
937             if doc_string is not None:
938                 self.panelAssistant.ChangeValue(doc_string)
939             hookepropertyeditor.PropertyEditor.Initialize(self.panelProperties, properties)
940         event.Skip()
941
942     def UpdatePlaylists(self):
943         #setup the playlist in the Playlist tree
944         tree_root = self.panelPlaylists.PlaylistsTree.GetRootItem()
945         playlist_root = self.panelPlaylists.PlaylistsTree.AppendItem(tree_root, playlist.name, 0)
946         #add all curves to the Playlist tree
947         curves = {}
948         for index, curve in enumerate(playlist.curves):
949             ##remove the extension from the name of the curve
950             ##TODO: optional?
951             #item_text, extension = os.path.splitext(curve.name)
952             #curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, item_text, 1)
953             curve_ID = self.panelPlaylists.PlaylistsTree.AppendItem(playlist_root, curve.name, 1)
954             if index == playlist.index:
955                 self.panelPlaylists.PlaylistsTree.SelectItem(curve_ID)
956         #create the plot tab and add playlist to the dictionary
957         plotPanel = wxmpl.PlotPanel(self, ID_FirstPlot + len(self.playlists))
958         notebook_tab = self.plotNotebook.AddPage(plotPanel, playlist.name, True)
959         #tab_index = self.plotNotebook.GetSelection()
960         figure = plotPanel.get_figure()
961         #self.playlists[playlist.name] = [playlist, tab_index, figure]
962         self.playlists[playlist.name] = [playlist, figure]
963         self.panelPlaylists.PlaylistsTree.Expand(playlist_root)
964         self.statusbar.SetStatusText(playlist.get_status_string(), 0)
965         self.UpdatePlot()
966
967 #HELPER FUNCTIONS
968 #Everything sending an event should be here
969     def _measure_N_points(self, N, whatset=1):
970         '''
971         general helper function for N-points measures
972         '''
973         wx.PostEvent(self.frame,self.list_of_events['measure_points'](num_of_points=N, set=whatset))
974         while 1:
975             try:
976                 points=self.frame.events_from_gui.get()
977                 break
978             except Empty:
979                 pass
980         return points
981
982     def _clickize(self, xvector, yvector, index):
983         '''
984         returns a ClickedPoint() object from an index and vectors of x, y coordinates
985         '''
986         point = lh.ClickedPoint()
987         point.index = index
988         point.absolute_coords = xvector[index], yvector[index]
989         point.find_graph_coords(xvector, yvector)
990         return point
991
992 #PLAYLIST INTERACTION COMMANDS
993 #-------------------------------
994     def do_genlist(self, folder=lh.hookeDir, filemask='*.*'):
995         '''
996         GENLIST
997         Generates a file playlist.
998         Note it doesn't *save* it: see savelist for this.
999
1000         If [input files] is a directory, it will use all files in the directory for playlist.
1001         So:
1002         genlist dir
1003         genlist dir/
1004         genlist dir/*.*
1005
1006         are all equivalent syntax.
1007         ------------
1008         Syntax: genlist [input files]
1009         '''
1010         #args list is: input folder, file mask
1011         if os.path.isdir(folder):
1012             path = os.path.join(folder, filemask)
1013             #expanding correctly the input list with the glob module :)
1014             files = glob.glob(path)
1015             files.sort()
1016             #TODO: change cursor or progressbar (maybe in statusbar)
1017             #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1018             playlist = playlist.Playlist(self.drivers)
1019             for item in files:
1020                 curve = playlist.add_curve(item)
1021                 plot = copy.deepcopy(curve.plots[0])
1022                 #add the 'raw' data
1023                 curve.add_data('raw', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1024                 curve.add_data('raw', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1025                 #apply all active plotmanipulators and add the 'manipulated' data
1026                 for plotmanipulator in self.plotmanipulators:
1027                     plot = plotmanipulator[1](plot, curve)
1028                     curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1029                     curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1030             if playlist.count > 0:
1031                 playlist.name = self._GetUniquePlaylistName(os.path.basename(folder))
1032                 playlist.reset()
1033                 self.AddToPlaylists(playlist)
1034             self.AppendToOutput(playlist.get_status_string())
1035         else:
1036             self.AppendToOutput(''.join(['Cannot find folder ', folder]))
1037
1038     def do_loadlist(self, filename):
1039         '''
1040         LOADLIST
1041         Loads a file playlist
1042         -----------
1043         Syntax: loadlist [playlist file]
1044         '''
1045         #TODO: check for duplicate playlists, ask the user for a unique name
1046         #if self.playlist_name in self.playlists:
1047
1048         #add hkp extension if necessary
1049         if not filename.endswith('.hkp'):
1050             filename = ''.join([filename, '.hkp'])
1051         #prefix with 'hookeDir' if just a filename or a relative path
1052         filename = lh.get_file_path(filename)
1053         if os.path.isfile(filename):
1054             #TODO: change cursor
1055             #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1056             playlist_new = playlist.Playlist(self.drivers)
1057             playlist_new.load(filename)
1058             if playlist_new.count > 0:
1059                 for curve in playlist_new.curves:
1060                     plot = copy.deepcopy(curve.plots[0])
1061                     for plotmanip in self.plotmanipulators:
1062                         #to_plot = plotmanip[1](to_plot, curve)
1063                         plot = plotmanip[1](plot, curve)
1064                         curve.set_data('manipulated', plot.vectors[0][0], plot.vectors[0][1], color=plot.colors[0], style='plot')
1065                         curve.add_data('manipulated', plot.vectors[1][0], plot.vectors[1][1], color=plot.colors[1], style='plot')
1066                 self.AddToPlaylists(playlist_new)
1067             #else:
1068                 ##TODO: display dialog
1069             self.AppendToOutput(playlist_new.get_status_string())
1070             #TODO: change cursor
1071             #self.SetCursor(wx.StockCursor(wx.CURSOR_ARROW))
1072         else:
1073             #TODO: display dialog
1074             self.AppendToOutput(''.join['File ', filename, ' not found.\n'])
1075         pass
1076
1077     def do_savelist(self, filename):
1078         '''
1079         SAVELIST
1080         Saves the current file playlist on disk.
1081         ------------
1082         Syntax: savelist [filename]
1083         '''
1084
1085         #self.playlist_generics['pointer'] = self._GetActiveCurveIndex
1086         pointer = self._GetActiveCurveIndex()
1087         #autocomplete filename if not specified
1088         if not filename.endswith('.hkp'):
1089             filename = filename.join(['.hkp'])
1090
1091         playlist = self.GetActivePlaylist()
1092         playlist.set_XML()
1093         playlist.save(filename)
1094
1095 #PLOT INTERACTION COMMANDS
1096 #-------------------------------
1097     def UpdatePlot(self):
1098         def add_plot(plot):
1099             if plot['visible'] and plot['x'] and plot['y']:
1100                 color = plot['color']
1101                 style = plot['style']
1102                 if style == 'plot':
1103                     axes.plot(plot['x'], plot['y'], color=color, zorder=1)
1104                 if style == 'scatter':
1105                     axes.scatter(plot['x'], plot['y'], color=color, s=0.5, zorder=2)
1106
1107         def add_plot2(plot):
1108             if plot.visible and plot.x and plot.y:
1109                 if plot.style == 'plot':
1110                     axes.plot(plot.x, plot.y, color=plot.color, zorder=1)
1111                 if plot.style == 'scatter':
1112                     axes.scatter(plot.x, plot.y, color=plot.color, s=0.5, zorder=2)
1113
1114         playlist_name = self._GetActivePlaylistName()
1115         index = self._GetActiveCurveIndex()
1116         playlist = self.playlists[playlist_name][0]
1117         curve = playlist.get_active_curve()
1118         plot = playlist.get_active_plot()
1119         figure = self.playlists[playlist_name][1]
1120
1121         figure.clf()
1122         exclude = None
1123         if curve.data.has_key('manipulated'):
1124             exclude = 'raw'
1125         elif curve.data.has_key('raw'):
1126             exclude = 'manipulated'
1127
1128         if exclude is not None:
1129             #TODO: what is this good for?
1130             if not hasattr(self, 'subplot'):
1131                 axes = figure.add_subplot(111)
1132
1133             axes.set_title(plot.title)
1134             axes.set_xlabel(plot.units[0])
1135             axes.set_ylabel(plot.units[1])
1136
1137             for set_of_plots in curve.data:
1138                 if set_of_plots != exclude:
1139                     plots = curve.data[set_of_plots]
1140                     for each_plot in plots:
1141                         add_plot(each_plot)
1142
1143             #TODO: add multiple results support
1144             #for fit in curve.fits:
1145             if curve.fits.has_key('wlc'):
1146                 for plot in curve.fits['wlc'].results:
1147                     add_plot2(plot)
1148                 self.panelResults.DisplayResults(curve.fits['wlc'])
1149             else:
1150                 self.panelResults.ClearResults()
1151
1152             axes.figure.canvas.draw()
1153         else:
1154             self.AppendToOutput('Not able to plot.')
1155
1156
1157 if __name__ == '__main__':
1158     app = Hooke(debug=__debug__)
1159     app.MainLoop()
1160
1161