This file is indexed.

/usr/lib/thuban/Thuban/UI/tableview.py is in thuban 1.2.2-12build3.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
 38
 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
 98
 99
100
101
102
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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
# Copyright (c) 2001, 2002, 2003 by Intevation GmbH
# Authors:
# Bernhard Herzog <bh@intevation.de>
#
# This program is free software under the GPL (>=v2)
# Read the file COPYING coming with Thuban for details.

__version__ = "$Revision: 2817 $"

import os.path

from Thuban import _

import wx
from wx import grid

from Thuban.Lib.connector import Publisher
from Thuban.Model.table import FIELDTYPE_INT, FIELDTYPE_DOUBLE, \
     FIELDTYPE_STRING, table_to_dbf, table_to_csv
from dialogs import ThubanFrame

from messages import SHAPES_SELECTED, SESSION_REPLACED
from Thuban.Model.messages import TABLE_REMOVED, MAP_LAYERS_REMOVED
from Thuban.UI import internal_from_wxstring
from Thuban.UI.common import ThubanBeginBusyCursor, ThubanEndBusyCursor

wx_value_type_map = {FIELDTYPE_INT: grid.GRID_VALUE_NUMBER,
                     FIELDTYPE_DOUBLE: grid.GRID_VALUE_FLOAT,
                     FIELDTYPE_STRING: grid.GRID_VALUE_STRING}

ROW_SELECTED = "ROW_SELECTED"

QUERY_KEY = 'S'

class DataTable(grid.PyGridTableBase):

    """Wrapper around a Thuban table object suitable for a wxGrid"""

    def __init__(self, table = None):
        grid.PyGridTableBase.__init__(self)
        self.num_cols = 0
        self.num_rows = 0
        self.columns = []
        self.table = None
        self.SetTable(table)

    def SetTable(self, table):
        self.table = table
        self.num_cols = table.NumColumns()
        self.num_rows = table.NumRows()

        self.columns = []
        for i in range(self.num_cols):
            col = table.Column(i)
            self.columns.append((col.name, wx_value_type_map[col.type]))

    #
    # required methods for the wxPyGridTableBase interface
    #

    def GetNumberRows(self):
        return self.num_rows

    def GetNumberCols(self):
        return self.num_cols

    def IsEmptyCell(self, row, col):
        return 0

    # Get/Set values in the table.  The Python version of these
    # methods can handle any data-type, (as long as the Editor and
    # Renderer understands the type too,) not just strings as in the
    # C++ version.
    def GetValue(self, row, col):
        try:
            record = self.table.ReadRowAsDict(row, row_is_ordinal = 1)
        except UnicodeError:
            record = dict()
            for (key, val) in self.table.ReadRowAsDict(row, \
                              row_is_ordinal = 1).items():
                if isinstance(val, str):
                    record[key] = val.decode('iso-8859-1')
                else:
                    record[key] = val
        return record[self.columns[col][0]]

    def SetValue(self, row, col, value):
        pass

    #
    # Some optional methods
    #

    # Called when the grid needs to display labels
    def GetColLabelValue(self, col):
        return self.columns[col][0]

    # Called to determine the kind of editor/renderer to use by
    # default, doesn't necessarily have to be the same type used
    # nativly by the editor/renderer if they know how to convert.
    def GetTypeName(self, row, col):
        return self.columns[col][1]

    # Called to determine how the data can be fetched and stored by the
    # editor and renderer.  This allows you to enforce some type-safety
    # in the grid.
    def CanGetValueAs(self, row, col, typeName):
        # perhaps we should allow conversion int->double?
        return self.GetTypeName(row, col) == typeName

    def CanSetValueAs(self, row, col, typeName):
        return self.CanGetValueAs(row, col, typeName)


    #
    def RowIdToOrdinal(self, rowid):
        """Return the ordinal of the row given by its id"""
        return self.table.RowIdToOrdinal(rowid)

    def RowOrdinalToId(self, ordinal):
        """Return the id of the row given by its ordinal"""
        return self.table.RowOrdinalToId(ordinal)


