File: TextEditor.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 (503 lines) | stat: -rw-r--r-- 16,200 bytes parent folder | download | duplicates (2)
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
# 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


from styletext import StyleText, Style
import Tkinter
from Tkconstants import *
from tkFileDialog import asksaveasfilename, asksaveasfilename, \
     askopenfilename
from Sketch.Graphics import font
from Sketch import _

from cPickle import loads, dumps
import os


def raw2styling(raw):
    styling = []
    for l, line, char in raw:
        if l == 0:
            style = None
        else:
            style = apply(Style, [], {l[0] : l[1]})
        styling.append((style, line, char))
    return styling
    
def styling2raw(styling):
    raw_styling = []
    for style, line, char in styling:
        if style is not None:
            l = (style.sort, style.options)
        else:
            l = 0
        raw_styling.append((l, line, char))
    return raw_styling
    
    
    
st_signature = '## styletext '
def load_text(name):
    file = open(name, 'r')
    s = file.read()
    file.close()
    styling = []
    len_sig = len(st_signature)

    if s[:len_sig] == st_signature:
        text, raw = loads(s[len_sig:])
        styling = raw2styling(raw)
    else:
        # assume plain text otherwise
        text = s
    return text, styling

def save_text(name, text, styling=[]):
    file = open(name, 'w')
    if name[-3:] == '.st':
        raw = styling2raw(styling)
        s = st_signature + dumps((text, raw))
    else:
        s = text

    file.write(s)
    file.close()


class font_families:
    def __init__(self):
        self.family_to_fonts = font.make_family_to_fonts()
        self.families = self.family_to_fonts.keys()
        self.families.sort()

    def xlfd(self, **kw):
        fonts = self.family_to_fonts[kw['family']]
        list = kw['attr'][:]
        last = fonts[-1]
        family, attrs, xlfd_start, encoding = font.fontmap[last]
        list.append(attrs)
        for name in fonts:
            family, attrs, xlfd_start, encoding = font.fontmap[name]
            if attrs in list:
                return font.xlfd_template % (xlfd_start, kw['size'],
                                                 encoding)

    def ps(self, **kw):
        family = kw['family']
        fonts = self.family_to_fonts[family]
        list = kw['attr'][:]
        last = fonts[-1]
        family, attrs, xlfd_start, encoding = font.fontmap[last]
        list.append(attrs)
        for name in fonts:
            family, attrs, xlfd_start, encoding = font.fontmap[name]
            if attrs in list:
                    return name
        return ''

font.read_font_dirs()
FONTS = font_families()
std_sizes = (8, 9, 10, 12, 14, 18, 24, 36, 48, 72)



