/[thuban]/trunk/thuban/Thuban/UI/classifier.py
ViewVC logotype

Diff of /trunk/thuban/Thuban/UI/classifier.py

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 473 by jonathan, Wed Mar 5 18:39:45 2003 UTC revision 813 by jonathan, Mon May 5 15:04:21 2003 UTC
# Line 1  Line 1 
1  # Copyright (c) 2001 by Intevation GmbH  # Copyright (c) 2001, 2003 by Intevation GmbH
2  # Authors:  # Authors:
3  # Jonathan Coles <[email protected]>  # Jonathan Coles <[email protected]>
4  #  #
# Line 18  from wxPython.wx import * Line 18  from wxPython.wx import *
18  from wxPython.grid import *  from wxPython.grid import *
19    
20  from Thuban import _  from Thuban import _
 from Thuban.common import *  
21  from Thuban.UI.common import *  from Thuban.UI.common import *
22    
23  from Thuban.Model.classification import *  from Thuban.Model.classification import *
# Line 27  from Thuban.Model.color import Color Line 26  from Thuban.Model.color import Color
26    
27  from Thuban.Model.layer import Layer, SHAPETYPE_ARC, SHAPETYPE_POLYGON, SHAPETYPE_POINT  from Thuban.Model.layer import Layer, SHAPETYPE_ARC, SHAPETYPE_POLYGON, SHAPETYPE_POINT
28    
29  # widget id's  from Thuban.UI.classgen import ClassGenDialog, ClassGenerator
30  ID_PROPERTY_SELECT = 4010  
31    from dialogs import NonModalDialog
32    
33  ID_CLASS_TABLE = 40011  ID_CLASS_TABLE = 40011
34    
 ID_CLASSIFY_OK = 4001  
 ID_CLASSIFY_CANCEL = 4002  
 ID_CLASSIFY_ADD = 4003  
 ID_CLASSIFY_GENRANGE = 4004  
 ID_CLASSIFY_REMOVE = 4005  
 ID_CLASSIFY_MOVEUP = 4006  
 ID_CLASSIFY_MOVEDOWN = 4007  
35    
36  # table columns  # table columns
37  COL_SYMBOL = 0  COL_VISIBLE = 0
38  COL_VALUE  = 1  COL_SYMBOL  = 1
39  COL_LABEL  = 2  COL_VALUE   = 2
40    COL_LABEL   = 3
41    NUM_COLS    = 4
42    
43  # indices into the client data lists in Classifier.fields  # indices into the client data lists in Classifier.fields
44  FIELD_CLASS = 0  FIELD_CLASS = 0
# Line 56  FIELD_NAME = 2 Line 52  FIELD_NAME = 2
52  import weakref  import weakref
53  class ClassGrid(wxGrid):  class ClassGrid(wxGrid):
54    
55      def __init__(self, parent):  
56        def __init__(self, parent, classifier):
57          """Constructor.          """Constructor.
58    
59          parent -- the parent window          parent -- the parent window
# Line 65  class ClassGrid(wxGrid): Line 62  class ClassGrid(wxGrid):
62                   use for display.                   use for display.
63          """          """
64    
65          wxGrid.__init__(self, parent, ID_CLASS_TABLE, size = (340, 160))          wxGrid.__init__(self, parent, ID_CLASS_TABLE, style = 0)
66          #self.SetTable(ClassTable(fieldData, layer.ShapeType(), self), true)  
67          self.SetSelectionMode(wxGrid.wxGridSelectRows)          self.classifier = classifier
68    
69            self.currentSelection = []
70    
71          EVT_GRID_CELL_LEFT_DCLICK(self, self._OnCellDClick)          EVT_GRID_CELL_LEFT_DCLICK(self, self._OnCellDClick)
72          EVT_GRID_RANGE_SELECT(self, self._OnSelectedRange)          EVT_GRID_RANGE_SELECT(self, self._OnSelectedRange)
73          EVT_GRID_SELECT_CELL(self, self._OnSelectedCell)          EVT_GRID_SELECT_CELL(self, self._OnSelectedCell)
74            EVT_GRID_COL_SIZE(self, self._OnCellResize)
75            EVT_GRID_ROW_SIZE(self, self._OnCellResize)
76    
77          self.currentSelection = []      #def GetCellAttr(self, row, col):
78            #print "GetCellAttr ", row, col
79            #wxGrid.GetCellAttr(self, row, col)
80    
81      def CreateTable(self, clazz, shapeType):      def CreateTable(self, clazz, shapeType, group = None):
82    
83          assert(isinstance(clazz, Classification))          assert isinstance(clazz, Classification)
84    
         self.shapeType = shapeType  