class NullRenderer(grid.PyGridCellRenderer):

    """Renderer that draws NULL as a gray rectangle

    Other values are delegated to a normal renderer which is given as
    the parameter to the constructor.
    """

    def __init__(self, non_null_renderer):
        grid.PyGridCellRenderer.__init__(self)
        self.non_null_renderer = non_null_renderer

    def Draw(self, grid, attr, dc, rect, row, col, isSelected):
        value = grid.table.GetValue(row, col)
        if value is None:
            dc.SetBackgroundMode(wx.SOLID)
            dc.SetBrush(wx.Brush(wx.Colour(192, 192, 192), wx.SOLID))
            dc.SetPen(wx.TRANSPARENT_PEN)
            dc.DrawRectangle(rect.x, rect.y, rect.width, rect.height)
        else:
            self.non_null_renderer.Draw(grid, attr, dc, rect, row, col,
                                        isSelected)

    def GetBestSize(self, grid, attr, dc, row, col):
        self.non_null_renderer.GetBestSize(grid, attr, dc, row, col)

    def Clone(self):
        return NullRenderer(self.non_null_renderer)


class TableGrid(grid.Grid, Publisher):

    """A grid view for a Thuban table

    When rows are selected by the user the table issues ROW_SELECTED
    messages. wx sends selection events even when the selection is
    manipulated by code (instead of by the user) which usually lead to
    ROW_SELECTED messages being sent in turn. Therefore sending messages
    can be switched on and off with the allow_messages and
    disallow_messages methods.
    """

    def __init__(self, parent, table = None):
        grid.Grid.__init__(self, parent, -1)

        self.allow_messages_count = 0

        # keep track of which rows are selected.
        self.rows = {}

        self.table = DataTable(table)

        # The second parameter means that the grid is to take ownership
        # of the table and will destroy it when done. Otherwise you
        # would need to keep a reference to it and call its Destroy
        # method later.
        self.SetTable(self.table, True)

        #self.SetMargins(0,0)

        # AutoSizeColumns would allow us to make the grid have optimal
        # column widths automatically but it would cause a traversal of
        # the entire table which for large .dbf files can take a very
        # long time.
        #self.AutoSizeColumns(False)

        self.SetSelectionMode(grid.Grid.wxGridSelectRows)

        self.ToggleEventListeners(True)
        self.Bind(grid.EVT_GRID_RANGE_SELECT, self.OnRangeSelect)
        self.Bind(grid.EVT_GRID_SELECT_CELL, self.OnSelectCell)

        # Replace the normal renderers with our own versions which
        # render NULL/None values specially
        self.RegisterDataType(grid.GRID_VALUE_STRING,
                              NullRenderer(grid.GridCellStringRenderer()), None)
        self.RegisterDataType(grid.GRID_VALUE_NUMBER,
                              NullRenderer(grid.GridCellNumberRenderer()), None)
        self.RegisterDataType(grid.GRID_VALUE_FLOAT,
                              NullRenderer(grid.GridCellFloatRenderer()), None)

        self.Bind(wx.EVT_WINDOW_DESTROY, self.OnDestroy)

    def OnDestroy(self, event):
        Publisher.Destroy(self)

    def SetTableObject(self, table):
        self.table.SetTable(table)

    def OnRangeSelect(self, event):
        to_id = self.table.RowOrdinalToId
        if self.handleSelectEvents:
            self.rows = dict([(to_id(i), 0) for i in self.GetSelectedRows()])

            # if we're selecting we need to include the selected range and
            # make sure that the current row is also included, which may
            # not be the case if you just click on a single row!
            if event.Selecting():
                for i in range(event.GetTopRow(), event.GetBottomRow() + 1):
                    self.rows[to_id(i)] = 0
                self.rows[to_id(event.GetTopLeftCoords().GetRow())] = 0

            self.issue(ROW_SELECTED, self.rows.keys())

        event.Skip()

    def OnSelectCell(self, event):
        to_id = self.table.RowOrdinalToId
        if self.handleSelectEvents:
            self.issue(ROW_SELECTED,
                       [to_id(i) for i in self.GetSelectedRows()])
        event.Skip()

    def ToggleEventListeners(self, on):
        self.handleSelectEvents = on

    def GetNumberSelected(self):
        return len(self.rows)

    def disallow_messages(self):
        """Disallow messages to be send.

        This method only increases a counter so that calls to
        disallow_messages and allow_messages can be nested. Only the
        outermost calls will actually switch message sending on and off.
        """
        self.allow_messages_count += 1

    def allow_messages(self):
        """Allow messages to be send.

        This method only decreases a counter so that calls to
        disallow_messages and allow_messages can be nested. Only the
        outermost calls will actually switch message sending on and off.
        """
        self.allow_messages_count -= 1

    def issue(self, *args):
        """Issue a message unless disallowed.

        See the allow_messages and disallow_messages methods.
        """
        if self.allow_messages_count == 0:
            Publisher.issue(self, *args)

    def SelectRowById(self, rowid, do_select):
        """Select row with the id rowid"""
        self.SelectRow(self.table.RowIdToOrdinal(rowid), do_select)


