ElementsDatabaseEditor.py 11.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#MDANSE : Molecular Dynamics Analysis for Neutron Scattering Experiments
#------------------------------------------------------------------------------------------
#Copyright (C)
#2015- Eric C. Pellegrini Institut Laue-Langevin
#BP 156
#6, rue Jules Horowitz
#38042 Grenoble Cedex 9
#France
#pellegrini[at]ill.fr
#goret[at]ill.fr
#aoun[at]ill.fr
#
#This library is free software; you can redistribute it and/or
#modify it under the terms of the GNU Lesser General Public
#License as published by the Free Software Foundation; either
#version 2.1 of the License, or (at your option) any later version.
#
#This library is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
#Lesser General Public License for more details.
#
#You should have received a copy of the GNU Lesser General Public
#License along with this library; if not, write to the Free Software
#Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

''' 
Created on Apr 14, 2015

:author: Eric C. Pellegrini
'''

import os

import wx
import wx.grid as wxgrid

38
from MDANSE import ELEMENTS
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
from MDANSE.Core.Singleton import Singleton

class PropertyDialog(wx.Dialog):
    """
    This class pops up a dialog that prompts the user for registering a new property in the database.
    """
        
    def __init__(self,*args,**kwargs):
        """
        The constructor.
        """

        # The base class constructor
        wx.Dialog.__init__(self,*args,**kwargs)
        
        self.Center()
        
        panel = wx.Panel(self,wx.ID_ANY)
        
        staticLabel0 = wx.StaticText(panel, -1, "Enter property settings")
        
        subPanel = wx.Panel(panel,wx.ID_ANY)
        staticLabel1 = wx.StaticText(subPanel, wx.ID_ANY, "Name")
        self.name = wx.TextCtrl(subPanel, wx.ID_ANY)        
        staticLabel2 = wx.StaticText(subPanel, wx.ID_ANY, "Default value")
        self.propertyType = wx.ComboBox(subPanel, id = wx.ID_ANY, choices=ELEMENTS._TYPES.keys(), style=wx.CB_READONLY)
        
        staticLine = wx.StaticLine(self, wx.ID_ANY)

        buttonPanel = wx.Panel(self,wx.ID_ANY)
        ok = wx.Button(buttonPanel, wx.ID_OK, "OK")
        ok.SetDefault()
        cancel = wx.Button(buttonPanel, wx.ID_CANCEL, "Cancel")

        panelSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer.Add(staticLabel0, 0, wx.ALL|wx.ALIGN_LEFT, 5)
        subsizer = wx.GridBagSizer(5,5)
        subsizer.AddGrowableCol(1)
        subsizer.Add(staticLabel1,pos=(0,0),flag=wx.ALIGN_CENTER_VERTICAL)
        subsizer.Add(self.name   ,pos=(0,1),flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        subsizer.Add(staticLabel2,pos=(1,0),flag=wx.ALIGN_CENTER_VERTICAL)
        subsizer.Add(self.propertyType,pos=(1,1),flag=wx.ALIGN_CENTER_VERTICAL|wx.EXPAND)
        subPanel.SetSizer(subsizer)
        panelSizer.Add(subPanel, 0, wx.ALL|wx.EXPAND, 5)
        panel.SetSizer(panelSizer)

        btnsizer = wx.StdDialogButtonSizer()
        btnsizer.AddButton(cancel)
        btnsizer.AddButton(ok)
        btnsizer.Realize()        
        buttonPanel.SetSizer(btnsizer)

        dlgsizer = wx.BoxSizer(wx.VERTICAL)
        dlgsizer.Add(panel, 1, wx.ALL|wx.EXPAND, 5)
        dlgsizer.Add(staticLine, 0, wx.ALL|wx.EXPAND, 5)
        dlgsizer.Add(buttonPanel, 0, wx.ALL|wx.ALIGN_RIGHT|wx.EXPAND, 5)
        
        # Bind the top sizer to the dialog.
        self.SetSizer(dlgsizer)
98
                          
99
100
101
102
    def GetValue(self, event=None):
        """
        Handler called when the user clicks on the OK button of the property dialog.
        """
103
                
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
        pname = str(self.name.GetValue().strip())
        
        pdefault = str(self.propertyType.GetValue())
                                
        return pname,pdefault
 
class Database(wxgrid.PyGridTableBase):
    
    __metaclass__ = Singleton
                                    
    def GetColLabelValue(self, col):
        
        return "%s" % ELEMENTS.properties[col]

    def GetNumberCols(self):
        return ELEMENTS.nProperties

    def GetNumberRows(self):
        return ELEMENTS.nElements

    def GetRowLabelValue(self, row):

        return ELEMENTS.elements[row]

    def GetValue(self, row, col):
                    
        return ELEMENTS[ELEMENTS.elements[row],ELEMENTS.properties[col]]
    
    def SetValue(self, row, col, val):
        
        ELEMENTS[ELEMENTS.elements[row],ELEMENTS.properties[col]] = val                                           

    def add_column(self, pname,pdefault):
        
        ELEMENTS.add_property(pname, pdefault)
        
        self.notify_grid(wxgrid.GRIDTABLE_NOTIFY_COLS_APPENDED, 1)
    
    def add_row(self, ename):
                                
        ELEMENTS.add_element(ename)
                                        
        self.notify_grid(wxgrid.GRIDTABLE_NOTIFY_ROWS_APPENDED, 1)
        
    def notify_grid(self, msg, count):
        "Notifies the grid of the message and the affected count."
        
        tbl_msg = wxgrid.GridTableMessage(self, msg, count)                      
         
        self.GetView().ProcessTableMessage(tbl_msg)
        
    def saveas(self,fmt,filename):
        
        ELEMENTS.export(fmt,filename)
        
    def save(self, fmt="csv", filename=None):
        
        ELEMENTS.save()                    

class ElementsDatabaseEditor(wx.Frame):
    
    def __init__(self, parent):
        """
        The constructor.
        :Parameters:
            #. parent  (wx window): the parent window.
        """
                
        wx.Frame.__init__(self, parent, wx.ID_ANY, title="Elements database editor", style=wx.DEFAULT_FRAME_STYLE|wx.RESIZE_BORDER)
                
        self._database = Database()
        
        self.build_dialog()
        
        self.build_menu()
        
        self.CenterOnParent()
        
    def build_dialog(self):
        
        mainPanel = wx.Panel(self,wx.ID_ANY)
                
        mainSizer = wx.BoxSizer(wx.VERTICAL)
  
        # The wx grid that will store the database.            
        self._grid = wxgrid.Grid(mainPanel)
  
        # The grid style is set. This will be a standard text editor.
        self._grid.SetDefaultEditor(wxgrid.GridCellTextEditor())
                                                    
        self._grid.SetTable(self._database)
          
        self._grid.SetDefaultCellBackgroundColour(wx.NamedColour("LIGHT BLUE"))
          
        self._grid.SetColLabelAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
          
        self._grid.SetRowLabelAlignment(wx.ALIGN_LEFT, wx.ALIGN_CENTRE)
  
        self._grid.SetColMinimalAcceptableWidth(100)
          
        self._grid.Bind(wxgrid.EVT_GRID_CELL_CHANGE,self.on_edit_cell)
        self._grid.Bind(wxgrid.EVT_GRID_CELL_RIGHT_CLICK, self.on_show_popup_menu)
        mainSizer.Add(self._grid,1,wx.EXPAND|wx.ALL,5)
                                        
        mainPanel.SetSizer(mainSizer)
        
        self.SetSize((800,400))
        
        self.Bind(wx.EVT_CONTEXT_MENU, self.on_show_popup_menu)

    def build_menu(self):
 
        menubar = wx.MenuBar()
         
        fileMenu = wx.Menu()
         
        saveItem   = fileMenu.Append(wx.ID_ANY, '&Save database\tCtrl+S')
        saveasItem = fileMenu.Append(wx.ID_ANY, '&Save database as ...\tCtrl+Shift+S')        
 
        databaseMenu = wx.Menu()
        addElementItem = databaseMenu.Append(wx.ID_ANY, 'New element')
        addPropertyItem = databaseMenu.Append(wx.ID_ANY, 'New property')
        menubar.Append(databaseMenu, "Database")
                 
        self.Bind(wx.EVT_MENU,self.on_add_element, addElementItem)
        self.Bind(wx.EVT_MENU,self.on_add_property, addPropertyItem)
 
        self.Bind(wx.EVT_MENU,self.on_save_database, saveItem)
        self.Bind(wx.EVT_MENU,self.on_saveas_database, saveasItem)
 
        self.SetMenuBar(menubar)
235
                
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    def on_show_popup_menu(self, event):

        menu = wx.Menu()

        saveItem = menu.Append(wx.ID_ANY, 'Save database')
        saveasItem = menu.Append(wx.ID_ANY, 'Save database as ...')        
        menu.AppendSeparator()

        addElementItem = menu.Append(wx.ID_ANY, 'New element')
        addPropertyItem = menu.Append(wx.ID_ANY, 'New property')

        self.Bind(wx.EVT_MENU,self.on_add_element,addElementItem)
        self.Bind(wx.EVT_MENU,self.on_add_property,addPropertyItem)

        self.Bind(wx.EVT_MENU,self.on_save_database, saveItem)
        self.Bind(wx.EVT_MENU,self.on_saveas_database, saveasItem)

        self.PopupMenu(menu)

        menu.Destroy()
                        
    def on_edit_cell(self,event):
        
        event.Skip()
        
        self._grid.Refresh()

    def on_add_element(self, event):
        """
        Handler called when the user add new elements to the database.
        """
 
        d = wx.TextEntryDialog(self,"Enter element id","add element")
 
        # If the new element dialog is closed by clicking on OK. 
        if d.ShowModal() == wx.ID_CANCEL:
            return
 
274
275
        # Get rid of wxpython unicode string formatting
        ename = str(d.GetValue())
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
                         
        if not ename:
            return
                                 
        self._database.add_row(ename)
         
    def on_add_property(self, message):
        """
        Handler called when the user add a property to the database.
        """
 
        d = PropertyDialog(self,title="Add property",size=(400,160))
 
        if d.ShowModal() == wx.ID_CANCEL:
            return
 
        pname,pdefault = d.GetValue()
                     
        if not pname:
295
296
297
298
            return
        
        # Get rid of wxpython unicode string formatting
        pname = str(pname)
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
                                     
        self._database.add_column(pname,pdefault)      
  
    def on_save_database(self,event=None):
        """
        Handler called when the user saves the database to its defaut location.
        """
 
        d = wx.MessageDialog(None, 'This will overwrite your database. Continue ?', 'Question', wx.YES_NO|wx.YES_DEFAULT|wx.ICON_WARNING)
                 
        if d.ShowModal() == wx.ID_NO:
            return
         
        self._database.save()
         
    def on_saveas_database(self,event=None):
        """
        Handler called when the user saves the database to any location.
        """
 
        d = wx.FileDialog(self,
                          message="Save database as ...",
                          defaultDir=os.getcwd(),
                          defaultFile="elements_database",
                          wildcard="XML file (*.xml)|*.xml|CSV file (*.csv)|*.csv",
                          style=wx.SAVE|wx.FD_OVERWRITE_PROMPT)
 
        if d.ShowModal() == wx.ID_CANCEL:
            return
         
        filename = str(d.GetPath())
         
        if d.GetFilterIndex() == 0:
            fmt = 'xml'
             
        elif d.GetFilterIndex() == 1:
            fmt = 'csv'
                     
        self._database.saveas(fmt,filename)
                  
if __name__ == "__main__":
    app = wx.App(False)
    f = ElementsDatabaseEditor(None)
    f.Show()
    app.MainLoop()