source: sasview/sansguiframe/src/sans/guiframe/data_processor.py @ 83eb1b52

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 83eb1b52 was 83eb1b52, checked in by Gervaise Alina <gervyh@…>, 13 years ago

modify batch dialog to frame window

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