class LayerTableGrid(TableGrid):

    """Table grid for the layer tables.

    The LayerTableGrid is basically the same as a TableGrid but it's
    selection is usually coupled to the selected object in the map.
    """

    def select_shapes(self, layer, shapes):
        """Select the row corresponding to the specified shape and layer

        If layer is not the layer the table is associated with do
        nothing. If shape or layer is None also do nothing.
        """
        if layer is not None \
            and layer.ShapeStore().Table() is self.table.table:

            self.disallow_messages()
            try:
                self.ClearSelection()
                if len(shapes) > 0:
                    # keep track of the lowest id so we can make it the
                    # first visible item
                    first = -1

                    to_ordinal = self.table.RowIdToOrdinal
                    for shape in shapes:
                        row = to_ordinal(shape)
                        self.SelectRow(row, True)
                        if row < first:
                            first = row

                    self.SetGridCursor(first, 0)
                    self.MakeCellVisible(first, 0)
            finally:
                self.allow_messages()


class TableFrame(ThubanFrame):

    """Frame that displays a Thuban table in a grid view"""

    def __init__(self, parent, name, title, table):
        ThubanFrame.__init__(self, parent, name, title)
        self.panel = wx.Panel(self, -1)

        self.table = table
        self.grid = self.make_grid(self.table)
        self.app = self.parent.application
        self.app.Subscribe(SESSION_REPLACED, self.close_on_session_replaced)
        self.session = self.app.Session()
        self.session.Subscribe(TABLE_REMOVED, self.close_on_table_removed)

    def OnDestroy(self, event):
        """Extend inherited method to unsubscribe messages"""
        self.app.Unsubscribe(SESSION_REPLACED, self.close_on_session_replaced)
        self.session.Unsubscribe(TABLE_REMOVED, self.close_on_table_removed)
        ThubanFrame.OnDestroy(self, event)

    def make_grid(self, table):
        """Return the table grid to use in the frame.

        The default implementation returns a TableGrid instance.
        Override in derived classes to use different grid classes.
        """
        return TableGrid(self, table)

    def close_on_session_replaced(self, *args):
        """Subscriber for the SESSION_REPLACED messages.

        The table frame is tied to a session so close the window when
        the session changes.
        """
        self.Close()

    def close_on_table_removed(self, table):
        """Subscriber for the TABLE_REMOVED messages.

        The table frame is tied to a particular table so close the
        window when the table is removed.
        """
        if table is self.table:
            self.Close()


ID_QUERY = 4001
ID_EXPORT = 4002
ID_COMBOVALUE = 4003
ID_EXPORTSEL = 4004

