File: simple_grid_model.py

package info (click to toggle)
python-pyface 8.0.0-5
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 13,944 kB
  • sloc: python: 54,107; makefile: 82
file content (284 lines) | stat: -rw-r--r-- 8,947 bytes parent folder | download
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
# (C) Copyright 2005-2023 Enthought, Inc., Austin, TX
# All rights reserved.
#
# This software is provided without warranty under the terms of the BSD
# license included in LICENSE.txt and may be redistributed only under
# the conditions described in the aforementioned license. The license
# is also available online at http://www.enthought.com/licenses/BSD.txt
#
# Thanks for using Enthought open source!

""" A SimpleGridModel simply builds a table from a 2-dimensional
list/array containing the data. Optionally users can pass in specifications
for rows and columns. By default these are built off the data itself,
with row/column labels as the index + 1."""


from pyface.action.api import Action, Group, MenuManager
from traits.api import Any, Instance, List, Union
from pyface.wx.drag_and_drop import clipboard as enClipboard


from .grid_model import GridColumn, GridModel, GridRow


class SimpleGridModel(GridModel):
    """ A SimpleGridModel simply builds a table from a 2-dimensional
    list/array containing the data. Optionally users can pass in specifications
    for rows and columns. By default these are built off the data itself,
    with row/column labels as the index + 1."""

    # A 2-dimensional list/array containing the grid data.
    data = Any()

    # The rows in the model.
    rows = Union(None, List(Instance(GridRow)))

    # The columns in the model.
    columns = Union(None, List(Instance(GridColumn)))

    # ------------------------------------------------------------------------
    # 'GridModel' interface.
    # ------------------------------------------------------------------------

    def get_column_count(self):
        """ Return the number of columns for this table. """

        if self.columns is not None:
            # if we have an explicit declaration then use it
            count = len(self.columns)
        else:
            # otherwise look at the length of the first row
            # note: the data had better be 2D
            count = len(self.data[0])

        return count

    def get_column_name(self, index):
        """ Return the name of the column specified by the
        (zero-based) index. """

        if self.columns is not None:
            # if we have an explicit declaration then use it
            try:
                name = self.columns[index].label
            except IndexError:
                name = ""
        else:
            # otherwise return the index plus 1
            name = str(index + 1)

        return name

    def get_cols_drag_value(self, cols):
        """ Return the value to use when the specified columns are dragged or
        copied and pasted. cols is a list of column indexes. """

        # if there is only one column in cols, then we return a 1-dimensional
        # list
        if len(cols) == 1:
            value = self.__get_data_column(cols[0])
        else:
            # iterate over every column, building a list of the values in that
            # column
            value = []
            for col in cols:
                value.append(self.__get_data_column(col))

        return value

    def is_column_read_only(self, index):
        """ Return True if the column specified by the zero-based index
        is read-only. """

        # if there is no declaration then assume the column is not
        # read only
        read_only = False
        if self.columns is not None:
            # if we have an explicit declaration then use it
            try:
                read_only = self.columns[index].read_only
            except IndexError:
                pass
        return read_only

    def get_row_count(self):
        """ Return the number of rows for this table. """

        if self.rows is not None:
            # if we have an explicit declaration then use it
            count = len(self.rows)
        else:
            # otherwise look at the data
            count = len(self.data)

        return count

    def get_row_name(self, index):
        """ Return the name of the row specified by the
        (zero-based) index. """

        if self.rows is not None:
            # if we have an explicit declaration then use it
            try:
                name = self.rows[index].label
            except IndexError:
                name = str(index + 1)
        else:
            # otherwise return the index plus 1
            name = str(index + 1)

        return name

    def get_rows_drag_value(self, rows):
        """ Return the value to use when the specified rows are dragged or
        copied and pasted. rows is a list of row indexes. """

        # if there is only one row in rows, then we return a 1-dimensional
        # list
        if len(rows) == 1:
            value = self.__get_data_row(rows[0])
        else:
            # iterate over every row, building a list of the values in that
            # row
            value = []
            for row in rows:
                value.append(self.__get_data_row(row))

        return value

    def is_row_read_only(self, index):
        """ Return True if the row specified by the zero-based index
        is read-only. """

        # if there is no declaration then assume the row is not
        # read only
        read_only = False
        if self.rows is not None:
            # if we have an explicit declaration then use it
            try:
                read_only = self.rows[index].read_only
            except IndexError:
                pass

        return read_only

    def get_value(self, row, col):
        """ Return the value stored in the table at (row, col). """

        try:
            return self.data[row][col]

        except IndexError:
            pass

        return ""

    def is_cell_empty(self, row, col):
        """ Returns True if the cell at (row, col) has a None value,
        False otherwise."""

        if row >= self.get_row_count() or col >= self.get_column_count():
            empty = True

        else:
            try:
                value = self.get_value(row, col)
                empty = value is None
            except IndexError:
                empty = True

        return empty

    def get_cell_context_menu(self, row, col):
        """ Return a MenuManager object that will generate the appropriate
        context menu for this cell."""

        context_menu = MenuManager(
            Group(_CopyAction(self, row, col, name="Copy"), id="Group")
        )

        return context_menu

    def is_cell_editable(self, row, col):
        """ Returns True if the cell at (row, col) is editable,
        False otherwise. """
        return True

    # ------------------------------------------------------------------------
    # protected 'GridModel' interface.
    # ------------------------------------------------------------------------
    def _set_value(self, row, col, value):
        """ Sets the value of the cell at (row, col) to value.

        Raises a ValueError if the value is vetoed or the cell at
        (row, col) does not exist. """
        new_rows = 0
        try:
            self.data[row][col] = value
        except IndexError:
            # Add a new row.
            self.data.append([0] * self.GetNumberCols())
            self.data[row][col] = value
            new_rows = 1

        return new_rows

    def _delete_rows(self, pos, num_rows):
        """ Removes rows pos through pos + num_rows from the model. """

        if pos + num_rows >= self.get_row_count():
            num_rows = self.get_rows_count() - pos

        del self.data[pos, pos + num_rows]

        return num_rows

    # ------------------------------------------------------------------------
    # private interface.
    # ------------------------------------------------------------------------

    def __get_data_column(self, col):
        """ Return a 1-d list of data from the column indexed by col. """

        row_count = self.get_row_count()

        coldata = []
        for row in range(row_count):
            try:
                coldata.append(self.get_value(row, col))
            except IndexError:
                coldata.append(None)

        return coldata

    def __get_data_row(self, row):
        """ Return a 1-d list of data from the row indexed by row. """

        col_count = self.get_column_count()

        rowdata = []
        for col in range(col_count):
            try:
                rowdata.append(self.get_value(row, col))
            except IndexError:
                rowdata.append(None)

        return rowdata


# Private class
class _CopyAction(Action):
    def __init__(self, model, row, col, **kw):

        super().__init__(**kw)
        self._model = model
        self._row = row
        self._col = col

    def perform(self):

        # grab the specified value from the model and add it to the
        # clipboard
        value = self._model.get_cell_drag_value(self._row, self._col)
        enClipboard.data = value