85          table = self.GetTable()          table = self.GetTable()
86          if table is None:          if table is None:
87              self.SetTable(ClassTable(clazz, self.shapeType, self), true)              w = self.GetDefaultColSize() * NUM_COLS \
88          else:                  + self.GetDefaultRowLabelSize()
89              table.Reset(clazz, self.shapeType)              h = self.GetDefaultRowSize() * 4 \
90                    + self.GetDefaultColLabelSize()
91    
92                self.SetDimensions(-1, -1, w, h)
93                self.SetSizeHints(w, h, -1, -1)
94                table = ClassTable(self)
95                self.SetTable(table, True)
96    
97    
98            self.SetSelectionMode(wxGrid.wxGridSelectRows)
99          self.ClearSelection()          self.ClearSelection()
100    
101            table.Reset(clazz, shapeType, group)
102    
103      def GetCurrentSelection(self):      def GetCurrentSelection(self):
104          """Return the currently highlighted rows as an increasing list          """Return the currently highlighted rows as an increasing list
105             of row numbers."""             of row numbers."""
# Line 95  class ClassGrid(wxGrid): Line 107  class ClassGrid(wxGrid):
107          sel.sort()          sel.sort()
108          return sel          return sel
109    
110      def SetCellRenderer(self, row, col):      def GetSelectedRows(self):
111          raise ValueError(_("Must not allow setting of renderer in ClassGrid!"))          return self.GetCurrentSelection()
112    
113        #def SetCellRenderer(self, row, col, renderer):
114            #raise ValueError(_("Must not allow setting of renderer in ClassGrid!"))
115    
116      #      #
117      # [Set|Get]Table is taken from http://wiki.wxpython.org      # [Set|Get]Table is taken from http://wiki.wxpython.org
# Line 128  class ClassGrid(wxGrid): Line 143  class ClassGrid(wxGrid):
143          # if only one thing is selected check if it is the default          # if only one thing is selected check if it is the default
144          # data row, because we can't remove that          # data row, because we can't remove that
145          if len(sel) == 1:          if len(sel) == 1:
146              group = self.GetTable().GetValueAsCustom(sel[0], COL_SYMBOL, None)              #group = self.GetTable().GetValueAsCustom(sel[0], COL_SYMBOL, None)
147                group = self.GetTable().GetClassGroup(sel[0])
148              if isinstance(group, ClassGroupDefault):              if isinstance(group, ClassGroupDefault):
149                  wxMessageDialog(self,                  wxMessageDialog(self,
150                                  "The Default group cannot be removed.",                                  "The Default group cannot be removed.",
# Line 160  class ClassGrid(wxGrid): Line 176  class ClassGrid(wxGrid):
176                  r = self.GetNumberRows() - 1                  r = self.GetNumberRows() - 1
177              self.SelectRow(r)              self.SelectRow(r)
178                    
179    
180        def SelectGroup(self, group, makeVisible = True):
181            if group is None: return
182    
183            assert isinstance(group, ClassGroup)
184    
185            table = self.GetTable()
186    
187            assert table is not None
188    
189            for i in range(table.GetNumberRows()):
190                g = table.GetClassGroup(i)
191                if g is group:
192                    self.SelectRow(i)
193                    if makeVisible:
194                        self.MakeCellVisible(i, 0)
195                    break
196    
197  #  #
198  # XXX: This isn't working, and there is no way to deselect rows wxPython!  # XXX: This isn't working, and there is no way to deselect rows wxPython!
199  #  #
# Line 172  class ClassGrid(wxGrid): Line 206  class ClassGrid(wxGrid):
206  #                                  sel = False))  #                                  sel = False))
207    
208      def _OnCellDClick(self, event):      def _OnCellDClick(self, event):
209          """Handle a double on a cell."""          """Handle a double click on a cell."""
210    
211          r = event.GetRow()          r = event.GetRow()
212          c = event.GetCol()          c = event.GetCol()
         if c == COL_SYMBOL:  
             group = self.GetTable().GetValueAsCustom(r, c, None)  
             prop = group.GetProperties()  
213    
214              # get a new ClassGroupProperties object and copy the          if c == COL_SYMBOL:
215              # values over to our current object              self.classifier.EditSymbol(r)
216              propDlg = SelectPropertiesDialog(NULL, prop, self.shapeType)          else:
217              if propDlg.ShowModal() == wxID_OK:              event.Skip()
                 new_prop = propDlg.GetClassGroupProperties()  
                 prop.SetProperties(new_prop)  
                 self.Refresh()  
             propDlg.Destroy()  
218    
219      #      #
220      # _OnSelectedRange() and _OnSelectedCell() were borrowed      # _OnSelectedRange() and _OnSelectedCell() were borrowed
# Line 214  class ClassGrid(wxGrid): Line 241  class ClassGrid(wxGrid):
241          #self.ConfigureForSelection()          #self.ConfigureForSelection()
242          event.Skip()          event.Skip()
243    
244        def _OnCellResize(self, event):
245            self.FitInside()
246    
247  class ClassTable(wxPyGridTableBase):  class ClassTable(wxPyGridTableBase):
248      """Represents the underlying data structure for the grid."""      """Represents the underlying data structure for the grid."""
249    
250      NUM_COLS = 3      __col_labels = [_("Visible"), _("Symbol"), _("Value"), _("Label")]
251    
     __col_labels = [_("Symbol"), _("Value"), _("Label")]  
252    
253      def __init__(self, clazz, shapeType, view = None):      def __init__(self, view = None):
254        #def __init__(self, clazz, shapeType, view = None):
255          """Constructor.          """Constructor.
256    
257          shapeType -- the type of shape that the layer uses          shapeType -- the type of shape that the layer uses
# Line 230  class ClassTable(wxPyGridTableBase): Line 260  class ClassTable(wxPyGridTableBase):
260          """          """
261    
262          wxPyGridTableBase.__init__(self)          wxPyGridTableBase.__init__(self)
         self.SetView(view)  
         self.tdata = []  
263    
264          self.Reset(clazz, shapeType)          assert len(ClassTable.__col_labels) == NUM_COLS
265    
266            self.clazz = None
267            self.__colAttr = {}
268    
269      def Reset(self, clazz, shapeType):          self.SetView(view)
270    
271        def Reset(self, clazz, shapeType, group = None):
272          """Reset the table with the given data.          """Reset the table with the given data.
273    
274          This is necessary because wxWindows does not allow a grid's          This is necessary because wxWindows does not allow a grid's
# Line 249  class ClassTable(wxPyGridTableBase): Line 282  class ClassTable(wxPyGridTableBase):
282          shapeType -- the type of shape that the layer uses          shapeType -- the type of shape that the layer uses
283          """          """
284    
285          assert(isinstance(clazz, Classification))          assert isinstance(clazz, Classification)
286    
287          self.GetView().BeginBatch()          self.GetView().BeginBatch()
288    
289          self.clazz = clazz          self.fieldType = clazz.GetFieldType()
290          self.shapeType = shapeType          self.shapeType = shapeType
         self.renderer = ClassRenderer(self.shapeType)  
291    
292          old_len = len(self.tdata)          self.SetClassification(clazz, group)
293            self.__Modified(-1)
294    
295          self.tdata = []          self.__colAttr = {}
296    
297            attr = wxGridCellAttr()
298            attr.SetEditor(wxGridCellBoolEditor())
299            attr.SetRenderer(wxGridCellBoolRenderer())
300            attr.SetAlignment(wxALIGN_CENTER, wxALIGN_CENTER)
301            self.__colAttr[COL_VISIBLE] = attr
302    
303            attr = wxGridCellAttr()
304            attr.SetRenderer(ClassRenderer(self.shapeType))
305            attr.SetReadOnly()
306            self.__colAttr[COL_SYMBOL] = attr
307    
308            self.GetView().EndBatch()
309            self.GetView().FitInside()
310    
311        def GetClassification(self):
312            return self.clazz
313    
314        def SetClassification(self, clazz, group = None):
315    
316            self.GetView().BeginBatch()
317    
318            old_len = self.GetNumberRows()
319    
320            row = -1
321            self.clazz = clazz
322    
323            self.__NotifyRowChanges(old_len, self.GetNumberRows())
324    
325          #          #
326          # copy the data out of the classification and into our          # XXX: this is dead code at the moment
         # array  
327          #          #
328          for p in self.clazz:          if row > -1:
329              np = copy.copy(p)              self.GetView().ClearSelection()
330              self.__SetRow(-1, np)              self.GetView().SelectRow(row)
331                self.GetView().MakeCellVisible(row, 0)
332    
333            self.__Modified()
334    
   
         self.__Modified(False)  
335    
         self.__NotifyRowChanges(old_len, len(self.tdata))  
336          self.GetView().EndBatch()          self.GetView().EndBatch()
337            self.GetView().FitInside()
338    
339      def __NotifyRowChanges(self, curRows, newRows):      def __NotifyRowChanges(self, curRows, newRows):
340          #          #
# Line 285  class ClassTable(wxPyGridTableBase): Line 346  class ClassTable(wxPyGridTableBase):
346                          wxGRIDTABLE_NOTIFY_ROWS_APPENDED,                          wxGRIDTABLE_NOTIFY_ROWS_APPENDED,
347                          newRows - curRows)    # how many                          newRows - curRows)    # how many
348              self.GetView().ProcessTableMessage(msg)              self.GetView().ProcessTableMessage(msg)
349                self.GetView().FitInside()
350          elif newRows < curRows:          elif newRows < curRows:
351              msg = wxGridTableMessage(self,              msg = wxGridTableMessage(self,
352                          wxGRIDTABLE_NOTIFY_ROWS_DELETED,                          wxGRIDTABLE_NOTIFY_ROWS_DELETED,
353                          curRows - newRows,    # position                          curRows,              # position
354                          curRows - newRows)    # how many                          curRows - newRows)    # how many
355              self.GetView().ProcessTableMessage(msg)              self.GetView().ProcessTableMessage(msg)
356                self.GetView().FitInside()
357    
358    
359      def __SetRow(self, row, group):      def __SetRow(self, row, group):
360          """Set a row's data to that of the group.          """Set a row's data to that of the group.
361    
362          row -- if row is -1 or greater than the current number of rows          The table is considered modified after this operation.
363                 then group is appended to the end.  
364            row -- if row is < 0 'group' is inserted at the top of the table
365                   if row is >= GetNumberRows() or None 'group' is append to
366                        the end of the table.
367                   otherwise 'group' replaces row 'row'
368          """          """
369    
370          # either append or replace          # either append or replace
371          if row == -1 or row >= self.GetNumberRows():          if row is None or row >= self.GetNumberRows():
372              self.tdata.append(group)              self.clazz.AppendGroup(group)
373            elif row < 0:
374                self.clazz.InsertGroup(0, group)
375          else:          else:
376              self.tdata[row] = group              if row == 0:
377                    self.clazz.SetDefaultGroup(group)
378                else:
379                    self.clazz.ReplaceGroup(row - 1, group)
380    
381          self.__Modified()          self.__Modified()
382    
# Line 314  class ClassTable(wxPyGridTableBase): Line 387  class ClassTable(wxPyGridTableBase):
387      def GetRowLabelValue(self, row):      def GetRowLabelValue(self, row):
388          """Return the label for the given row."""          """Return the label for the given row."""
389    
390          group = self.tdata[row]          if row == 0:
391          if isinstance(group, ClassGroupDefault):   return _("Default")              return _("Default")
392          if isinstance(group, ClassGroupSingleton): return _("Singleton")          else:
393          if isinstance(group, ClassGroupRange):     return _("Range")              group = self.clazz.GetGroup(row - 1)
394          if isinstance(group, ClassGroupMap):       return _("Map")              if isinstance(group, ClassGroupDefault):   return _("Default")
395                if isinstance(group, ClassGroupSingleton): return _("Singleton")
396                if isinstance(group, ClassGroupRange):     return _("Range")
397                if isinstance(group, ClassGroupMap):       return _("Map")
398    
399          assert(False) # shouldn't get here          assert False # shouldn't get here
400          return _("")          return ""
401    
402      def GetNumberRows(self):      def GetNumberRows(self):
403          """Return the number of rows."""          """Return the number of rows."""
404          return len(self.tdata)          if self.clazz is None:
405                return 0
406    
407            return self.clazz.GetNumGroups() + 1 # +1 for default group
408    
409      def GetNumberCols(self):      def GetNumberCols(self):
410          """Return the number of columns."""          """Return the number of columns."""
411          return self.NUM_COLS          return NUM_COLS
412    
413      def IsEmptyCell(self, row, col):      def IsEmptyCell(self, row, col):
414          """Determine if a cell is empty. This is always false."""          """Determine if a cell is empty. This is always false."""
# Line 347  class ClassTable(wxPyGridTableBase): Line 426  class ClassTable(wxPyGridTableBase):
426          """          """
427    
428          self.SetValueAsCustom(row, col, None, value)          self.SetValueAsCustom(row, col, None, value)
         self.__Modified()  
429                
430      def GetValueAsCustom(self, row, col, typeName):      def GetValueAsCustom(self, row, col, typeName):
431          """Return the object that is used to represent the given          """Return the object that is used to represent the given
# Line 356  class ClassTable(wxPyGridTableBase): Line 434  class ClassTable(wxPyGridTableBase):
434          typeName -- unused, but needed to overload wxPyGridTableBase          typeName -- unused, but needed to overload wxPyGridTableBase
435          """          """
436    
437          group = self.tdata[row]          if row == 0:
438                group = self.clazz.GetDefaultGroup()
439            else:
440                group = self.clazz.GetGroup(row - 1)
441    
442    
443            if col == COL_VISIBLE:
444                return group.IsVisible()
445    
446          if col == COL_SYMBOL:          if col == COL_SYMBOL:
447              return group              return group.GetProperties()
448    
449          if col == COL_LABEL:          if col == COL_LABEL:
450              return group.GetLabel()              return group.GetLabel()
451    
452          # col must be COL_VALUE          # col must be COL_VALUE
453          assert(col == COL_VALUE)          assert col == COL_VALUE
454    
455          if isinstance(group, ClassGroupDefault):          if isinstance(group, ClassGroupDefault):
456              return _("DEFAULT")              return _("DEFAULT")
# Line 385  class ClassTable(wxPyGridTableBase): Line 470  class ClassTable(wxPyGridTableBase):
470          value, or of length two if it is a range.          value, or of length two if it is a range.
471          """          """
472    
473          type = self.clazz.GetFieldType()          type = self.fieldType
474    
475          if type == FIELDTYPE_STRING:          if type == FIELDTYPE_STRING:
476              return (value,)              return (value,)
477          elif type == FIELDTYPE_INT or type == FIELDTYPE_DOUBLE:          elif type in (FIELDTYPE_INT, FIELDTYPE_DOUBLE):
478    
479              if type == FIELDTYPE_INT:              if type == FIELDTYPE_INT:
480                    # the float call allows the user to enter 1.0 for 1
481                  conv = lambda p: int(float(p))                  conv = lambda p: int(float(p))
482              else:              else:
483                  conv = lambda p: p                  conv = lambda p: p
# Line 406  class ClassTable(wxPyGridTableBase): Line 492  class ClassTable(wxPyGridTableBase):
492              # function.              # function.
493              #              #
494              try:              try:
495                  return (conv(Str2Num(value)),)                  return (conv(value),)
496              except ValueError:              except ValueError:
497                  i = value.find('-')                  i = value.find('-')
498                  if i == 0:                  if i == 0:
499                      i = value.find('-', 1)                      i = value.find('-', 1)
500    
501                  return (conv(Str2Num(value[:i])), conv(Str2Num(value[i+1:])))                  return (conv(value[:i]), conv(value[i+1:]))
502    
503          assert(False) # shouldn't get here          assert False  # shouldn't get here
504            return (0,)
505                            
506    
507      def SetValueAsCustom(self, row, col, typeName, value):      def SetValueAsCustom(self, row, col, typeName, value):
# Line 429  class ClassTable(wxPyGridTableBase): Line 516  class ClassTable(wxPyGridTableBase):
516          typeName -- unused, but needed to overload wxPyGridTableBase          typeName -- unused, but needed to overload wxPyGridTableBase
517          """          """
518    
519          assert(col >= 0 and col < self.GetNumberCols())          assert 0 <= col < self.GetNumberCols()
520          assert(row >= 0 and row < self.GetNumberRows())          assert 0 <= row < self.GetNumberRows()
521    
522          group = self.tdata[row]          if row == 0:
523                group = self.clazz.GetDefaultGroup()
524            else:
525                group = self.clazz.GetGroup(row - 1)
526    
527          mod = False          mod = True # assume the data will change
528    
529          if col == COL_SYMBOL:          if col == COL_VISIBLE:
530              self.__SetRow(row, value)              group.SetVisible(value)
531              mod = True          elif col == COL_SYMBOL:
532                group.SetProperties(value)
533            elif col == COL_LABEL:
534                group.SetLabel(value)
535          elif col == COL_VALUE:          elif col == COL_VALUE:
536              if isinstance(group, ClassGroupDefault):              if isinstance(group, ClassGroupDefault):
537                  # not allowed to modify the default value                  # not allowed to modify the default value
# Line 451  class ClassTable(wxPyGridTableBase): Line 544  class ClassTable(wxPyGridTableBase):
544                      dataInfo = self.__ParseInput(value)                      dataInfo = self.__ParseInput(value)
545                  except ValueError:                  except ValueError:
546                      # bad input, ignore the request                      # bad input, ignore the request
547                      pass                      mod = False
548                  else:                  else:
549    
550                        changed = False
551                      ngroup = group                      ngroup = group
552                      props = group.GetProperties()                      props = group.GetProperties()
553    
# Line 464  class ClassTable(wxPyGridTableBase): Line 558  class ClassTable(wxPyGridTableBase):
558                      #                      #
559                      if len(dataInfo) == 1:                      if len(dataInfo) == 1:
560                          if not isinstance(group, ClassGroupSingleton):                          if not isinstance(group, ClassGroupSingleton):
561                              ngroup = ClassGroupSingleton(prop = props)                              ngroup = ClassGroupSingleton(props = props)
562                                changed = True
563                          ngroup.SetValue(dataInfo[0])                          ngroup.SetValue(dataInfo[0])
564                      elif len(dataInfo) == 2:                      elif len(dataInfo) == 2:
565                          if not isinstance(group, ClassGroupRange):                          if not isinstance(group, ClassGroupRange):
566                              ngroup = ClassGroupRange(prop = props)                              ngroup = ClassGroupRange(props = props)
567                                changed = True
568                          ngroup.SetRange(dataInfo[0], dataInfo[1])                          ngroup.SetRange(dataInfo[0], dataInfo[1])
569                      else:                      else:
570                          assert(False)                          assert False
571                            pass
                     ngroup.SetLabel(group.GetLabel())  
   
                     self.__SetRow(row, ngroup)  
   
                     mod = True  
   
572    
573          elif col == COL_LABEL:                      if changed:
574              group.SetLabel(value)                          ngroup.SetLabel(group.GetLabel())
575              mod = True                          self.SetClassGroup(row, ngroup)
576            else:
577                assert False # shouldn't be here
578                pass
579    
580          if mod:          if mod:
581              self.__Modified()              self.__Modified()
582              self.GetView().Refresh()              self.GetView().Refresh()
583    
584      def GetAttr(self, row, col, someExtraParameter):      def GetAttr(self, row, col, someExtraParameter):
585          """Returns the cell attributes"""          """Returns the cell attributes"""
586    
587          attr = wxGridCellAttr()          return self.__colAttr.get(col, wxGridCellAttr()).Clone()
         #attr = wxPyGridTableBase.GetAttr(self, row, col, someExtraParameter)  
   
         if col == COL_SYMBOL:  
             attr.SetRenderer(ClassRenderer(self.shapeType))  
             attr.SetReadOnly()  
   
         return attr  
588    
589      def GetClassGroup(self, row):      def GetClassGroup(self, row):
590          """Return the ClassGroup object representing row 'row'."""          """Return the ClassGroup object representing row 'row'."""
591    
592          return self.GetValueAsCustom(row, COL_SYMBOL, None)          #return self.GetValueAsCustom(row, COL_SYMBOL, None)
593            if row == 0:
594                return self.clazz.GetDefaultGroup()
595            else:
596                return self.clazz.GetGroup(row - 1)
597    
598      def SetClassGroup(self, row, group):      def SetClassGroup(self, row, group):
599          self.SetValueAsCustom(row, COL_SYMBOL, None, group)          self.__SetRow(row, group)
600            self.GetView().Refresh()
601    
602      def __Modified(self, mod = True):      def __Modified(self, mod = True):
603          """Set the modified flag."""          """Adjust the modified flag.
604          self.modified = mod  
605            mod -- if -1 set the modified flag to False, otherwise perform
606                   an 'or' operation with the current value of the flag and
607                   'mod'
608            """
609    
610            if mod == -1:
611                self.modified = False
612            else:
613                self.modified = mod or self.modified
614    
615      def IsModified(self):      def IsModified(self):
616          """True if this table is considered modified."""          """True if this table is considered modified."""
617          return self.modified          return self.modified
618    
619      def DeleteRows(self, pos, numRows = 1):      def DeleteRows(self, pos, numRows = 1):
620          """Deletes 'numRows' beginning at row 'pos'.          """Deletes 'numRows' beginning at row 'pos'.
621    
622          The table is considered modified after this operation.          The row representing the default group is not removed.
623    
624            The table is considered modified if any rows are removed.
625          """          """
626    
627          assert(pos >= 0)          assert pos >= 0
628          old_len = len(self.tdata)          old_len = self.GetNumberRows()
629          for row in range(pos, pos - numRows, -1):          for row in range(pos, pos - numRows, -1):
630              group = self.GetValueAsCustom(row, COL_SYMBOL, None)              group = self.GetClassGroup(row)
631              if not isinstance(group, ClassGroupDefault):              if row != 0:
632                  self.tdata.pop(row)                  self.clazz.RemoveGroup(row - 1)
633                  self.__Modified()                  self.__Modified()
634            
635          if self.IsModified():          if self.IsModified():
636              self.__NotifyRowChanges(old_len, len(self.tdata))              self.__NotifyRowChanges(old_len, self.GetNumberRows())
637    
638      def AppendRows(self, numRows = 1):      def AppendRows(self, numRows = 1):
639          """Append 'numRows' empty rows to the end of the table."""          """Append 'numRows' empty rows to the end of the table.
640    
641          old_len = len(self.tdata)          The table is considered modified if any rows are appended.
642            """
643    
644            old_len = self.GetNumberRows()
645          for i in range(numRows):          for i in range(numRows):
646              np = ClassGroupSingleton()              np = ClassGroupSingleton()
647              self.__SetRow(-1, np)              self.__SetRow(None, np)
             #self.tdata.append([np, np.GetValue(), np.GetLabel()])  
             self.__Modified()  
648    
649          if self.IsModified():          if self.IsModified():
650              self.__NotifyRowChanges(old_len, len(self.tdata))              self.__NotifyRowChanges(old_len, self.GetNumberRows())
651    
652    
653  class Classifier(wxDialog):  ID_PROPERTY_REVERT = 4002
654        ID_PROPERTY_ADD = 4003
655      def __init__(self, parent, layer):  ID_PROPERTY_GENCLASS = 4004
656          wxDialog.__init__(self, parent, -1, _("Classify"),  ID_PROPERTY_REMOVE = 4005
657                            style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)  ID_PROPERTY_MOVEUP = 4006
658    ID_PROPERTY_MOVEDOWN = 4007
659    ID_PROPERTY_TRY = 4008
660    ID_PROPERTY_EDITSYM = 4009
661    ID_PROPERTY_SELECT = 4011
662    ID_PROPERTY_TITLE = 4012
663    ID_PROPERTY_FIELDTEXT = 4013
664    
665    BTN_ADD = 0
666    BTN_EDIT = 1
667    BTN_GEN = 2
668    BTN_UP = 3
669    BTN_DOWN = 4
670    BTN_RM = 5
671    
672    EB_LAYER_TITLE = 0
673    EB_SELECT_FIELD = 1
674    EB_GEN_CLASS = 2
675    
676    class Classifier(NonModalDialog):
677    
678        type2string = {None:             _("None"),
679                       FIELDTYPE_STRING: _("Text"),
680                       FIELDTYPE_INT:    _("Integer"),
681                       FIELDTYPE_DOUBLE: _("Decimal")}
682    
683        def __init__(self, parent, name, layer, group = None):
684            NonModalDialog.__init__(self, parent, name, "")
685    
686            self.__SetTitle(layer.Title())
687    
688          self.layer = layer          self.layer = layer
689    
690          topBox = wxBoxSizer(wxVERTICAL)          self.originalClass = self.layer.GetClassification()
691            field = self.originalClass.GetField()
692            fieldType = self.originalClass.GetFieldType()
693    
694          topBox.Add(wxStaticText(self, -1, _("Layer: %s") % layer.Title()),          self.genDlg = None
695              0, wxALIGN_LEFT | wxALL, 4)  
696          topBox.Add(wxStaticText(self, -1, _("Type: %s") % layer.ShapeType()),          ############################
697              0, wxALIGN_LEFT | wxALL, 4)          # Create the controls
698            #
699    
700          propertyBox = wxBoxSizer(wxHORIZONTAL)          panel = wxPanel(self, -1)
         propertyBox.Add(wxStaticText(self, -1, _("Field: ")),  
             0, wxALIGN_CENTER | wxALL, 4)  
701    
702          self.fields = wxComboBox(self, ID_PROPERTY_SELECT, "",          text_title = wxTextCtrl(panel, ID_PROPERTY_TITLE, layer.Title())
703                                       style = wxCB_READONLY)          #
704            # make field choice box
705            #
706            self.fields = wxChoice(panel, ID_PROPERTY_SELECT,)
707    
708          self.num_cols = layer.table.field_count()          self.num_cols = layer.table.field_count()
709          # just assume the first field in case one hasn't been          # just assume the first field in case one hasn't been
710          # specified in the file.          # specified in the file.
711          self.__cur_field = 0          self.__cur_field = 0
         clazz = layer.GetClassification()  
         field = clazz.GetField()  
712    
713          self.fields.Append("<None>")          self.fields.Append("<None>")
714          self.fields.SetClientData(0, None)  
715            if self.originalClass.GetFieldType() is None:
716                self.fields.SetClientData(0, copy.deepcopy(self.originalClass))
717            else:
718                self.fields.SetClientData(0, None)
719    
720          for i in range(self.num_cols):          for i in range(self.num_cols):
721              type, name, len, decc = layer.table.field_info(i)              type, name, len, decc = layer.table.field_info(i)
# Line 586  class Classifier(wxDialog): Line 723  class Classifier(wxDialog):
723    
724              if name == field:              if name == field:
725                  self.__cur_field = i + 1                  self.__cur_field = i + 1
726                  self.fields.SetClientData(i + 1, clazz)                  self.fields.SetClientData(i + 1,
727                                              copy.deepcopy(self.originalClass))
728              else:              else:
729                  self.fields.SetClientData(i + 1, None)                  self.fields.SetClientData(i + 1, None)
730    
         self.fields.SetSelection(self.__cur_field)  
731    
732          propertyBox.Add(self.fields, 1, wxGROW|wxALL, 4)          self.fieldTypeText = wxStaticText(panel, -1, "")
         EVT_COMBOBOX(self, ID_PROPERTY_SELECT, self._OnFieldSelect)  
733    
734          topBox.Add(propertyBox, 0, wxGROW, 4)          button_gen = wxButton(panel, ID_PROPERTY_GENCLASS, _("Generate Class"))
735    
736          #          button_add = wxButton(panel, ID_PROPERTY_ADD, _("Add"))
737          # Classification data table          button_moveup = wxButton(panel, ID_PROPERTY_MOVEUP, _("Move Up"))
738            button_movedown = wxButton(panel, ID_PROPERTY_MOVEDOWN, _("Move Down"))
739            button_edit = wxButton(panel, ID_PROPERTY_EDITSYM, _("Edit Symbol"))
740            button_remove = wxButton(panel, ID_PROPERTY_REMOVE, _("Remove"))
741    
742    
743            button_try = wxButton(panel, ID_PROPERTY_TRY, _("Try"))
744            button_revert = wxButton(panel, ID_PROPERTY_REVERT, _("Revert"))
745            button_ok = wxButton(panel, wxID_OK, _("OK"))
746            button_ok.SetDefault()
747            button_close = wxButton(panel, wxID_CANCEL, _("Close"))
748    
749            self.classGrid = ClassGrid(panel, self)
750    
751            # calling __SelectField after creating the classGrid fills in the
752            # grid with the correct information
753            self.fields.SetSelection(self.__cur_field)
754            self.__SelectField(self.__cur_field, group = group)
755    
756            ############################
757            # Layout the controls
758          #          #
759    
760          controlBox = wxBoxSizer(wxHORIZONTAL)          topBox = wxBoxSizer(wxVERTICAL)
761          self.classGrid = ClassGrid(self)          panelBox = wxBoxSizer(wxVERTICAL)
762    
763          self.__SetGridTable(self.__cur_field)          sizer = wxBoxSizer(wxHORIZONTAL)
764            sizer.Add(wxStaticText(panel, -1, _("Title: ")),
765                0, wxALIGN_LEFT | wxALL | wxALIGN_CENTER_VERTICAL, 4)
766            sizer.Add(text_title, 1, wxGROW, 0)
767    
768          controlBox.Add(self.classGrid, 1, wxGROW, 0)          panelBox.Add(sizer, 0, wxGROW, 4)
769    
770            panelBox.Add(wxStaticText(panel, -1,
771                                    _("Type: %s") % layer.ShapeType()),
772                0, wxALIGN_LEFT | wxALL, 4)
773    
774            classBox = wxStaticBoxSizer(
775                        wxStaticBox(panel, -1, _("Classification")), wxVERTICAL)
776    
777    
778            sizer = wxBoxSizer(wxHORIZONTAL)
779            sizer.Add(wxStaticText(panel, ID_PROPERTY_FIELDTEXT, _("Field: ")),
780                0, wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL | wxALL, 4)
781            sizer.Add(self.fields, 1, wxGROW | wxALL, 4)
782    
783            classBox.Add(sizer, 0, wxGROW, 4)
784    
785            classBox.Add(self.fieldTypeText, 0,
786                         wxGROW | wxALIGN_LEFT | wxALL | wxADJUST_MINSIZE, 4)
787    
788            controlBox = wxBoxSizer(wxHORIZONTAL)
789          controlButtonBox = wxBoxSizer(wxVERTICAL)          controlButtonBox = wxBoxSizer(wxVERTICAL)
         controlButtonBox.Add(wxButton(self, ID_CLASSIFY_ADD,  
             _("Add")), 0, wxGROW | wxALL, 4)  
         controlButtonBox.Add(wxButton(self, ID_CLASSIFY_GENRANGE,  
             _("Generate Ranges")), 0, wxGROW | wxALL, 4)  
   
         controlButtonBox.Add(wxButton(self, ID_CLASSIFY_MOVEUP,  
             _("Move Up")), 0, wxGROW | wxALL, 4)  
         controlButtonBox.Add(wxButton(self, ID_CLASSIFY_MOVEDOWN,  
             _("Move Down")), 0, wxGROW | wxALL, 4)  
790    
791          controlButtonBox.Add(wxButton(self, ID_CLASSIFY_REMOVE,          controlButtonBox.Add(button_gen, 0, wxGROW|wxALL, 4)
792              _("Remove")), 0, wxGROW | wxALL | wxALIGN_BOTTOM, 4)          controlButtonBox.Add(button_add, 0, wxGROW|wxALL, 4)
793            controlButtonBox.Add(button_moveup, 0, wxGROW|wxALL, 4)
794            controlButtonBox.Add(button_movedown, 0, wxGROW|wxALL, 4)
795            controlButtonBox.Add(button_edit, 0, wxGROW|wxALL, 4)
796            controlButtonBox.Add(60, 20, 0, wxGROW|wxALL|wxALIGN_BOTTOM, 4)
797            controlButtonBox.Add(button_remove, 0, wxGROW|wxALL|wxALIGN_BOTTOM, 4)
798    
799            controlBox.Add(self.classGrid, 1, wxGROW, 0)
800          controlBox.Add(controlButtonBox, 0, wxGROW, 10)          controlBox.Add(controlButtonBox, 0, wxGROW, 10)
         topBox.Add(controlBox, 1, wxGROW, 10)  
   
         EVT_BUTTON(self, ID_CLASSIFY_ADD, self._OnAdd)  
         EVT_BUTTON(self, ID_CLASSIFY_REMOVE, self._OnRemove)  
         EVT_BUTTON(self, ID_CLASSIFY_GENRANGE, self._OnGenRange)  
         EVT_BUTTON(self, ID_CLASSIFY_MOVEUP, self._OnMoveUp)  
         EVT_BUTTON(self, ID_CLASSIFY_MOVEDOWN, self._OnMoveDown)  
801    
802          #          classBox.Add(controlBox, 1, wxGROW, 10)
803          # Control buttons:          panelBox.Add(classBox, 1, wxGROW, 0)
         #  
         buttonBox = wxBoxSizer(wxHORIZONTAL)  
         buttonBox.Add(wxButton(self, ID_CLASSIFY_OK, _("OK")),  
                       0, wxALL, 4)  
         buttonBox.Add(wxButton(self, ID_CLASSIFY_CANCEL, _("Cancel")),  
                       0, wxALL, 4)  
         topBox.Add(buttonBox, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_BOTTOM, 10)  
804    
         EVT_BUTTON(self, ID_CLASSIFY_OK, self._OnOK)  
         EVT_BUTTON(self, ID_CLASSIFY_CANCEL, self._OnCancel)  
805    
806            buttonBox = wxBoxSizer(wxHORIZONTAL)
807            buttonBox.Add(button_try, 0, wxALL, 4)
808            buttonBox.Add(60, 20, 0, wxALL, 4)
809            buttonBox.Add(button_revert, 0, wxALL, 4)
810            buttonBox.Add(60, 20, 0, wxALL, 4)
811            buttonBox.Add(button_ok, 0, wxALL, 4)
812            buttonBox.Add(60, 20, 0, wxALL, 4)
813            buttonBox.Add(button_close, 0, wxALL, 4)
814            panelBox.Add(buttonBox, 0,
815                wxALL|wxALIGN_CENTER_HORIZONTAL|wxALIGN_BOTTOM, 0)
816    
817            panel.SetAutoLayout(True)
818            panel.SetSizer(panelBox)
819            panelBox.Fit(panel)
820            panelBox.SetSizeHints(panel)
821    
822            topBox.Add(panel, 1, wxGROW | wxALL, 4)
823    
824          self.SetAutoLayout(true)          self.SetAutoLayout(True)
825          self.SetSizer(topBox)          self.SetSizer(topBox)
826          topBox.Fit(self)          topBox.Fit(self)
827          topBox.SetSizeHints(self)          topBox.SetSizeHints(self)
828            self.Layout()
829    
830      def __BuildClassification(self, fieldIndex):          ###########
831    
832          clazz = Classification()          EVT_CHOICE(self, ID_PROPERTY_SELECT, self._OnFieldSelect)
833          fieldName = self.fields.GetString(fieldIndex)          EVT_TEXT(self, ID_PROPERTY_TITLE, self._OnTitleChanged)
834          fieldType = self.layer.GetFieldType(fieldName)          EVT_BUTTON(self, wxID_OK, self._OnOK)
835            EVT_BUTTON(self, ID_PROPERTY_TRY, self._OnTry)
836            EVT_BUTTON(self, wxID_CANCEL, self._OnCloseBtn)
837            EVT_BUTTON(self, ID_PROPERTY_REVERT, self._OnRevert)
838    
839            EVT_BUTTON(self, ID_PROPERTY_ADD, self._OnAdd)
840            EVT_BUTTON(self, ID_PROPERTY_EDITSYM, self._OnEditSymbol)
841            EVT_BUTTON(self, ID_PROPERTY_REMOVE, self._OnRemove)
842            EVT_BUTTON(self, ID_PROPERTY_GENCLASS, self._OnGenClass)
843            EVT_BUTTON(self, ID_PROPERTY_MOVEUP, self._OnMoveUp)
844            EVT_BUTTON(self, ID_PROPERTY_MOVEDOWN, self._OnMoveDown)
845    
846            ######################
847    
848            self.fields.SetFocus()
849            self.haveApplied = False
850    
851        def EditSymbol(self, row):
852            table = self.classGrid.GetTable()
853            prop = table.GetValueAsCustom(row, COL_SYMBOL, None)
854    
855            # get a new ClassGroupProperties object and copy the
856            # values over to our current object
857            propDlg = SelectPropertiesDialog(NULL, prop, self.layer.ShapeType())
858    
859            self.Enable(False)
860            if propDlg.ShowModal() == wxID_OK:
861                new_prop = propDlg.GetClassGroupProperties()
862                table.SetValueAsCustom(row, COL_SYMBOL, None, new_prop)
863            self.Enable(True)
864            propDlg.Destroy()
865            
866        def _SetClassification(self, clazz):
867            
868            self.fields.SetClientData(self.__cur_field, clazz)
869            self.classGrid.GetTable().SetClassification(clazz)
870    
871        def __BuildClassification(self, fieldIndex, copyClass = False):
872    
873    #       numRows = self.classGrid.GetNumberRows()
874    #       assert numRows > 0  # there should always be a default row
875    
876    #       clazz = Classification()
877            if fieldIndex == 0:
878                fieldName = None
879                fieldType = None
880            else:
881                fieldName = self.fields.GetString(fieldIndex)
882                fieldType = self.layer.GetFieldType(fieldName)
883    
884            clazz = self.classGrid.GetTable().GetClassification()
885    
886            if copyClass:
887                clazz = copy.deepcopy(clazz)
888    
889          clazz.SetField(fieldName)          clazz.SetField(fieldName)
890          clazz.SetFieldType(fieldType)          clazz.SetFieldType(fieldType)
891    
         numRows = self.classGrid.GetNumberRows()  
892    
893          assert(numRows > 0) # there should always be a default row  #       table = self.classGrid.GetTable()
894    #       clazz.SetDefaultGroup(table.GetClassGroup(0))
895    
896          table = self.classGrid.GetTable()  #       for i in range(1, numRows):
897          clazz.SetDefaultGroup(table.GetClassGroup(0))  #           clazz.AppendGroup(table.GetClassGroup(i))
   
         for i in range(1, numRows):  
             clazz.AddGroup(table.GetClassGroup(i))  
898    
899          return clazz          return clazz
900    
901      def __SetGridTable(self, fieldIndex):      def __SetGridTable(self, fieldIndex, group = None):
902    
903          clazz = self.fields.GetClientData(fieldIndex)          clazz = self.fields.GetClientData(fieldIndex)
904    
# Line 680  class Classifier(wxDialog): Line 906  class Classifier(wxDialog):
906              clazz = Classification()              clazz = Classification()
907              clazz.SetDefaultGroup(              clazz.SetDefaultGroup(
908                  ClassGroupDefault(                  ClassGroupDefault(
909                      self.layer.GetClassification().GetDefaultGroup().GetProperties()))                      self.layer.GetClassification().
910                                   GetDefaultGroup().GetProperties()))
911    
912              fieldName = self.fields.GetString(fieldIndex)              fieldName = self.fields.GetString(fieldIndex)
913              fieldType = self.layer.GetFieldType(fieldName)              fieldType = self.layer.GetFieldType(fieldName)
914              clazz.SetFieldType(fieldType)              clazz.SetFieldType(fieldType)
915                                    
916          self.classGrid.CreateTable(clazz, self.layer.ShapeType())          self.classGrid.CreateTable(clazz, self.layer.ShapeType(), group)
917    
918      def _OnFieldSelect(self, event):      def __SetFieldTypeText(self, fieldIndex):
919          clazz = self.__BuildClassification(self.__cur_field)          fieldName = self.fields.GetString(fieldIndex)
920          self.fields.SetClientData(self.__cur_field, clazz)          fieldType = self.layer.GetFieldType(fieldName)
921    
922          self.__cur_field = self.fields.GetSelection()          assert Classifier.type2string.has_key(fieldType)
         self.__SetGridTable(self.__cur_field)  
923    
924      def _OnOK(self, event):          text = Classifier.type2string[fieldType]
925    
926            self.fieldTypeText.SetLabel(_("Data Type: %s") % text)
927    
928        def __SelectField(self, newIndex, oldIndex = -1, group = None):
929            """This method assumes that the current selection for the
930            combo has already been set by a call to SetSelection().
931            """
932    
933            assert oldIndex >= -1
934    
935            if oldIndex != -1:
936                clazz = self.__BuildClassification(oldIndex)
937                self.fields.SetClientData(oldIndex, clazz)
938    
939            self.__SetGridTable(newIndex, group)
940    
941            self.__EnableButtons(EB_SELECT_FIELD, newIndex != 0)
942    
943            self.__SetFieldTypeText(newIndex)
944    
945        def __SetTitle(self, title):
946            if title != "":
947                title = ": " + title
948    
949            self.SetTitle(_("Layer Properties") + title)
950    
951        def _OnEditSymbol(self, event):
952            sel = self.classGrid.GetCurrentSelection()
953    
954            if len(sel) == 1:
955                self.EditSymbol(sel[0])
956    
957        def _OnFieldSelect(self, event):
958            index = self.fields.GetSelection()
959            self.__SelectField(index, self.__cur_field)
960            self.__cur_field = index
961    
962        def _OnTry(self, event):
963          """Put the data from the table into a new Classification and hand          """Put the data from the table into a new Classification and hand
964             it to the layer.             it to the layer.
965          """          """
# Line 707  class Classifier(wxDialog): Line 971  class Classifier(wxDialog):
971          # to begin with or it has been modified          # to begin with or it has been modified
972          #          #
973          if clazz is None or self.classGrid.GetTable().IsModified():          if clazz is None or self.classGrid.GetTable().IsModified():
974              clazz = self.__BuildClassification(self.__cur_field)              clazz = self.__BuildClassification(self.__cur_field, True)
   
         clazz.SetLayer(self.layer)  
975    
976          self.layer.SetClassification(clazz)          self.layer.SetClassification(clazz)
977    
978          self.EndModal(wxID_OK)          self.haveApplied = True
979    
980      def _OnCancel(self, event):      def _OnOK(self, event):
981          """Do nothing. The layer's current classification stays the same."""          self._OnTry(event)
982          self.EndModal(wxID_CANCEL)          self.Close()
983    
984        def OnClose(self, event):
985            NonModalDialog.OnClose(self, event)
986    
987        def _OnCloseBtn(self, event):
988            """Close is similar to Cancel except that any changes that were
989            made and applied remain applied, but the currently displayed
990            classification is discarded.
991            """
992    
993            self.Close()
994    
995        def _OnRevert(self, event):
996            """The layer's current classification stays the same."""
997            if self.haveApplied:
998                self.layer.SetClassification(self.originalClass)
999    
1000            #self.Close()
1001    
1002      def _OnAdd(self, event):      def _OnAdd(self, event):
1003          self.classGrid.AppendRows()          self.classGrid.AppendRows()
# Line 725  class Classifier(wxDialog): Line 1005  class Classifier(wxDialog):
1005      def _OnRemove(self, event):      def _OnRemove(self, event):
1006          self.classGrid.DeleteSelectedRows()          self.classGrid.DeleteSelectedRows()
1007    
1008      def _OnGenRange(self, event):      def _OnGenClass(self, event):
1009          print "Classifier._OnGenRange()"  
1010            self.genDlg = ClassGenDialog(self, self.layer,
1011                              self.fields.GetString(self.__cur_field))
1012    
1013            EVT_CLOSE(self.genDlg, self._OnGenDialogClose)
1014    
1015            self.__EnableButtons(EB_GEN_CLASS, False)
1016    
1017            self.genDlg.Show()
1018    
1019        def _OnGenDialogClose(self, event):
1020            self.genDlg.Destroy()
1021            self.__EnableButtons(EB_GEN_CLASS, True)
1022    
1023      def _OnMoveUp(self, event):      def _OnMoveUp(self, event):
1024          sel = self.classGrid.GetCurrentSelection()          sel = self.classGrid.GetCurrentSelection()
# Line 741  class Classifier(wxDialog): Line 1033  class Classifier(wxDialog):
1033                  table.SetClassGroup(i, x)                  table.SetClassGroup(i, x)
1034                  self.classGrid.ClearSelection()                  self.classGrid.ClearSelection()
1035                  self.classGrid.SelectRow(i - 1)                  self.classGrid.SelectRow(i - 1)
1036                    self.classGrid.MakeCellVisible(i - 1, 0)
1037    
1038      def _OnMoveDown(self, event):      def _OnMoveDown(self, event):
1039          sel = self.classGrid.GetCurrentSelection()          sel = self.classGrid.GetCurrentSelection()
# Line 755  class Classifier(wxDialog): Line 1048  class Classifier(wxDialog):
1048                  table.SetClassGroup(i + 1, x)                  table.SetClassGroup(i + 1, x)
1049                  self.classGrid.ClearSelection()                  self.classGrid.ClearSelection()
1050                  self.classGrid.SelectRow(i + 1)                  self.classGrid.SelectRow(i + 1)
1051                    self.classGrid.MakeCellVisible(i + 1, 0)
1052    
1053        def _OnTitleChanged(self, event):
1054            obj = event.GetEventObject()
1055    
1056            self.layer.SetTitle(obj.GetValue())
1057            self.__SetTitle(self.layer.Title())
1058    
1059            self.__EnableButtons(EB_LAYER_TITLE, self.layer.Title() != "")
1060    
1061        def __EnableButtons(self, case, enable):
1062    
1063            if case == EB_LAYER_TITLE:  
1064                list = (wxID_OK,
1065                        wxID_CANCEL)
1066    
1067            elif case == EB_SELECT_FIELD:
1068                list = (ID_PROPERTY_GENCLASS,
1069                        ID_PROPERTY_ADD,
1070                        ID_PROPERTY_MOVEUP,
1071                        ID_PROPERTY_MOVEDOWN,
1072                        ID_PROPERTY_EDITSYM,
1073                        ID_PROPERTY_REMOVE)
1074    
1075            elif case == EB_GEN_CLASS:
1076                list = (ID_PROPERTY_SELECT,
1077                        ID_PROPERTY_FIELDTEXT,
1078                        ID_PROPERTY_GENCLASS,
1079                        ID_PROPERTY_EDITSYM)
1080    
1081            for id in list:
1082                self.FindWindowById(id).Enable(enable)
1083    
 ID_SELPROP_OK = 4001  
 ID_SELPROP_CANCEL = 4002  
1084  ID_SELPROP_SPINCTRL = 4002  ID_SELPROP_SPINCTRL = 4002
1085  ID_SELPROP_PREVIEW = 4003  ID_SELPROP_PREVIEW = 4003
1086  ID_SELPROP_STROKECLR = 4004  ID_SELPROP_STROKECLR = 4004
1087  ID_SELPROP_FILLCLR = 4005  ID_SELPROP_FILLCLR = 4005
1088    ID_SELPROP_STROKECLRTRANS = 4006
1089    ID_SELPROP_FILLCLRTRANS = 4007
1090    
1091  class SelectPropertiesDialog(wxDialog):  class SelectPropertiesDialog(wxDialog):
1092    
1093      def __init__(self, parent, prop, shapeType):      def __init__(self, parent, prop, shapeType):
1094          wxDialog.__init__(self, parent, -1, _("Select Properties"),          wxDialog.__init__(self, parent, -1, _("Select Properties"),
1095                            style = wxRESIZE_BORDER)                            style = wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER)
1096    
1097          self.prop = ClassGroupProperties(prop)          self.prop = ClassGroupProperties(prop)
1098    
# Line 780  class SelectPropertiesDialog(wxDialog): Line 1104  class SelectPropertiesDialog(wxDialog):
1104          previewBox = wxBoxSizer(wxVERTICAL)          previewBox = wxBoxSizer(wxVERTICAL)
1105          previewBox.Add(wxStaticText(self, -1, _("Preview:")),          previewBox.Add(wxStaticText(self, -1, _("Preview:")),
1106              0, wxALIGN_LEFT | wxALL, 4)              0, wxALIGN_LEFT | wxALL, 4)
1107          self.previewer = ClassDataPreviewer(None, self.prop, shapeType,  
1108                                              self, ID_SELPROP_PREVIEW, (40, 40))          self.previewWin = ClassGroupPropertiesCtrl(
1109          previewBox.Add(self.previewer, 1, wxGROW, 15)              self, ID_SELPROP_PREVIEW, self.prop, shapeType,
1110                (40, 40), wxSIMPLE_BORDER)
1111    
1112            self.previewWin.AllowEdit(False)
1113    
1114            previewBox.Add(self.previewWin, 1, wxGROW | wxALL, 4)
1115    
1116          itemBox.Add(previewBox, 1, wxALIGN_LEFT | wxALL | wxGROW, 0)          itemBox.Add(previewBox, 1, wxALIGN_LEFT | wxALL | wxGROW, 0)
1117    
1118          # control box          # control box
1119          ctrlBox = wxBoxSizer(wxVERTICAL)          ctrlBox = wxBoxSizer(wxVERTICAL)
1120          ctrlBox.Add(  
1121              wxButton(self, ID_SELPROP_STROKECLR, "Change Line Color"),          lineColorBox = wxBoxSizer(wxHORIZONTAL)
1122              0, wxALIGN_CENTER_HORIZONTAL | wxALL | wxGROW, 4)          button = wxButton(self, ID_SELPROP_STROKECLR, _("Change Line Color"))
1123            button.SetFocus()
1124            lineColorBox.Add(button, 1, wxALL | wxGROW, 4)
1125          EVT_BUTTON(self, ID_SELPROP_STROKECLR, self._OnChangeLineColor)          EVT_BUTTON(self, ID_SELPROP_STROKECLR, self._OnChangeLineColor)
1126    
1127            lineColorBox.Add(
1128                wxButton(self, ID_SELPROP_STROKECLRTRANS, _("Transparent")),
1129                1, wxALL | wxGROW, 4)
1130            EVT_BUTTON(self, ID_SELPROP_STROKECLRTRANS,
1131                       self._OnChangeLineColorTrans)
1132    
1133            ctrlBox.Add(lineColorBox, 0,
1134                        wxALIGN_CENTER_HORIZONTAL | wxALL | wxGROW, 4)
1135    
1136          if shapeType != SHAPETYPE_ARC:          if shapeType != SHAPETYPE_ARC:
1137              ctrlBox.Add(              fillColorBox = wxBoxSizer(wxHORIZONTAL)
1138                  wxButton(self, ID_SELPROP_FILLCLR, "Change Fill Color"),              fillColorBox.Add(
1139                  0, wxALIGN_LEFT | wxALL | wxGROW, 4)                  wxButton(self, ID_SELPROP_FILLCLR, _("Change Fill Color")),
1140                    1, wxALL | wxGROW, 4)
1141              EVT_BUTTON(self, ID_SELPROP_FILLCLR, self._OnChangeFillColor)              EVT_BUTTON(self, ID_SELPROP_FILLCLR, self._OnChangeFillColor)
1142                fillColorBox.Add(
1143                    wxButton(self, ID_SELPROP_FILLCLRTRANS, _("Transparent")),
1144                    1, wxALL | wxGROW, 4)
1145                EVT_BUTTON(self, ID_SELPROP_FILLCLRTRANS,
1146                           self._OnChangeFillColorTrans)
1147                ctrlBox.Add(fillColorBox, 0,
1148                            wxALIGN_CENTER_HORIZONTAL | wxALL | wxGROW, 4)
1149    
1150          spinBox = wxBoxSizer(wxHORIZONTAL)          spinBox = wxBoxSizer(wxHORIZONTAL)
1151          spinBox.Add(wxStaticText(self, -1, _("Line Width: ")),          spinBox.Add(wxStaticText(self, -1, _("Line Width: ")),
# Line 815  class SelectPropertiesDialog(wxDialog): Line 1163  class SelectPropertiesDialog(wxDialog):
1163          itemBox.Add(ctrlBox, 0, wxALIGN_RIGHT | wxALL | wxGROW, 0)          itemBox.Add(ctrlBox, 0, wxALIGN_RIGHT | wxALL | wxGROW, 0)
1164          topBox.Add(itemBox, 1, wxALIGN_LEFT | wxALL | wxGROW, 0)          topBox.Add(itemBox, 1, wxALIGN_LEFT | wxALL | wxGROW, 0)
1165    
   
1166          #          #
1167          # Control buttons:          # Control buttons:
1168          #          #
1169          buttonBox = wxBoxSizer(wxHORIZONTAL)          buttonBox = wxBoxSizer(wxHORIZONTAL)
1170          buttonBox.Add(wxButton(self, ID_CLASSIFY_OK, _("OK")),          button_ok = wxButton(self, wxID_OK, _("OK"))
1171                        0, wxALL, 4)          button_ok.SetDefault()
1172          buttonBox.Add(wxButton(self, ID_CLASSIFY_CANCEL, _("Cancel")),          buttonBox.Add(button_ok, 0, wxALL, 4)
1173            buttonBox.Add(wxButton(self, wxID_CANCEL, _("Cancel")),
1174                        0, wxALL, 4)                        0, wxALL, 4)
1175          topBox.Add(buttonBox, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_BOTTOM, 10)          topBox.Add(buttonBox, 0, wxALIGN_CENTER_HORIZONTAL|wxALIGN_BOTTOM, 10)
1176                                                                                                                                                                    
1177          EVT_BUTTON(self, ID_SELPROP_OK, self._OnOK)          #EVT_BUTTON(self, wxID_OK, self._OnOK)
1178          EVT_BUTTON(self, ID_SELPROP_CANCEL, self._OnCancel)          #EVT_BUTTON(self, ID_SELPROP_CANCEL, self._OnCancel)
1179                                                                                                                                                                    
1180          self.SetAutoLayout(true)          self.SetAutoLayout(True)
1181          self.SetSizer(topBox)          self.SetSizer(topBox)
1182          topBox.Fit(self)          topBox.Fit(self)
1183          topBox.SetSizeHints(self)          topBox.SetSizeHints(self)
1184    
1185      def _OnOK(self, event):      def OnOK(self, event):
1186          self.EndModal(wxID_OK)          self.EndModal(wxID_OK)
1187    
1188      def _OnCancel(self, event):      def OnCancel(self, event):
1189          self.EndModal(wxID_CANCEL)          self.EndModal(wxID_CANCEL)
1190    
1191      def _OnSpin(self, event):      def _OnSpin(self, event):
1192          self.prop.SetLineWidth(self.spinCtrl.GetValue())          self.prop.SetLineWidth(self.spinCtrl.GetValue())
1193          self.previewer.Refresh()          self.previewWin.Refresh()
1194    
1195      def __GetColor(self, cur):      def __GetColor(self, cur):
1196          dialog = wxColourDialog(self)          dialog = wxColourDialog(self)
1197          dialog.GetColourData().SetColour(Color2wxColour(cur))          if cur is not Color.Transparent:
1198                dialog.GetColourData().SetColour(Color2wxColour(cur))
1199    
1200          ret = None          ret = None
1201          if dialog.ShowModal() == wxID_OK:          if dialog.ShowModal() == wxID_OK:
1202              ret = wxColour2Color(dialog.GetColourData().GetColour())              ret = wxColour2Color(dialog.GetColourData().GetColour())
# Line 859  class SelectPropertiesDialog(wxDialog): Line 1209  class SelectPropertiesDialog(wxDialog):
1209          clr = self.__GetColor(self.prop.GetLineColor())          clr = self.__GetColor(self.prop.GetLineColor())
1210          if clr is not None:          if clr is not None:
1211              self.prop.SetLineColor(clr)              self.prop.SetLineColor(clr)
1212          self.previewer.Refresh() # XXX: work around, see ClassDataPreviewer          self.previewWin.Refresh() # XXX: work around, see ClassDataPreviewer
1213    
1214        def _OnChangeLineColorTrans(self, event):
1215            self.prop.SetLineColor(Color.Transparent)
1216            self.previewWin.Refresh() # XXX: work around, see ClassDataPreviewer
1217            
1218      def _OnChangeFillColor(self, event):      def _OnChangeFillColor(self, event):
1219          clr = self.__GetColor(self.prop.GetFill())          clr = self.__GetColor(self.prop.GetFill())
1220          if clr is not None:          if clr is not None:
1221              self.prop.SetFill(clr)              self.prop.SetFill(clr)
1222          self.previewer.Refresh() # XXX: work around, see ClassDataPreviewer          self.previewWin.Refresh() # XXX: work around, see ClassDataPreviewer
1223    
1224        def _OnChangeFillColorTrans(self, event):
1225            self.prop.SetFill(Color.Transparent)
1226            self.previewWin.Refresh() # XXX: work around, see ClassDataPreviewer
1227    
1228      def GetClassGroupProperties(self):      def GetClassGroupProperties(self):
1229          return self.prop          return self.prop
1230    
1231    
1232  class ClassDataPreviewer(wxWindow):  class ClassDataPreviewWindow(wxWindow):
1233    
1234      def __init__(self, rect, prop, shapeType,      def __init__(self, rect, prop, shapeType,
1235                         parent = None, id = -1, size = wxDefaultSize):                         parent = None, id = -1, size = wxDefaultSize):
1236          if parent is not None:          if parent is not None:
1237              wxWindow.__init__(self, parent, id, size=size)              wxWindow.__init__(self, parent, id, (0, 0), size)
1238              EVT_PAINT(self, self._OnPaint)              EVT_PAINT(self, self._OnPaint)
1239    
1240          self.rect = rect          self.rect = rect
1241    
1242          self.prop = prop          self.prop = prop
1243          self.shapeType = shapeType          self.shapeType = shapeType
1244            self.previewer = ClassDataPreviewer()
1245    
1246        def GetProperties():
1247            return self.prop
1248    
1249      def _OnPaint(self, event):      def _OnPaint(self, event):
1250          dc = wxPaintDC(self)          dc = wxPaintDC(self)
# Line 889  class ClassDataPreviewer(wxWindow): Line 1252  class ClassDataPreviewer(wxWindow):
1252          # XXX: this doesn't seem to be having an effect:          # XXX: this doesn't seem to be having an effect:
1253          dc.DestroyClippingRegion()          dc.DestroyClippingRegion()
1254    
1255          self.Draw(dc, None)          if self.rect is None:
1256                w, h = self.GetSize()
1257                rect = wxRect(0, 0, w, h)
1258            else:
1259                rect = self.rect
1260    
1261            self.previewer.Draw(dc, rect, self.prop, self.shapeType)
1262    
1263    class ClassDataPreviewer:
1264    
1265      def Draw(self, dc, rect, prop = None, shapeType = None):      def Draw(self, dc, rect, prop, shapeType):
1266    
1267          if prop is None: prop = self.prop          assert dc is not None
1268          if shapeType is None: shapeType = self.shapeType          assert isinstance(prop, ClassGroupProperties)
1269    
1270          if rect is None:          if rect is None:
1271              x = y = 0              x = 0
1272              w, h = self.GetClientSizeTuple()              y = 0
1273                w, h = dc.GetSize()
1274          else:          else:
1275              x = rect.GetX()              x = rect.GetX()
1276              y = rect.GetY()              y = rect.GetY()
# Line 906  class ClassDataPreviewer(wxWindow): Line 1278  class ClassDataPreviewer(wxWindow):
1278              h = rect.GetHeight()              h = rect.GetHeight()
1279    
1280          stroke = prop.GetLineColor()          stroke = prop.GetLineColor()
1281          if stroke is Color.None:          if stroke is Color.Transparent:
1282              pen = wxTRANSPARENT_PEN              pen = wxTRANSPARENT_PEN
1283          else:          else:
1284              pen = wxPen(Color2wxColour(stroke),              pen = wxPen(Color2wxColour(stroke),
# Line 914  class ClassDataPreviewer(wxWindow): Line 1286  class ClassDataPreviewer(wxWindow):
1286                          wxSOLID)                          wxSOLID)
1287    
1288          stroke = prop.GetFill()          stroke = prop.GetFill()
1289          if stroke is Color.None:          if stroke is Color.Transparent:
1290              brush = wxTRANSPARENT_BRUSH              brush = wxTRANSPARENT_BRUSH
1291          else:          else:
1292              brush = wxBrush(Color2wxColour(stroke), wxSOLID)              brush = wxBrush(Color2wxColour(stroke), wxSOLID)
# Line 928  class ClassDataPreviewer(wxWindow): Line 1300  class ClassDataPreviewer(wxWindow):
1300                             wxPoint(x + w/2, y + h/4*3),                             wxPoint(x + w/2, y + h/4*3),
1301                             wxPoint(x + w, y)])                             wxPoint(x + w, y)])
1302    
1303          elif shapeType == SHAPETYPE_POINT or \          elif shapeType == SHAPETYPE_POINT:
              shapeType == SHAPETYPE_POLYGON:  