class QueryTableFrame(TableFrame):

    """Frame that displays a table in a grid view and offers user actions
    selection and export

    A QueryTableFrame is TableFrame whose selection is connected to the
    selected object in a map.
    """

    def __init__(self, parent, name, title, table):
        TableFrame.__init__(self, parent, name, title, table)

        self.combo_fields = wx.ComboBox(self.panel, -1, style=wx.CB_READONLY)
        self.choice_comp = wx.Choice(self.panel, -1,
                              choices=["<", "<=", "==", "!=", ">=", ">"])
        self.combo_value = wx.ComboBox(self.panel, ID_COMBOVALUE)
        self.choice_action = wx.Choice(self.panel, -1,
                                choices=[_("Replace Selection"),
                                        _("Refine Selection"),
                                        _("Add to Selection")])

        button_query = wx.Button(self.panel, ID_QUERY, _("Query"))
        button_export = wx.Button(self.panel, ID_EXPORT, _("Export"))
        button_exportSel = wx.Button(self.panel, ID_EXPORTSEL, _("Export Selection"))
        button_close = wx.Button(self.panel, wx.ID_CLOSE, _("Close"))

        self.CreateStatusBar()

        self.grid.SetSize((400, 200))

        self.combo_value.Append("")
        for i in range(table.NumColumns()):
            name = table.Column(i).name
            self.combo_fields.Append(name)
            self.combo_value.Append(name)

        # assume at least one field?
        self.combo_fields.SetSelection(0)
        self.combo_value.SetSelection(0)
        self.choice_action.SetSelection(0)
        self.choice_comp.SetSelection(0)

        self.grid.Reparent(self.panel)

        self.UpdateStatusText()

        topBox = wx.BoxSizer(wx.VERTICAL)

        sizer = wx.StaticBoxSizer(wx.StaticBox(self.panel, -1,
                                  _("Selection")),
                                  wx.HORIZONTAL)
        sizer.Add(self.combo_fields, 1, wx.EXPAND|wx.ALL, 4)
        sizer.Add(self.choice_comp, 0, wx.ALL, 4)
        sizer.Add(self.combo_value, 1, wx.EXPAND|wx.ALL, 4)
        sizer.Add(self.choice_action, 0, wx.ALL, 4)
        sizer.Add(button_query, 0, wx.ALL | wx.ALIGN_CENTER_VERTICAL, 4)
        sizer.Add( (40, 20), 0, wx.ALL, 4)

        topBox.Add(sizer, 0, wx.EXPAND|wx.ALL, 4)
        topBox.Add(self.grid, 1, wx.EXPAND|wx.ALL, 0)

        sizer = wx.BoxSizer(wx.HORIZONTAL)
        sizer.Add(button_export, 0, wx.ALL, 4)
        sizer.Add(button_exportSel, 0, wx.ALL, 4)
        sizer.Add( (60, 20), 1, wx.ALL|wx.EXPAND, 4)
        sizer.Add(button_close, 0, wx.ALL|wx.ALIGN_RIGHT, 4)
        topBox.Add(sizer, 0, wx.ALL | wx.EXPAND, 4)

        self.panel.SetAutoLayout(True)
        self.panel.SetSizer(topBox)
        topBox.Fit(self.panel)
        topBox.SetSizeHints(self.panel)

        panelSizer = wx.BoxSizer(wx.VERTICAL)
        panelSizer.Add(self.panel, 1, wx.EXPAND, 0)
        self.SetAutoLayout(True)
        self.SetSizer(panelSizer)
        panelSizer.Fit(self)
        panelSizer.SetSizeHints(self)

        self.grid.SetFocus()

        self.Bind(wx.EVT_BUTTON, self.OnQuery, id=ID_QUERY)
        self.Bind(wx.EVT_BUTTON, self.OnExport, id=ID_EXPORT)
        self.Bind(wx.EVT_BUTTON, self.OnExportSel, id=ID_EXPORTSEL)
        self.Bind(wx.EVT_BUTTON, self.OnClose, id=wx.ID_CLOSE)
        self.Bind(wx.EVT_KEY_DOWN, self.OnKeyDown, self.grid)

        self.grid.Subscribe(ROW_SELECTED, self.UpdateStatusText)

    def UpdateStatusText(self, rows=None):
        self.SetStatusText(_("%i rows (%i selected), %i columns")
            % (self.grid.GetNumberRows(),
               self.grid.GetNumberSelected(),
               self.grid.GetNumberCols()))

    def OnKeyDown(self, event):
        """Catch query key from grid"""
        if event.AltDown() and event.GetKeyCode() == ord(QUERY_KEY):
            self.combo_fields.SetFocus()
            self.combo_fields.refocus = True
        else:
            event.Skip()

    def OnQuery(self, event):
        ThubanBeginBusyCursor()
        try:

            text = self.combo_value.GetValue()
            if self.combo_value.GetSelection() < 1 \
                or self.combo_value.FindString(text) == -1:
                value = text
            else:
                value = self.table.Column(text)

            ids = self.table.SimpleQuery(
                    self.table.Column(self.combo_fields.GetStringSelection()),
                    self.choice_comp.GetStringSelection(),
                    value)

            choice = self.choice_action.GetSelection()

            #
            # what used to be nice code got became a bit ugly because
            # each time we select a row a message is sent to the grid
            # which we are listening for and then we send further 
            # messages. 
            #
            # now, we disable those listeners select everything but
            # the first item, reenable the listeners, and select
            # the first element, which causes everything to be
            # updated properly.
            #
            if ids:
                self.grid.ToggleEventListeners(False)

            if choice == 0:
                # Replace Selection
                self.grid.ClearSelection()
            elif choice == 1:
                # Refine Selection
                sel = self.get_selected()
                self.grid.ClearSelection()
                ids = filter(sel.has_key, ids)
            elif choice == 2:
                # Add to Selection
                pass

            #
            # select the rows (all but the first)
            # 
            firsttime = True
            for id in ids:
                if firsttime:
                    firsttime = False
                else:
                    self.grid.SelectRowById(id, True)

            self.grid.ToggleEventListeners(True)

            #
            # select the first row
            #
            if ids:
                self.grid.SelectRowById(ids[0], True)

        finally:
            ThubanEndBusyCursor()

    def doExport(self, onlySelected):

        dlg = wx.FileDialog(self, _("Export Table To"), ".", "",
                           _("DBF Files (*.dbf)|*.dbf|") +
                           _("CSV Files (*.csv)|*.csv|") +
                           _("All Files (*.*)|*.*"),
                           wx.SAVE|wx.OVERWRITE_PROMPT)
        if dlg.ShowModal() == wx.ID_OK:
            filename = internal_from_wxstring(dlg.GetPath())
            type = os.path.basename(filename).split('.')[-1:][0]
            dlg.Destroy()

            if onlySelected:
                records = self.grid.GetSelectedRows()
            else:
                records = None

            if type.upper() == "DBF":
                table_to_dbf(self.table, filename, records)
            elif type.upper() == 'CSV':
                table_to_csv(self.table, filename, records)
            else:
                dlg = wx.MessageDialog(None, "Unsupported format: %s" % type,
                                      "Table Export", wx.OK|wx.ICON_WARNING)
                dlg.ShowModal()
                dlg.Destroy()
        else:
            dlg.Destroy()

    def OnExport(self, event):
        self.doExport(False)

    def OnExportSel(self, event):
        self.doExport(True)

    def OnClose(self, event):
        TableFrame.OnClose(self, event)

    def get_selected(self):
        """Return a dictionary of the selected rows.

        The dictionary has the indexes as keys."""
        to_id = self.table.RowOrdinalToId
        return dict([(to_id(i), 0) for i in self.grid.GetSelectedRows()])


