Ticket #1138: gGridEditors.py

File gGridEditors.py, 10.0 kB (added by gary, 6 months ago)

Preliminary Version of Classes for GridDateEditor?

Line 
1 """Grid Editors
2
3 20080131 - GNT
4 """
5
6 import wx
7 import dabo
8 import datetime
9 import time
10 import locale
11 import sys
12 dabo.ui.loadUI("wx")
13 #Todo: I still haven't got the Tool Tip showing for the control.
14
15 # I'm unsure of how to import this as dabo.ui.dDateTextBox.CalPanel is not available.  Coppied and Pasted here, with some minor changes:
16 class CalPanel(dabo.ui.dPanel):
17     def __init__(self, parent, pos=None, dt=None, ctrl=None ):
18         if dt is None:
19             self.date = datetime.date.today()
20         else:
21             self.date = dt
22         self.ctrl = ctrl
23         super(CalPanel, self).__init__(parent, pos=pos)
24        
25    
26     def afterInit(self):
27         """ Create the calendar control, and resize this panel
28         to the calendar's size.
29         """
30         self.cal = dabo.ui.dCalendar(self, Position=(5, 5))
31         self.cal.Date = self.date
32         self.cal.bindEvent(dabo.dEvents.Hit, self.onCalSelection)
33         self.cal.bindEvent(dabo.dEvents.KeyChar, self.onCalKey)
34         wd, ht = self.cal.Size
35         self.Size = (wd+10, ht+10)
36         self.BackColor = (192, 192, 0)
37         self.cal.Visible = True
38        
39        
40     def onCalSelection(self, evt):
41         if self.ctrl is not None:
42             self.ctrl.setDate(self.cal.Date)
43             self.ctrl.setFocus()
44         self.Visible = False
45    
46    
47     def onCalKey(self, evt):
48         if evt.keyCode == wx.WXK_ESCAPE:
49             evt.Continue = False
50             if self.ctrl is not None:
51                 self.ctrl.setFocus()
52             self.Visible = False
53
54
55
56 class GridDateTextBox(dabo.ui.dDateTextBox):
57         def showCalendar(self):
58         if self.ReadOnly:
59             # ignore
60             return
61         availHt = self.Parent.Parent.Bottom - self.Bottom
62         try:
63             self.calPanel.cal.Date = self.Value
64         except:
65             self.calPanel = CalPanel(self.Parent, dt=self.Value, ctrl=self)
66         cp = self.calPanel
67         cp.Position = (self.Left, self.Bottom)
68         if self.Bottom + cp.Height > self.Parent.Parent.Bottom:
69             # Maybe we should move it above
70             if cp.Height <= self.Top:
71                 cp.Bottom = self.Top
72             else:
73                 # We can't fit it cleanly, so try to fit as much as possible
74                 cp.Top = max(0, (self.Parent.Parent.Height - cp.Height) )
75         if self.Left + cp.Width > self.Parent.Parent.Right:
76             # Try moving it to the left
77             cp.Left = max(0, (self.Parent.Parent.Width - cp.Width) )
78         cp.Visible = True
79         cp.bringToFront()
80         # Commented out so that the grid control will receive the update from the Calendar
81         # For some reaons the application crashes when the Cal losses focus and the focus
82         #  doesn't return to the control.  I might need to execute this line but pass to the
83         #  control the "End Edit" function from the GridDataEditor.
84         #  Now it appears this doesn't work at all? Correction:  Seems to die when editing
85         #  a bizobj DataSource?
86         cp.setFocus()
87
88 class GridDateEditor(wx.grid.PyGridCellEditor):
89     def __init__(self, *args, **kwargs):
90         dabo.infoLog.write("GridDateEditor: Init ")
91         dabo.infoLog.write(str(args))
92         dabo.infoLog.write(str(kwargs))
93
94                 super(GridDateEditor, self).__init__(*args, **kwargs)
95
96     def Create(self, parent, id, evtHandler, *args, **kwargs):
97         dabo.infoLog.write("GridDateEditor: Create")
98         dabo.infoLog.write(str(args))
99         dabo.infoLog.write(str(kwargs))
100         control = GridDateTextBox(parent=parent, id=id)
101         self.control = control
102
103         self.SetControl(self.control)
104         if evtHandler:
105             self.control.PushEventHandler(evtHandler)
106 #       super(GridDateEditor, self).Create(parent, id, evtHandler)
107
108     def Clone(self):
109         return self.__class__()
110
111     def SetParameters(self, paramStr):
112         dabo.infoLog.write("GridDateEditor: SetParameters: %s" % paramStr)
113         #self.control.Choices = eval(paramStr)
114
115     def BeginEdit(self, row, col, grid):
116         dabo.infoLog.write("GridDateEditor: BeginEdit (%d,%d)" % (row, col))
117         self.value = grid.GetTable().GetValue(row, col)
118        
119                 #datetime.datetime.fromtimestamp(time.mktime(time.strptime(mytime, time_format)))
120                
121         try:
122                 try:
123                         timeValue = time.strptime(self.value, self.DateFormat)
124                     except ValueError:
125                             dabo.infoLog.write("GridDateEditor: Control Text does not Match Date Format")
126                             #Take our best Guess
127                             dabo.infoLog.write("GridDateEditor: Guessing Time Format")
128                             try:
129                                     timeValue = self.control.strToDate(self.value).timetuple()
130                             except:
131                                     # Still No Luck, default to today
132                                     dabo.infoLog.write("GridDateEditor: %s" %(str(sys.exc_info()[0])))
133                                     dabo.infoLog.write("GridDateEditor: Setting Unknown Control Value to Today")
134                                     timeValue = datetime.date.today().timetuple()
135                            
136             dateValue = datetime.date(timeValue[0], timeValue[1], timeValue[2])
137             self.control.Value = dateValue
138
139         except ValueError, vError:
140             dabo.infoLog.write("GridDateEditor: ValueError in BeginEdit: " + str(vError))
141            
142         self.control.SetFocus()
143
144     def EndEdit(self, row, col, grid):
145             print "End Control Focus"
146         changed = False
147         v = self.control.Value.strftime(self.DateFormat)
148        
149         if v != self.value:
150             changed = True
151         if changed:
152             grid.GetTable().SetValue(row, col, v)
153             # I don't think the DateTextBox handles an empty value?
154         #self.value = ""
155         #self.control.Value = self.value
156         return changed
157
158     def Reset(self):
159         self.control.Value = self.value
160
161 #   def SetSize(self, rectorig):
162 #       dabo.infoLog.write("GridDateEditor: SetSize: %s" % rectorig)
163 #       dabo.infoLog.write("GridDateEditor: type of rectorig: %s" % type(rectorig))
164 # #         rect = wx.Rect(rectorig)
165 # #         dabo.infoLog.write("GridDateEditor RECT: %s" % rect)
166 #       super(GridDateEditor, self).SetSize(rectorig)
167
168     def IsAcceptedKey(self, key):
169         return true
170
171         #Properties
172     def _getDateFormat(self):
173                 # Get the date format - Make it up if none is given using the system locale
174                 if hasattr(self, "_dateFormat"):
175                 return self._dateFormat
176         else:
177                         #dateFormat = locale.nl_langinfo(locale.D_FMT) # %d/%m/%y
178                         #pos = dateFormat.find("%")+1
179                         #date1 = dateFormat[pos]
180                         #pos = dateFormat.find("%", pos)+1
181                         #date2 = dateFormat[pos]
182                         #pos = dateFormat.find("%", pos)+1
183                         #date3 = dateFormat[pos]
184                         #return "%" + date1 + "-%" + date2 + "-%" + date3
185                         return "%Y-%m-%d"
186        
187     def _setDateFormat(self, val):
188             #Todo: Check format is valid
189         self._dateFormat = val
190     DateFormat = property(_getDateFormat, _setDateFormat, None,
191             "Get or Set the Date Format String for this Control.")
192
193
194
195
196 class _dGrid_test(dabo.ui.dGrid):
197     def initProperties(self):
198         self.DataSet = [
199                 {"name" : "Ed Leafe", "age" : 49, "coder" :  True, "color": "2008-10-10"},
200                 {"name" : "Paul McNett", "age" : 37, "coder" :  True, "color": "11-10-2008"},
201                 {"name" : "Ted Roche", "age" : 48, "coder" :  True, "color": "2008-10-12"},
202                 {"name" : "Derek Jeter", "age": 32 , "coder" :  False, "color": "white"},
203                 {"name" : "Halle Berry", "age" : 38, "coder" :  False, "color": "orange"},
204                 {"name" : "Steve Wozniak", "age" : 56, "coder" :  True, "color": "yellow"},
205                 {"name" : "LeBron James", "age" : 22, "coder" :  False, "color": "gold"},
206                 {"name" : "Madeline Albright", "age" : 69, "coder" :  False, "color": "red"}]
207         self.Width = 360
208         self.Height = 150
209         self.Editable = True
210         #self.Sortable = False
211         #self.Searchable = False
212
213
214     def afterInit(self):
215         self.super()
216
217         self.addColumn(Name="Geek", DataField="coder", Caption="Geek?",
218                 Order=10, DataType="bool", Width=60, Sortable=False,
219                 Searchable=False, Editable=True, HeaderFontBold=False)
220
221         col = dabo.ui.dColumn(self, Name="Person", Order=20, DataField="name",
222                 DataType="string", Width=200, Caption="Celebrity Name",
223                 Sortable=True, Searchable=True, Editable=True, Expand=False)
224         self.addColumn(col)
225
226         col.HeaderFontItalic = True
227         col.HeaderBackColor = "orange"
228         col.HeaderVerticalAlignment = "Top"
229         col.HeaderHorizontalAlignment = "Left"
230
231         self.addColumn(Name="Age", Order=30, DataField="age",
232                 DataType="integer", Width=40, Caption="Age",
233                 Sortable=True, Searchable=True, Editable=True)
234
235         col = dabo.ui.dColumn(self, Name="Color", Order=40, DataField="color",
236                 DataType="string", Width=40, Caption="Favorite Color",
237                 Sortable=True, Searchable=True, Editable=True, Expand=False)
238         self.addColumn(col)
239
240         #col.ListEditorChoices = dabo.dColors.colors
241         #col.CustomEditorClass = gGridEditors.GridListEditor
242         col.CustomEditorClass = GridDateEditor
243
244         col.HeaderVerticalAlignment = "Bottom"
245         col.HeaderHorizontalAlignment = "Right"
246         col.HeaderForeColor = "brown"
247
248         self.RowLabels = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"]
249         #self.ShowRowLabels = True
250
251 if __name__ == '__main__':
252     class TestForm(dabo.ui.dForm):
253         def afterInit(self):
254             self.BackColor = "khaki"
255             g = self.grid = _dGrid_test(self, RegID="sampleGrid")
256             self.Sizer.append(g, 1, "x", border=40, borderSides="all")
257             self.Sizer.appendSpacer(10)
258             gsz = dabo.ui.dGridSizer(HGap=50)
259
260             chk = dabo.ui.dCheckBox(self, Caption="Edit Table", RegID="geekEdit",
261                     DataSource="sampleGrid", DataField="Editable")
262             chk.refresh()
263             gsz.append(chk, row=0, col=0)
264
265             chk = dabo.ui.dCheckBox(self, Caption="Show Row Labels",
266                     RegID="showRowLabels", DataSource="sampleGrid",
267                     DataField="ShowRowLabels")
268             gsz.append(chk, row=1, col=0)
269             chk.refresh()
270
271             chk = dabo.ui.dCheckBox(self, Caption="Allow Multiple Selection",
272                     RegID="multiSelect", DataSource="sampleGrid",
273                     DataField="MultipleSelection")
274             chk.refresh()
275             gsz.append(chk, row=2, col=0)
276
277             radSelect = dabo.ui.dRadioList(self, Choices=["Row", "Col", "Cell"],
278                     ValueMode="string", Caption="Sel Mode", BackColor=self.BackColor,
279                     DataSource="sampleGrid", DataField="SelectionMode", RegID="radSelect")
280             radSelect.refresh()
281             gsz.append(radSelect, row=0, col=1, rowSpan=3)
282
283             self.Sizer.append(gsz, halign="Center", border=10)
284             gsz.setColExpand(True, 1)
285             self.layout()
286
287             self.fitToSizer(20,20)
288
289
290     app = dabo.dApp(MainFormClass=TestForm)
291     app.setup()
292     app.MainForm.radSelect.setFocus()
293     app.start()