source: sasview/sansguiframe/src/sans/guiframe/data_processor.py @ 2073eb7

ESS_GUIESS_GUI_DocsESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_iss879ESS_GUI_iss959ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalccostrafo411magnetic_scattrelease-4.1.1release-4.1.2release-4.2.2release_4.0.1ticket-1009ticket-1094-headlessticket-1242-2d-resolutionticket-1243ticket-1249ticket885unittest-saveload
Last change on this file since 2073eb7 was 2073eb7, checked in by Gervaise Alina <gervyh@…>, 13 years ago

add name to batch result plotted

  • Property mode set to 100644
File size: 28.4 KB
Line 
1"""
2Implement grid used to store data
3"""
4import wx
5import numpy
6import math
7import re
8import os
9import sys
10import copy
11from wx.lib.scrolledpanel import ScrolledPanel
12import  wx.grid as  Grid
13import wx.aui
14from wx.aui import AuiNotebook as nb
15from sans.guiframe.panel_base import PanelBase
16import wx.lib.sheet as sheet
17
18from sans.guiframe.events import NewPlotEvent
19from sans.guiframe.events import StatusEvent 
20from sans.guiframe.dataFitting import Data1D
21
22FUNC_DICT = {"sqrt": "math.sqrt",
23             "pow": "math.sqrt"}
24
25
26def parse_string(sentence, list):
27    """
28    Return a dictionary of column label and index or row selected
29    :param sentence: String to parse
30    :param list: list of columns label
31    """
32    toks = []
33    p2 = re.compile(r'\d+')
34    p = re.compile(r'[\+\-\*\%\/]')
35    labels = p.split(sentence)
36    col_dict = {}
37    for elt in labels:
38        rang = None
39        temp_arr = []
40        for label in  list:
41            label_pos =  elt.find(label)
42            if label_pos != -1:
43                if elt.count(',') > 0:
44                    new_temp = []
45                    temp = elt.split(label)
46                    for item in temp:
47                        range_pos = item.find(":")
48                        if range_pos != -1:
49                            rang = p2.findall(item)
50                            for i in xrange(int(rang[0]), int(rang[1])+1 ):
51                                new_temp.append(i)
52                    temp_arr += new_temp
53                else:
54                    temp = elt.split(label)
55                    for item in temp:
56                        range_pos = item.find(":")
57                        if range_pos != -1:
58                            rang = p2.findall(item)
59                            for i in xrange(int(rang[0]), int(rang[1])+1 ):
60                                temp_arr.append(i)
61                col_dict[elt] = (label, temp_arr)
62    return col_dict
63
64class GridPage(sheet.CSheet):
65    """
66    """
67    def __init__(self, parent, panel=None):
68        """
69        """
70        sheet.CSheet.__init__(self, parent)
71        self.SetLabelBackgroundColour('#DBD4D4')
72        self.AutoSize()
73        self.panel = panel
74        self.col_names = []
75        self.data_inputs = {}
76        self.data_outputs = {}
77        self._cols = 50
78        self._rows = 51
79        col_with = 30
80        row_height = 20
81        self.axis_value = []
82        self.axis_label = ""
83        self.selected_cells = []
84        self.selected_cols = []
85        self.SetColMinimalAcceptableWidth(col_with)
86        self.SetRowMinimalAcceptableHeight(row_height)
87        self.SetNumberRows(self._cols)
88        self.SetNumberCols(self._rows)
89        self.Bind(wx.grid.EVT_GRID_LABEL_LEFT_CLICK, self.on_left_click)
90        self.Bind(wx.grid.EVT_GRID_LABEL_RIGHT_CLICK, self.on_right_click)
91        self.Bind(wx.grid.EVT_GRID_CELL_LEFT_CLICK, self.on_selected_cell)
92       
93    def on_selected_cell(self, event):
94        """
95        Handler catching cell selection
96        """
97        flag = event.CmdDown() or event.ControlDown()
98        row, col = event.GetRow(), event.GetCol()
99        cell = (row, col)
100        if not flag:
101            self.selected_cells = []
102            self.axis_value = []
103            self.axis_label = ""
104        if cell in self.selected_cells:
105            self.selected_cells.remove(cell)
106        else:
107            self.selected_cells.append(cell)
108        if row > 1:
109            if (cell) in self.selected_cells:
110                self.axis_value.append(self.GetCellValue(row, col))
111        self.axis_label = self.GetCellValue(row, col)
112        event.Skip()
113     
114    def on_left_click(self, event):
115        """
116        Catch the left click on label mouse event
117        """
118        flag = event.CmdDown() or event.ControlDown()
119        col = event.GetCol()
120        if not flag:
121            self.selected_cols = []
122            self.axis_value = []
123            self.axis_label = ""
124        if col not in self.selected_cols:
125            self.selected_cols.append(col)
126        if not flag :
127            for row in range(2, self.GetNumberRows()+ 1):
128                self.axis_value.append(self.GetCellValue(row, col))
129            row = 1
130            self.axis_label = self.GetCellValue(row, col)
131        event.Skip()
132       
133    def on_right_click(self, event):
134        """
135        Catch the right click mouse
136        """
137        col = event.GetCol()
138        if col != -1 and len(self.col_names) > col:
139            label = self.col_names[int(col)]
140            self.axis_label = label
141            if label in self.data.keys():
142                col_val = self.data[label]
143                self.axis_value = col_val
144        # Slicer plot popup menu
145        slicerpop = wx.Menu()
146        id = wx.NewId()
147        slicerpop.Append(id, '&Set X axis', 'Set X axis')
148        wx.EVT_MENU(self, id, self.on_set_x_axis)
149       
150        id = wx.NewId()
151        slicerpop.Append(id, '&Set Y axis', 'Set Y axis')
152        wx.EVT_MENU(self, id, self.on_set_y_axis)
153        pos = event.GetPosition()
154        pos = self.ScreenToClient(pos)
155        self.PopupMenu(slicerpop, pos)
156       
157    def on_set_x_axis(self, event):
158        """
159        """
160        self.panel.set_xaxis(x=self.axis_value, label=self.axis_label)
161   
162    def on_set_y_axis(self, event):
163        """
164        """
165        self.panel.set_yaxis(y=self.axis_value, label=self.axis_label)     
166           
167    def set_data(self, data_inputs, data_outputs):
168        """
169        Add data to the grid
170        """
171        if data_outputs is None:
172            data_outputs = {}
173        self.data_outputs = data_outputs
174        if self.data_inputs is None:
175            data_inputs = {}
176        self.data_inputs = data_inputs
177       
178        if  len(self.data_outputs) > 0:
179            self._cols = self.GetNumberCols()
180            self._rows = self.GetNumberRows()
181            self.col_names = self.data_outputs.keys()
182            self.col_names.sort() 
183            nbr_user_cols = len(self.col_names)
184            #Add more columns to the grid if necessary
185            if nbr_user_cols > self._cols:
186                new_col_nbr = nbr_user_cols -  self._cols
187                self.AppendCols(new_col_nbr, True)
188            #Add more rows to the grid if necessary 
189            nbr_user_row = len(self.data_outputs.values())
190            if nbr_user_row > self._rows + 1:
191                new_row_nbr =  nbr_user_row - self._rows
192                self.AppendRows(new_row_nbr, True)
193            # add data to the grid   
194            row = 0
195            col = 0
196            cell_col = 0
197            for col_name in  self.col_names:
198                # use the first row of the grid to add user defined labels
199                self.SetCellValue(row, col, str(col_name))
200                col += 1
201                cell_row =  1
202                value_list = self.data_outputs[col_name]
203               
204                for value in value_list:
205                    self.SetCellValue(cell_row, cell_col, str(value))
206                    cell_row += 1
207                cell_col += 1
208            self.AutoSize()
209           
210
211class Notebook(nb, PanelBase):
212    """
213    ## Internal name for the AUI manager
214    window_name = "Fit panel"
215    ## Title to appear on top of the window
216    """
217    window_caption = "Notebook "
218   
219    def __init__(self, parent, manager=None, data=None, *args, **kwargs):
220        """
221        """
222        nb.__init__(self, parent, -1,
223                    style= wx.aui.AUI_BUTTON_DOWN|
224                    wx.aui.AUI_NB_WINDOWLIST_BUTTON|
225                    wx.aui.AUI_NB_DEFAULT_STYLE|
226                    wx.CLIP_CHILDREN)
227        PanelBase.__init__(self, parent)
228        self.enable_close_button()
229        self.parent = parent
230        self.manager = manager
231        self.data = data
232        self.Bind(wx.aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.on_close_page)
233   
234    def enable_close_button(self):
235        """
236        display the close button on tab for more than 1 tabs else remove the
237        close button
238        """
239        if self.GetPageCount() <= 1:
240            style = self.GetWindowStyleFlag() 
241            flag = wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
242            if style & wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB == flag:
243                style = style & ~wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
244                self.SetWindowStyle(style)
245        else:
246            style = self.GetWindowStyleFlag()
247            flag = wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
248            if style & wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB != flag:
249                style |= wx.aui.AUI_NB_CLOSE_ON_ACTIVE_TAB
250                self.SetWindowStyle(style)
251             
252    def on_edit_axis(self):
253        """
254        Return the select cell of a given selected column
255        """
256        pos = self.GetSelection()
257        grid = self.GetPage(pos)
258        if len(grid.selected_cols) > 1:
259            msg = "Edit axis doesn't understand this selection.\n"
260            msg += "Please select only one column"
261            raise ValueError, msg
262        list_of_cells = []
263        if len(grid.selected_cols) == 1:
264            col = grid.selected_cols[0]
265            if len(grid.selected_cells) > 0:
266                cell_row, cell_col = grid.selected_cells[0]
267                if cell_col  != col:
268                    msg = "Edit axis doesn't understand this selection.\n"
269                    msg += "Please select element of the same col"
270                    raise ValueError, msg
271            for row in range(grid.GetNumberRows()):
272                list_of_cells.append((row + 1 , col))
273            for item in grid.selected_cells:
274                if item in list_of_cells:
275                    list_of_cells.remove(item)
276        elif len(grid.selected_cols) == 0:
277            list_of_cells = [(row + 1, col) for row, col in grid.selected_cells]
278        return list_of_cells
279   
280    def get_column_labels(self):
281        """
282        return dictionary of columns labels of the current page
283        """
284        pos = self.GetSelection()
285        grid = self.GetPage(pos)
286        labels = {}
287        row = 0
288        for col in range(grid.GetNumberCols()):
289            label = grid.GetCellValue(row, col)
290            if label.strip() != "" :
291                labels[label.strip()] = col
292        return labels
293       
294    def create_axis_label(self, cell_list):
295        """
296        Receive a list of cells and  create a string presenting the selected
297        cells.
298        :param cell_list: list of tuple
299       
300        """
301        pos = self.GetSelection()
302        grid = self.GetPage(pos)
303        label = ""
304        col_name = ""
305        if len(cell_list) > 0:
306            temp_list = copy.deepcopy(cell_list)
307            temp_list.sort()
308            temp = []
309            for item in temp_list:
310                if item[0] <= 1:
311                    temp.append(item)
312            for element in temp:
313                temp_list.remove(element)
314            row_min, col  = temp_list[0]   
315            row_max = row_min
316            col_name = grid.GetCellValue(0, col)
317            label += str(col_name) + "[" + str(row_min) + ":"
318            for index in xrange(len(temp_list)):
319                prev = index - 1
320                row, _ = temp_list[index]
321                if row > row_max + 1 :
322                    if prev > 0:
323                        row_max, _ = temp_list[prev]
324                        label += str(row_max) + "]" + ","
325                        row_min = row
326                        label  += "[" + str(row_min) + ":"
327                row_max = row
328                if (index == len(temp_list)- 1):
329                    label +=  str(row_max) + "]"     
330        return label, col_name
331   
332    def on_close_page(self, event):
333        """
334        close the page
335        """
336        if self.GetPageCount() == 1:
337            event.Veto()
338        self.enable_close_button()
339       
340    def set_data(self, data_inputs, data_outputs):
341        if data_outputs is None or data_outputs == {}:
342            return
343        grid = GridPage(self, panel=self.parent)
344        grid.set_data(data_inputs, data_outputs) 
345        self.AddPage(grid, "")
346        pos = self.GetPageIndex(grid)
347        title = "Batch " + str(self.GetPageCount())
348        self.SetPageText(pos, title)
349       
350    def add_column(self):
351        """
352        Append a new column to the grid
353        """
354        pos = self.GetSelection()
355        grid = self.GetPage(pos)
356        grid.AppendCols(1, True)
357       
358    def on_remove_column(self):
359        """
360        Remove column to the current grid
361        """
362        pos = self.GetSelection()
363        grid = self.GetPage(pos)
364        cols_pos = grid.GetSelectedCols() 
365        for cpos in cols_pos:
366            grid.DeleteCols(cpos)
367         
368         
369class SPanel(ScrolledPanel):
370    def __init__(self, parent, *args, **kwds):
371        ScrolledPanel.__init__(self, parent , *args, **kwds)
372        self.SetupScrolling() 
373
374
375class GridPanel(SPanel):
376    def __init__(self, parent, data_inputs=None,
377                 data_outputs=None, *args, **kwds):
378        SPanel.__init__(self, parent , *args, **kwds)
379        self.vbox = wx.BoxSizer(wx.VERTICAL)
380       
381        self.plotting_sizer = wx.FlexGridSizer(3, 7, 10, 5)
382        self.grid_sizer = wx.BoxSizer(wx.HORIZONTAL)
383        self.vbox.AddMany([(self.grid_sizer, 1, wx.EXPAND, 0),
384                           (wx.StaticLine(self, -1), 0, wx.EXPAND, 0),
385                           (self.plotting_sizer)])
386        self.parent = parent
387        self._data_inputs = data_inputs
388        self._data_outputs = data_outputs
389        self.x = []
390        self.= []
391        self.x_axis_label = None
392        self.y_axis_label = None
393        self.x_axis_title = None
394        self.y_axis_title = None
395        self.x_axis_unit = None
396        self.y_axis_unit = None
397        self.plot_button = None
398        self.notebook = None
399        self.layout_grid()
400        self.layout_plotting_area()
401        self.SetSizer(self.vbox)
402       
403    def set_data(self, data_inputs, data_outputs):
404        """
405        """
406        if self.notebook is not None:
407            self.notebook.set_data(data_inputs, data_outputs)
408       
409    def set_xaxis(self, label="", x=None):
410        """
411        """
412        if x is None:
413            x = []
414        self.x = x
415        self.x_axis_label.SetValue("%s[:]" % str(label))
416        self.x_axis_title.SetValue(str(label))
417       
418    def set_yaxis(self, label="", y=None):
419        """
420        """
421        if y is None:
422            y = []
423        self.y = y
424        self.y_axis_label.SetValue("%s[:]" % str(label))
425        self.y_axis_title.SetValue(str(label))
426       
427    def get_plot_axis(self, col, list):
428        """
429       
430        """
431        axis = []
432        pos = self.notebook.GetSelection()
433        grid = self.notebook.GetPage(pos)
434        for row in list:
435            label = grid.GetCellValue(0, col)
436            value = grid.GetCellValue(row - 1, col).strip()
437            if value != "":
438                if label.lower().strip() == "data":
439                    axis.append(float(row - 1))
440                else:
441                    axis.append(float(value))
442            else:
443                axis.append(None) 
444        return axis
445   
446    def on_plot(self, event):
447        """
448        Evaluate the contains of textcrtl and plot result
449        """ 
450        pos = self.notebook.GetSelection()
451        grid = self.notebook.GetPage(pos)
452        column_names = {}
453        if grid is not None:
454            column_names = self.notebook.get_column_labels()
455        #evalue x
456        sentence = self.x_axis_label.GetValue()
457        if sentence.strip() == "":
458            msg = "select value for x axis"
459            raise ValueError, msg
460        dict = parse_string(sentence, column_names.keys())
461        for tok, (col_name, list) in dict.iteritems():
462            col = column_names[col_name]
463            xaxis = self.get_plot_axis(col, list)
464            sentence = sentence.replace(tok, 
465                                        "numpy.array(%s)" % str(xaxis))
466        for key, value in FUNC_DICT.iteritems():
467            sentence = sentence.replace(key.lower(), value)
468        x = eval(sentence)
469        #evaluate y
470        sentence = self.y_axis_label.GetValue()
471        if sentence.strip() == "":
472            msg = "select value for y axis"
473            raise ValueError, msg
474        dict = parse_string(sentence, column_names.keys())
475        for tok, (col_name, list) in dict.iteritems():
476            col = column_names[col_name]
477            yaxis = self.get_plot_axis(col, list)
478            sentence = sentence.replace(tok, 
479                                        "numpy.array(%s)" % str(yaxis))
480        for key, value in FUNC_DICT.iteritems():
481            sentence = sentence.replace(key, value)
482        y = eval(sentence)
483        #plotting
484        new_plot = Data1D(x=x, y=y)
485        new_plot.id =  wx.NewId()
486        new_plot.group_id = wx.NewId()
487        title = "%s vs %s" % (self.y_axis_title.GetValue(), 
488                              self.x_axis_title.GetValue())
489        new_plot.xaxis(self.x_axis_title.GetValue(), self.x_axis_unit.GetValue())
490        new_plot.yaxis(self.y_axis_title.GetValue(), self.y_axis_unit.GetValue())
491        try:
492            title = self.notebook.GetPageText(pos)
493            data.name = title
494            wx.PostEvent(self.parent.parent, 
495                             NewPlotEvent(plot=new_plot, 
496                        group_id=str(new_plot.group_id), title =title))   
497        except:
498            pass
499       
500    def layout_grid(self):
501        """
502        Draw the area related to the grid
503        """
504        self.notebook = Notebook(parent=self)
505        self.notebook.set_data(self._data_inputs, self._data_outputs)
506        self.grid_sizer.Add(self.notebook, 1, wx.EXPAND, 0)
507       
508    def layout_plotting_area(self):
509        """
510        Draw area containing options to plot
511        """
512        self.x_axis_title = wx.TextCtrl(self, -1)
513        self.y_axis_title = wx.TextCtrl(self, -1)
514        self.x_axis_label = wx.TextCtrl(self, -1, size=(200, -1))
515        self.y_axis_label = wx.TextCtrl(self, -1, size=(200, -1))
516        self.x_axis_add = wx.Button(self, -1, "Add")
517        self.x_axis_add.Bind(event=wx.EVT_BUTTON, handler=self.on_edit_axis, 
518                            id=self.x_axis_add.GetId())
519        self.y_axis_add = wx.Button(self, -1, "Add")
520        self.y_axis_add.Bind(event=wx.EVT_BUTTON, handler=self.on_edit_axis, 
521                            id=self.y_axis_add.GetId())
522        self.x_axis_unit = wx.TextCtrl(self, -1)
523        self.y_axis_unit = wx.TextCtrl(self, -1)
524        self.plot_button = wx.Button(self, -1, "Plot")
525        wx.EVT_BUTTON(self, self.plot_button.GetId(), self.on_plot)
526        self.plotting_sizer.AddMany([
527                    (wx.StaticText(self, -1, "x-axis label"), 1,
528                      wx.TOP|wx.BOTTOM|wx.LEFT, 10),
529                    (self.x_axis_label, 1, wx.TOP|wx.BOTTOM, 10),
530                    (self.x_axis_add, 1, wx.TOP|wx.BOTTOM|wx.RIGHT, 10),
531                    (wx.StaticText(self, -1, "x-axis title"), 1, 
532                     wx.TOP|wx.BOTTOM|wx.LEFT, 10),
533                    (self.x_axis_title, 1, wx.TOP|wx.BOTTOM, 10),
534                    (wx.StaticText(self, -1 , "unit"), 1, 
535                     wx.TOP|wx.BOTTOM, 10),
536                    (self.x_axis_unit, 1, wx.TOP|wx.BOTTOM, 10),
537                    (wx.StaticText(self, -1, "y-axis label"), 1, 
538                     wx.BOTTOM|wx.LEFT, 10),
539                    (self.y_axis_label, wx.BOTTOM, 10),
540                    (self.y_axis_add, 1, wx.BOTTOM|wx.RIGHT, 10),
541                    (wx.StaticText(self, -1, "y-axis title"), 1, 
542                     wx.BOTTOM|wx.LEFT, 10),
543                    (self.y_axis_title,  wx.BOTTOM, 10),
544                    (wx.StaticText(self, -1 , "unit"), 1, wx.BOTTOM, 10),
545                    (self.y_axis_unit, 1, wx.BOTTOM, 10),
546                      (-1, -1),
547                      (-1, -1),
548                      (-1, -1),
549                      (-1, -1),
550                      (-1, -1),
551                      (-1, -1),
552                      (self.plot_button, 1, wx.LEFT|wx.BOTTOM, 10)])
553   
554    def on_edit_axis(self, event):
555        """
556        Get the selected column on  the visible grid and set values for axis
557        """
558        cell_list = self.notebook.on_edit_axis()
559        label, title = self.create_axis_label(cell_list)
560        tcrtl = event.GetEventObject()
561        if tcrtl == self.x_axis_add:
562            self.edit_axis_helper(self.x_axis_label, self.x_axis_title,
563                                   label, title)
564        elif tcrtl == self.y_axis_add:
565            self.edit_axis_helper(self.y_axis_label, self.y_axis_title,
566                                   label, title)
567           
568    def create_axis_label(self, cell_list):
569        """
570        Receive a list of cells and  create a string presenting the selected
571        cells.
572        :param cell_list: list of tuple
573       
574        """
575        if self.notebook is not None:
576            return self.notebook.create_axis_label(cell_list)
577   
578    def edit_axis_helper(self, tcrtl_label, tcrtl_title, label, title):
579        """
580        get controls to modify
581        """
582        tcrtl_label.SetValue(str(label))
583        tcrtl_title.SetValue(str(title))
584       
585    def add_column(self):
586        """
587        """
588        if self.notebook is not None:
589            self.notebook.add_column()
590       
591    def on_remove_column(self):
592        """
593        """
594        if self.notebook is not None:
595            self.notebook.on_remove_column()
596       
597       
598class GridFrame(wx.Frame):
599    def __init__(self, parent=None, data_inputs=None, data_outputs=None, id=-1, 
600                 title="Batch Results", size=(700, 400)):
601        wx.Frame.__init__(self, parent=parent, id=id, title=title, size=size)
602        self.parent = parent
603        self.panel = GridPanel(self, data_inputs, data_outputs)
604        menubar = wx.MenuBar()
605        self.SetMenuBar(menubar)
606        edit = wx.Menu()
607        menubar.Append(edit, "&Edit")
608        self.Bind(wx.EVT_CLOSE, self.on_close)
609       
610        add_col_menu = edit.Append(wx.NewId(), 'Add Column', 'Add column')
611        wx.EVT_MENU(self, add_col_menu.GetId(), self.on_add_column)
612        remove_col_menu = edit.Append(wx.NewId(), 'Remove Column', 
613                                      'Remove Column')
614        wx.EVT_MENU(self, remove_col_menu.GetId(), self.on_remove_column)
615
616    def on_close(self, event):
617        """
618        """
619        self.Hide()
620       
621    def on_remove_column(self, event):
622        """
623        Remove the selected column to the grid
624        """
625        self.panel.on_remove_column()
626       
627    def on_add_column(self, event):
628        """
629        Append a new column to the grid
630        """
631        self.panel.add_column()
632       
633    def set_data(self, data_inputs, data_outputs):
634        """
635        """
636        self.panel.set_data(data_inputs, data_outputs)
637     
638     
639class BatchOutputFrame(wx.Frame):
640    """
641    Allow to select where the result of batch will be displayed or stored
642    """
643    def __init__(self, parent, data_inputs, data_outputs, file_name="",
644                 details="", *args, **kwds):
645        """
646        :param parent: Window instantiating this dialog
647        :param result: result to display in a grid or export to an external
648                application.
649        """
650        #kwds['style'] = wx.CAPTION|wx.SYSTEM_MENU
651        wx.Frame.__init__(self, parent, *args, **kwds)
652        self.parent = parent
653        self.panel = wx.Panel(self)
654        self.file_name = file_name
655        self.details = details
656        self.data_inputs = data_inputs
657        self.data_outputs = data_outputs
658        self.data = {}
659        for item in (self.data_outputs, self.data_inputs):
660            self.data.update(item)
661        self.flag = 1
662        self.SetSize((300, 200))
663        self.local_app_selected = None
664        self.external_app_selected = None
665        self.save_to_file = None
666        self._do_layout()
667   
668    def _do_layout(self):
669        """
670        Draw the content of the current dialog window
671        """
672        vbox = wx.BoxSizer(wx.VERTICAL)
673        box_description = wx.StaticBox(self.panel, -1, str("Batch Outputs"))
674        hint_sizer = wx.StaticBoxSizer(box_description, wx.VERTICAL)
675        selection_sizer = wx.GridBagSizer(5, 5)
676        button_sizer = wx.BoxSizer(wx.HORIZONTAL)
677        text = "Open with %s" % self.parent.application_name
678        self.local_app_selected = wx.RadioButton(self.panel, -1, text,
679                                                style=wx.RB_GROUP)
680        self.Bind(wx.EVT_RADIOBUTTON, self.onselect,
681                    id=self.local_app_selected.GetId())
682        text = "Open with Excel"
683        self.external_app_selected  = wx.RadioButton(self.panel, -1, text)
684        self.Bind(wx.EVT_RADIOBUTTON, self.onselect,
685                    id=self.external_app_selected.GetId())
686        text = "Save to File"
687        self.save_to_file = wx.CheckBox(self.panel, -1, text)
688        self.Bind(wx.EVT_CHECKBOX, self.onselect,
689                    id=self.save_to_file.GetId())
690        self.local_app_selected.SetValue(True)
691        self.external_app_selected.SetValue(False)
692        self.save_to_file.SetValue(False)
693        button_close = wx.Button(self.panel, -1, "Close")
694        button_close.Bind(wx.EVT_BUTTON, id=button_close.GetId(),
695                           handler=self.on_close)
696        button_apply = wx.Button(self.panel, -1, "Apply")
697        button_apply.Bind(wx.EVT_BUTTON, id=button_apply.GetId(),
698                        handler=self.on_apply)
699        button_apply.SetFocus()
700        hint = ""
701        hint_sizer.Add(wx.StaticText(self.panel, -1, hint))
702        hint_sizer.Add(selection_sizer)
703        #draw area containing radio buttons
704        ix = 0
705        iy = 0
706        selection_sizer.Add(self.local_app_selected, (iy, ix),
707                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
708        iy += 1
709        selection_sizer.Add(self.external_app_selected, (iy, ix),
710                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
711        iy += 1
712        selection_sizer.Add(self.save_to_file, (iy, ix),
713                           (1, 1), wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
714        #contruction the sizer contaning button
715        button_sizer.Add((20, 20), 1, wx.EXPAND|wx.ADJUST_MINSIZE, 0)
716
717        button_sizer.Add(button_close, 0,
718                        wx.LEFT|wx.EXPAND|wx.ADJUST_MINSIZE, 15)
719        button_sizer.Add(button_apply, 0,
720                                wx.LEFT|wx.RIGHT|wx.ADJUST_MINSIZE, 10)
721        vbox.Add(hint_sizer,  0, wx.EXPAND|wx.ALL, 10)
722        vbox.Add(wx.StaticLine(self.panel, -1),  0, wx.EXPAND, 0)
723        vbox.Add(button_sizer, 0 , wx.TOP|wx.BOTTOM, 10)
724        self.SetSizer(vbox)
725       
726    def on_apply(self, event):
727        """
728        Get the user selection and display output to the selected application
729        """
730        if self.flag == 1:
731            self.parent.open_with_localapp(data_inputs=self.data_inputs,
732                                            data_outputs=self.data_outputs)
733        elif self.flag == 2:
734            self.parent.open_with_externalapp(data=self.data, 
735                                           file_name=self.file_name,
736                                           details=self.details)
737    def on_close(self, event):
738        """
739        close the Window
740        """
741        self.Close()
742       
743    def onselect(self, event=None):
744        """
745        Receive event and display data into third party application
746        or save data to file.
747       
748        """
749        if self.save_to_file.GetValue():
750            reader, ext = os.path.splitext(self.file_name)
751            path = None
752            location = os.getcwd()
753            if self.parent is not None: 
754                location = os.path.dirname(self.file_name)
755                dlg = wx.FileDialog(self, "Save Project file",
756                            location, self.file_name, ext, wx.SAVE)
757                path = None
758                if dlg.ShowModal() == wx.ID_OK:
759                    path = dlg.GetPath()
760                dlg.Destroy()
761                if path != None:
762                    if self.parent is not None and  self.data is not None:
763                        self.parent.write_batch_tofile(data=self.data, 
764                                               file_name=path,
765                                               details=self.details)
766        if self.local_app_selected.GetValue():
767            self.flag = 1
768        else:
769            self.flag = 2
770        return self.flag
771   
772 
773       
774if __name__ == "__main__":
775    app = wx.App()
776   
777    try:
778        data = {}
779        j = 0
780        for i in range(4):
781            j += 1
782            data["index"+str(i)] = [i/j, i*j, i, i+j]
783           
784        frame = GridFrame(data_outputs=data, data_inputs=data)
785        frame.Show(True)
786    except:
787        print sys.exc_value
788       
789    app.MainLoop()
Note: See TracBrowser for help on using the repository browser.