class LayerTableFrame(QueryTableFrame):

    """Frame that displays a layer table in a grid view

    A LayerTableFrame is a QueryTableFrame whose selection is connected to the
    selected object in a map.
    """

    def __init__(self, parent, name, title, layer, table):
        QueryTableFrame.__init__(self, parent, name, title, table)
        self.layer = layer
        self.grid.Subscribe(ROW_SELECTED, self.rows_selected)
        self.parent.Subscribe(SHAPES_SELECTED, self.select_shapes)
        self.map = self.parent.Map()
        self.map.Subscribe(MAP_LAYERS_REMOVED, self.map_layers_removed)

        # if there is already a selection present, update the grid
        # accordingly
        sel = self.get_selected().keys()
        for i in sel:
            self.grid.SelectRowById(i, True)

    def OnDestroy(self, event):
        """Extend inherited method to unsubscribe messages"""
        # There's no need to unsubscribe from self.grid's messages
        # because it will get a DESTROY event too (since destroying the
        # frame basically means that all child windows are also
        # destroyed) and this it will clear all subscriptions
        # automatically.  It may even have been destroyed already (this
        # does happen on w2000 for instance) so calling any of its
        # methods here would be an error.
        self.parent.Unsubscribe(SHAPES_SELECTED, self.select_shapes)
        self.map.Unsubscribe(MAP_LAYERS_REMOVED, self.map_layers_removed)
        QueryTableFrame.OnDestroy(self, event)

    def make_grid(self, table):
        """Override the derived method to return a LayerTableGrid.
        """
        return LayerTableGrid(self, table)

    def get_selected(self):
        """Override the derived method to return a dictionary of the selected
        rows.
        """
        return dict([(i, 0) for i in self.parent.SelectedShapes()])

    def select_shapes(self, layer, shapes):
        """Subscribed to the SHAPES_SELECTED message.

        If shapes contains exactly one shape id, select that shape in
        the grid. Otherwise deselect all.
        """
        self.grid.select_shapes(layer, shapes)

    def rows_selected(self, rows):
        """Return the selected rows of the layer as they are returned
        by Layer.SelectShapes().
        """
        if self.layer is not None:
            self.parent.SelectShapes(self.layer, rows)

    def map_layers_removed(self, *args):
        """Receiver for the map's MAP_LAYERS_REMOVED message

        Close the dialog if the layer whose table we're showing is not
        in the map anymore.
        """
        if self.layer not in self.map.Layers():
            self.Close()