File: iterator.py

package info (click to toggle)
skencil 0.6.17-7
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 6,136 kB
  • ctags: 8,589
  • sloc: python: 36,672; ansic: 16,571; sh: 151; makefile: 92
file content (389 lines) | stat: -rw-r--r-- 11,634 bytes parent folder | download | duplicates (4)
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
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Library General Public License for more details.
#
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

class StyletextError(Exception):
    pass
    
    
class Style:

    is_Style = 1

    def __init__(self, **kw):
        if len(kw) != 1:
            raise StyletextError(
                "Style should be called with exactly one parameter "
                "eg. Style(size=3): %s" % kw)
        self.sort = kw.keys()[0]
        self.options = kw.values()[0]
        self._signature_ = str(kw)

    def __cmp__ (self, other):
        if not hasattr(other, 'is_Style'):
            raise StyletextError(
                "can't compare styles to non-style objects: %s" %
                other)
        s1 = self._signature_
        s2 = other._signature_
        return cmp(s1,s2)

class Id:

    def __init__(self):
        self.next_id = -1

    def new_id(self):
        self.next_id = self.next_id+1
        return '_'+str(self.next_id)

class Pool(Id):

    def __init__(self, text_inst=None):
        self.keys = []
        self.signatures = []
        self.dict = {}
        self.Text = text_inst

        Id.__init__(self)

    def __len__(self):
        return len(self.keys)

    def __getitem__(self, key):
        i = self.keys.index(key)
        sig = self.signatures[i]
        return self.dict[sig]

    def __setitem__(self, key, value):
        # XXX inconistency: keys should be created solely by pool
        try:
            i = self.keys.index(key)
            sig = value._signature_
        except:
            self.keys.append(key)
            sig = value._signature_
            self.signatures.append(sig)
        self.dict[sig] = value

    def __delitem__(self, key):
        i = self.keys.index(key)
        del self.keys[i]
        sig = self.signatures[i]
        del self.signatures[i]
        try:
            i = self.signatures.index(sig)
        except:
            del self.dict[sig]

    def dump(self):
        out = []
        print "______________ POOL DUMP __________"
        for i in range(len(self.keys)):
            sig = self.signatures[i]
            id = self.keys[i]
            if self.Text is not None:
                index = self.Text.index(id)
            else: index = ""
            out.append((index,  id, self.dict[sig]))
        for index, id, style in out:
            print index,"\t", id,"\t", style
        print "# of keys = ", len(self.keys)
        print "# of signatures = ", len(self.signatures)

    class Iterator:

        def __init__(self, pool):
            self.pool = pool
            self.i = -1
            self._update()

        def __repr__(self):
            return "Iterator of %s" % repr(self.pool)

        def __str__(self):
            if self.i<0:
                index = "1.0"
            elif self.i>=len(self.pool):
                index = "end"
            else:
                index = self.id
            return str(index)

        def _update(self):
            if self.i >= len(self.pool) or self.i <0:
                self.outofboundary = 1
                self.current = None
                self.id = None
            else:
                self.outofboundary = 0
                self.id = self.pool.keys[self.i]
                sig = self.pool.signatures[self.i]
                self.current = self.pool.dict[sig]

        def next(self):
            if self.i<len(self.pool):
                self.i = self.i+1
                self._update()
            return self.current

        def prev(self):
            if self.i>=0:
                self.i = self.i-1
                self._update()
            return self.current

        def insert_left(self, style, index=None):
            '''inserts stlye before index or if it is not given, after 
            current id'''
            texti = self._textinst()

            if index is None:
                index = self.current
                if index is None:
                    raise StyletextError(
                         "Can't insert at index: %s" % index)
            it = self.pool.iterator()
            it.before(index)
            it.next()
            it.align_left()

            # case 1: there is no mark before index
            if it.outofboundary:
                i = it.i

            # case 2: there is already a mark at index
            elif texti.compare(it, '==', index):
                it.align_left()
                i = it.i

            # case 3: there is no mark at index, but after index
            else:
                i = it.i
            sig = style._signature_
            id = self.pool.new_id()
            texti.mark_set(id, index)
            texti.mark_gravity(id, 'right')
            self.pool.keys.insert(i, id)
            self.pool.signatures.insert(i, sig)
            self.pool.dict[sig] = style
            self.i = i

            return self._update()

        def insert_right(self, style, index=None):
            '''inserts stlye after index or if it is not given, 
            after current id'''
            texti = self._textinst()

            if index is None:
                index = self.current
                if index is None:
                    raise StyletextError(
                         "Can't insert at index '%s'" % index)

            it = self.pool.iterator()
            it.after(index)
            it.align_right()

            # case 1: there is no mark at or after index
            if it.outofboundary:
                i = it.i

            # case 2: there is already a mark at index
            elif texti.compare(it, '==', index):
                it.align_right()
                i = it.i+1

            # case 3: there is no mark at index, but after index
            else:
                i = it.i

            sig = style._signature_
            id = self.pool.new_id()
            texti.mark_set(id, index)
            texti.mark_gravity(id, 'right')
            self.pool.keys.insert(i, id)
            self.pool.signatures.insert(i, sig)
            self.pool.dict[sig] = style
            self.i = i
            return self._update()

        def delete(self):
            texti = self._textinst()
            del self.pool.keys[self.i]
            del self.pool.signatures[self.i]
            texti.mark_unset(self.id)
            if self.i>len(self.pool):
                self.i = self.i-1
            self._update()

        def _textinst(self):
            '''Returns pools assigned text instance, error if no Text is
            assigned'''
            if self.pool.Text is None:
                raise StyletextError("pool has no 'text' instance")
            return self.pool.Text

        def guess(self, indexOrId):
            '''finds a style mark which is before indexOrId. Not Necessarily
            the nearest one.
            '''
            if len(self.pool) == 0:
                return  self._update()

            texti = self._textinst()

            # start with a good guess
            index = indexOrId
            while 1:
                mark = texti.mark_previous(index)
                #print "mark = ",mark
                if mark is None or type(mark)=='None':
                    # there is no mark before indexorid then
                    self.i = -1
                    return  self._update()
                if mark[0] == '_':
                    id = mark
                    break
                index = mark
            i = self.pool.keys.index(id)
            self.i = i
            return self._update()


        def after(self, indexOrId):
            '''finds last stylemark which is at index or, if there is none, 
            the next one'''
            if len(self.pool) == 0:
                return self._update()
            texti = self._textinst()
            it = self.pool.iterator()

            # start with a good guess
            it.guess(indexOrId)
            if it.i<0:
                it.next()

            i = it.i

            # fine tuning
            while texti.compare(self.pool.keys[i],'<', indexOrId):
                i = i+1
                if i>=len(self.pool):
                    break
            self.i = i

        def before(self, indexOrId):
            '''finds last style mark which is before indexOrId
            # XXX inconsistent to Tk: previous = next mark bevor or at index

            '''
            if len(self.pool) == 0:
                return  self._update()

            texti = self._textinst()
            it = self.pool.iterator()

            # start with a good guess
            it.guess(indexOrId)
            while (not it.outofboundary) and (texti.compare(it,'>=', \
                    indexOrId)):
                it.prev()

            if it.outofboundary:
                self.i = it.i
                return self._update()

            i = it.i
            # now fine tuning
            oi = i
            while texti.compare(self.pool.keys[i], '<',indexOrId):
                #~ print i, "<", texti.index(indexOrId)
                oi = i
                i = i+1
                if i>=len(self.pool):
                    break

            # now oi  is at the last stylemark which is before indexOrId
            self.i = oi
            return self._update()

        def set(self, id):
            self.i = self.pool.keys.index(id)
            self._update()
            return current

        def align_left(self):
            if self.outofboundary:
                return self.current
            ids = self.pool.keys
            compare = self._textinst().compare
            i = self.i

            while i>0 and i<len(self.pool) and compare(ids[i-1],'==',ids[i]):
                i = i-1
            self.i = i
            self._update()
            return self.current


        def align_right(self):
            if self.outofboundary:
                return self.current
            ids = self.pool.keys
            compare = self._textinst().compare
            i = self.i
            while i<len(ids)-1 and compare(ids[i],'==',ids[i+1]):
                i = i+1
            self.i = i
            self._update()
            return self.current

        def is_first(self):
            return self.i == 0

        def is_last(self):
            return self.i == len(self.pool)-1

    def iterator(self):
        return Pool.Iterator(pool=self)


if __name__=='__main__':
    from Tkinter import *
    tk = Tk()
    text = Text(tk)
    text.pack()
    for i in range(5):
        text.insert('end', '0123456789\n')
    pool = Pool(text)
    s1 = Style(q=1)
    s2 = Style(w=1)
    s3 = Style(w=1)
    if s2 == s3: print "error"
    if s2 != s3: print "error"
        
    i = pool.iterator()
    i.insert_left(Style(color = "blue"),'1.0')
    i.insert_left(Style(color = "red"),'2.0')
    i.insert_left(Style(color = "green"),'3.0')
    i.insert_left(Style(color = "black"),'1.0')
    i.insert_right(Style(color = "grey"),'1.0')

    pool.dump()
    i.after("1.0")
    print "after 1.0: ",i,i.i
    
    i.after("2.0")
    print "after 2.0: ",i,i.i