class TextEditor(StyleText):
    def __init__(self, parent=None, **kw):
        self.top = parent
        apply(StyleText.__init__, (self, parent), kw)

        self.register_sort('family', self.FamilySort, 'Times' )
        self.register_sort('bold', self.BoldSort, 0)
        self.register_sort('italic', self.ItalicSort, 0)
        self.register_sort('size', self.SizeSort, 12)
        self.register_sort('color', self.ColorSort, 'black' )
        self.register_sort('supersub', self.SupersubSort, 'normal' )
        self.plain_options = {'size':14, 'color':'black'}

        bar = Tkinter.Frame(parent)
        self._make_menu()

        self.bind('<ButtonRelease-1>', lambda e, s=self: s.Update())
        self.bind('<KeyRelease>', lambda e, s=self: s.Update())

        rightFrame = Tkinter.Frame(bar)
        self.button_apply = Tkinter.Button(rightFrame, text='apply')
        self.button_apply.pack()
        rightFrame.pack(side='right')
        bar.pack(side = 'top', fill = 'x')

    def _make_menu(self):
        # make menu button
        menu = Tkinter.Menu(self)
        menu.file = Tkinter.Menu(menu)

        menu.file.add_command(label='Load', command=self.load)
        menu.file.add_command(label='Save', command=self.saveas)
        menu.file.add_command(label='Insert', command=self.insert_file)


        menu.options = Tkinter.Menu(menu)
        self._plainmode_state = Tkinter.IntVar()
        menu.options.add_checkbutton(label='Plain mode', \
            variable = self._plainmode_state,
            command = lambda s=self: s.fontify('1.0', 'end'))

        menu.family = Tkinter.Menu(menu)
        for f in FONTS.families:
            menu.family.add_command(label=f,
                command=lambda s=self, f=f: s.change_family(f))

        menu.size = Tkinter.Menu(menu)
        for f in std_sizes:
            menu.size.add_command(label=f,
                command=lambda s=self, f=f: s.change_size(f))

        menu.color = Tkinter.Menu(menu)
        for f in ('black', 'darkgray', 'gray', 'lightgray', 'blue', 'cyan',
                  'green', 'magenta', 'red', 'yellow', 'white'):
            menu.color.add_command(label=f, \
                command=lambda s=self, f=f: s.change_color(f),
                background = f)

        # definition of the menu one level up...
        menu.add_cascade(
            label='File',
            menu=menu.file)
        menu.add_cascade(
            label='Options',
            menu=menu.options)

        menu.add_separator()

        menu.add_cascade(
            label='Font Family',
            menu=menu.family)

        menu.add_cascade(
            label='Size',
            menu=menu.size)

        menu.add_cascade(
            label='Color',
            menu=menu.color)

        self._bold_state = Tkinter.IntVar()
        self._italic_state = Tkinter.IntVar()

        menu.add_checkbutton(label=_('Bold'), \
                             variable=self._bold_state,
                             command=lambda s=self, i=self._bold_state: \
                                     s.change_bold(i.get())
                            )
        menu.add_checkbutton(label=_("Italic"),
                             variable=self._italic_state,
                             command=lambda s=self, i=self._italic_state: \
                                     s.change_italic(i.get())
                            )

        self._subscript_state = Tkinter.IntVar()
        self._superscript_state = Tkinter.IntVar()

        menu.add_checkbutton(label=_("Subscript"), \
            variable=self._subscript_state,
            command=lambda s=self, i=self._subscript_state: \
                    s.change_subscript(i.get())
            )
        menu.add_checkbutton(label=_("Superscript"), \
            variable=self._superscript_state,
            command=lambda s=self, i=self._superscript_state: \
                    s.change_superscript(i.get())
            )

        self.menu = menu
        self.bind('<Button-3>',
                  lambda e, s=self: s.menu.tk_popup(e.x_root, e.y_root))
                      
    def warn(self, title, message):
        # This will be overridden
        pass
        
    def _update_menu(self):
        styles = self.style_get('insert')
        dict = {}
        for style in styles:
            dict[style.sort] = style.options

        self.menu.entryconfigure(4, label=dict['family'])
        self.menu.entryconfigure(5, label=dict['size'])
        self.menu.entryconfigure(6, foreground=dict['color'])
        supersub = dict['supersub']
        self._superscript_state.set(supersub=='superscript')
        self._subscript_state.set(supersub=='subscript')

        self._bold_state.set(dict['bold'])
        self._italic_state.set(dict['italic'])

    def Update(self):
        self._update_menu()

    def ColorSort(self, tagoptions, alloptions):
        if not self._plainmode_state.get():
            tagoptions['foreground'] = alloptions['color']
        else:
            tagoptions['foreground'] = self.plain_options['color']

    
    def SupersubSort(self, tagoptions, alloptions):
        if self._plainmode_state.get():
            size = self.plain_options['size']
        else:
            size = alloptions['size']

        option = alloptions['supersub']
        if option == 'subscript':
            alloptions['size'] = size * 0.5
            tagoptions['offset'] = -size * 0.2
        elif option == 'superscript':
            alloptions['size'] = size * 0.5
            tagoptions['offset'] = size * 0.6

    def FamilySort(self, tagoptions, alloptions):
        pass
    
    def ItalicSort(self, tagoptions, alloptions):
        pass
    
    def BoldSort(self, tagoptions, alloptions):
        pass
    
    def SizeSort(self, tagoptions, alloptions):
        dict = {}
        if not self._plainmode_state.get():
            dict['size'] = int(round(alloptions['size']))
        else:
            dict['size'] = self.plain_options['size']

        dict['family'] = alloptions['family']
        bold = alloptions['bold']
        italic = alloptions['italic']
        if bold and italic:
            dict['attr'] = ['Bold Italic', 'Bold Oblique', 'Demi Oblique', 'Demi Italic', 'Medium Italic', 'Demi Bold Italic']
        elif bold:
            dict['attr'] = ['Bold', 'Demi', 'Medium', 'Demi Bold']
        elif italic:
            dict['attr'] = ['Italic', 'Oblique', 'Book Oblique', 'Light Italic', 'Regular Oblique', 'Regular Italic']
        else:
            dict['attr'] = ['Roman', 'Book', 'Light', 'Regular']

        xfont = apply(FONTS.xlfd, (), dict)
        tagoptions['font'] = xfont


    def change_set(self, style):
        range = self.tag_ranges('sel')
        if len(range) == 2:
            apply(self.style_add,(style,)+self.tag_ranges('sel'))
        else:
            self.style_force.append(style)
        self.Update()

    def change_bold(self, state):
        style = Style(bold=state)
        self.change_set(style)

    def change_subscript(self, state):
        if state:
            self._superscript_state.set(0)
            style = Style(supersub='subscript')
        else:
            style = Style(supersub='normal')
        self.change_set(style)


    def change_superscript(self, state):
        if state:
            self._subscript_state.set(0)
            style = Style(supersub='superscript')
        else:
            style = Style(supersub='normal')
        self.change_set(style)

    def change_italic(self, state):
        style = Style(italic=state)
        self.change_set(style)

    def change_family(self, family):
        style = Style(family=family)
        self.change_set(style)

    def change_size(self, size):
        style = Style(size=size)
        self.change_set(style)

    def change_color(self, color):
        style = Style(color=color)
        self.change_set(style)

    def load(self, event=None):
        name = askopenfilename( \
            filetypes=[(_("styletext files"), "*.st"), \
                        (_("all files"), "*")])
        if name:
            try:
                text, styling = load_text(name) 
            except Exception, value:
                self.warn( 
                    title = _("Load File"),
                    message = _("Cannot load %(filename)s:\n"
                               "%(message)s") \
                    % {'filename':`os.path.split(name)[1]`,
                      'message':value})
                return
            index = '1.0'
            self.style_removeall()
            self.delete('1.0', 'end')
            self.insert(index, text)
            self.styling_apply(index, styling)

    def saveas(self, event=None):
        name = asksaveasfilename( \
            filetypes=[(_("styletext files"), "*.st"), \
                        (_("all files"), "*")])
        if name:
            text = self.get('1.0', 'end')
            styling = self.styling_get('1.0', 'end')
            try:
                save_text(name, text, styling)
            except IOError, value:
                self.warn( 
                    title = _("Save File"),
                    message = _("Cannot Save %(filename)s:\n"
                               "%(message)s") \
                    % {'filename':`os.path.split(name)[1]`,
                      'message':value})

    def insert_file(self, event=None):
        name = askopenfilename( \
            filetypes=[(_("styletext files"), "*.st"), \
                        (_("all files"), "*")])
        if name:
            try:
                text, styling = load_text(name) 
            except Exception, value:
                self.warn( 
                    title = _("Insert File"),
                    message = _("Cannot insert %(filename)s:\n"
                               "%(message)s") \
                    % {'filename':`os.path.split(name)[1]`,
                      'message':value})
                return
            
            index = self.index('insert')
            self.insert(index, text)
            self.styling_apply(index, styling)
    


