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