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