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