1304    
1305              dc.DrawCircle(x + w/2, y + h/2,              dc.DrawCircle(x + w/2, y + h/2,
1306                            (min(w, h) - prop.GetLineWidth())/2)                            (min(w, h) - prop.GetLineWidth())/2)
1307    
1308            elif shapeType == SHAPETYPE_POLYGON:
1309                dc.DrawRectangle(x, y, w, h)
1310    
1311  class ClassRenderer(wxPyGridCellRenderer):  class ClassRenderer(wxPyGridCellRenderer):
1312    
1313      def __init__(self, shapeType):      def __init__(self, shapeType):
1314          wxPyGridCellRenderer.__init__(self)          wxPyGridCellRenderer.__init__(self)
1315          self.previewer = ClassDataPreviewer(None, None, shapeType)          self.shapeType = shapeType
1316            self.previewer = ClassDataPreviewer()
1317    
1318      def Draw(self, grid, attr, dc, rect, row, col, isSelected):      def Draw(self, grid, attr, dc, rect, row, col, isSelected):
1319          data = grid.GetTable().GetValueAsCustom(row, col, None)          data = grid.GetTable().GetClassGroup(row)
1320    
1321          dc.SetClippingRegion(rect.GetX(), rect.GetY(),          dc.SetClippingRegion(rect.GetX(), rect.GetY(),
1322                               rect.GetWidth(), rect.GetHeight())                               rect.GetWidth(), rect.GetHeight())
# Line 951  class ClassRenderer(wxPyGridCellRenderer Line 1326  class ClassRenderer(wxPyGridCellRenderer
1326                           rect.GetWidth(), rect.GetHeight())                           rect.GetWidth(), rect.GetHeight())
1327    
1328          if not isinstance(data, ClassGroupMap):          if not isinstance(data, ClassGroupMap):
1329              self.previewer.Draw(dc, rect, data.GetProperties())              self.previewer.Draw(dc, rect, data.GetProperties(), self.shapeType)
1330    
1331          if isSelected:          if isSelected:
1332              dc.SetPen(wxPen(wxColour(0 * 255, 0 * 255, 0 * 255),              dc.SetPen(wxPen(wxBLACK, 1, wxSOLID))
                       4, wxSOLID))  