def test1():
    tk = Tkinter.Tk()
    text = TextEditor(tk, background='white')
    text.pack(fill=BOTH, expand=1)
    text.insert(END,'1\n2\n3\n4\n5\n')
    text.fontify('1.0','end')
    text.style_add(Style(size=24), '2.0','3.0')
    text.style_add(Style(size=36), '4.0','5.0')
    text.fontify('1.0','end')
    text.bind('<Control-l>', text.load)
    text.bind('<Control-s>', text.saveas)
    text.bind('<Control-i>', text.insert_file)

    raw_input()

def waste():
    global text
    print "profiling"
    for i in range(1000):
        text.insert('250.10', "x")

def test2():
    #
    # profiling
    tk = Tkinter.Tk()
    global text
    text = TextEditor(tk, background='white')
    text.pack(fill=BOTH, expand=1)
    n = 500
    print "n =", n
    for i in range(n):
#        print i
        text.insert(END, '1234567890abcdefghij\n')
        text.style_add(Style(sizesort, size=24), 'end -5 chars',
                       'end -3 chars')
        text.style_add(Style(familysort, family="Helvetica"), 'end -5 chars',
                       'end -3 chars')
        text.style_add(Style(attrsort, attr="Italic"), 'end -5 chars',
                       'end -3 chars')

    from profile import run
    run("waste()")

def test3():
    tk = Tkinter.Tk()
    text = TextEditor(tk, background='white')
    text.pack(fill=BOTH, expand=1)
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.style_add(Style(size = 24), '1.0','4.0')
    text.style_add(Style(size = 24), '2.0','3.0')
    text.pool.dump()

def test4():
    tk = Tkinter.Tk()
    text = TextEditor(tk, background='white')
    text.pack(fill=BOTH, expand=1)
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.style_add(Style(size = 24), '2.0','3.0')
    text.style_add(Style(size = 24), '1.0','4.0')
    text.pool.dump()


def test5():
    tk = Tkinter.Tk()
    text = TextEditor(tk, background='white')
    text.pack(fill=BOTH, expand=1)
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.insert(END,'1234567890\n')
    text.style_add(Style(size = 24), '1.0','3.0')
    text.style_add(Style(size = 24), '2.0','4.0')
    text.pool.dump()

if __name__=='__main__':
    import sys
    sys.path.append('/usr/lib/sketch-0.6.12/')
    # 
    test1()
    
    #
    #~ for test in (test3, test4, test5):
        #~ print "\n", test.__name__
        #~ apply(test)