1333              dc.SetBrush(wxTRANSPARENT_BRUSH)              dc.SetBrush(wxTRANSPARENT_BRUSH)
1334    
1335              dc.DrawRectangle(rect.GetX(), rect.GetY(),              dc.DrawRectangle(rect.GetX(), rect.GetY(),
1336                               rect.GetWidth(), rect.GetHeight())                               rect.GetWidth(), rect.GetHeight())
1337    
1338          dc.DestroyClippingRegion()          dc.DestroyClippingRegion()
1339    
1340    
1341    class ClassGroupPropertiesCtrl(wxWindow, wxControl):
1342    
1343        def __init__(self, parent, id, props, shapeType,
1344                     size = wxDefaultSize, style = 0):
1345    
1346            wxWindow.__init__(self, parent, id, size = size, style = style)
1347    
1348            self.SetProperties(props)
1349            self.SetShapeType(shapeType)
1350            self.AllowEdit(True)
1351    
1352            EVT_PAINT(self, self._OnPaint)
1353            EVT_LEFT_DCLICK(self, self._OnLeftDClick)
1354    
1355            self.previewer = ClassDataPreviewer()
1356    
1357        def _OnPaint(self, event):
1358            dc = wxPaintDC(self)
1359    
1360            # XXX: this doesn't seem to be having an effect:
1361            dc.DestroyClippingRegion()
1362    
1363            w, h = self.GetClientSize()
1364    
1365            self.previewer.Draw(dc,
1366                                wxRect(0, 0, w, h),
1367                                self.GetProperties(),
1368                                self.GetShapeType())
1369    
1370    
1371        def GetProperties(self):
1372            return self.props
1373    
1374        def SetProperties(self, props):
1375            self.props = props
1376            self.Refresh()
1377    
1378        def GetShapeType(self):
1379            return self.shapeType
1380    
1381        def SetShapeType(self, shapeType):
1382            self.shapeType = shapeType
1383            self.Refresh()
1384    
1385        def AllowEdit(self, allow):
1386            self.allowEdit = allow
1387    
1388        def DoEdit(self):
1389            if not self.allowEdit: return
1390    
1391            propDlg = SelectPropertiesDialog(NULL,
1392                                             self.GetProperties(),
1393                                             self.GetShapeType())
1394    
1395            if propDlg.ShowModal() == wxID_OK:
1396                new_prop = propDlg.GetClassGroupProperties()
1397                self.SetProperties(new_prop)
1398                self.Refresh()
1399    
1400            propDlg.Destroy()
1401    
1402        def _OnLeftDClick(self, event):
1403            self.DoEdit()

Legend:
Removed from v.473  
changed lines
  Added in v.813

[email protected]
ViewVC Help
Powered by ViewVC 1.1.26