| StyledEditor |
UserPreferences |
| Tkinter Wiki | FrontPage | RecentChanges | TitleIndex | WordIndex | SiteNavigation | HelpContents | moin.sf.net |
First Beta, guarantted to be loaded with bugs!
This demo creates a widget with full "styled text editing" capabilities; sort of a mini-word processor. It runs "as is" on my WinXP machine with Python 2.5. The demo allows styling of any selected text via toolbars; just select the text, then select the styling. (Currently, it's not possible to select insertion styling). Also included are buttons to save and retrieve all content and styling information (works for the small tests I've tried myself, however, expect bugs!).
There are actualy three widgets created: StyledText (which contains my desired API), ?TextWriter (A StyledText object with toolbars all thrown into a Frame, and ?StyleEditor (A dialog box for allowing the user to create custom styles). StyledText widget subclasses the Text widget to give greater freedom in the assignment of any single styling attribute to any region. This differs from the Text widget in that the Text widget does not allow you to assign a family, size, weight or slant with tag_config(). That is, for example, you can't simply apply 'bold' to some region of text.
This demo was written quite quickly (I pounded it out over the weekend) so I'm sure it's full of bugs and may not be entirely tk-like. Future versions will strive to increase functionality, reduce bugs and make the widget more tk-like. Suggestions for imporvements are more than welcome.
applyStyleAttribute( index1, index2, attributeName, attributeValue )
This method is the frontend to the business. attributeName and attributeValue may be any option accpeted by tag_config() of the Text widget along with appropriate value. There are also some new options:
Several previously existing options have some new values:
--- These notes assume you understand the basics of using the text widget. --
To make the widget react more naturally when changing the value of 'offset' across a region, I found it convenient to make 'offset' A sub-option of the font object rather than a full option. In this way if we have some text which has (Ariel, 12, bold, superscript), the original size is preserved in the font. The actual tag in the text widget gets configured with {font:('Ariel',5,bold), offset='10p'} . Now if the user decides to remove the superscript styling, the information of the original size (12) is still available in the font object so it's easily restored. To implement this I defined my own class Font to use with the StyledText in place of tkFont. This class includes the very useful method tagOptions() which returns a dictionary of options suitable for passing to Text's tag_config() to produce the desired appearance. class Font manages the options: family, size, weight, slant and offset. Underline and Overstrike can be set independently via tag_config(), so they are not managed by Font.
The primary attribute styling class is class Style. This class is a subclass of dict which is intended to hold values for all the style options not part of ?StylerFont. class Style also contains a _font member and like, ?StylerFont, has the very useful tagOptions() method. This tagOptions will combine its own values with any it gets from calling tagOptions() on _font to form a complete set of values suitable for tag_config().
To simplify the seeming chaos of layered tags and overlapping tagged regions, I decided to first define some restrictions on how tags can be used.
These restrictions eliminate "Infinite depth tag stack" (criteria 2, 3 & 4) and "tagName redundancy" (criteria 5). Conceptually we now have just two styling layers: default styling on the bottom, custom styling on top. So, for example if I call applyStyleAttribute( begin, end, 'underline', Tkinter.TRUE ), any existing tags in the region (begin,end) which assign to 'underline', are first deleted if the new styling is something other than the default for the attribute being set, the new styling is applied.
With the tag chaos of the Text widget under control, it's now possible to design an algorithm which provides applyStyleAttribute() with a "map" of the current styling of the region in question. This map actually splits the region at every point that any tag in the region begins or ends (as well as the endpoints of the region itself). Here's an example to illustrate:
Sample Text: Sample text to illustrate a styling map of a region of text.
Indecies: 1 2 3 4 5 6
0123456789012345678901234567890123456789012345678901234567890
tag1: |<---------------->| |<--------------->|
tag2: |<----------->|
Region to map: |<-------------------------------------->|
Resulting map: |<->|<------->|<------>|<-->|<--->|<---->|
So here we have some Sample Text. tag1 spans regions 1.5 - 1.24 and 1.35 - 1.53, and tag2 spans 1.15 - 1.29. mapRegion() slices at any tag begin or tag end and at its endpoints this results in a map with six segments. For each segment in the map, the list of active tags is also given. So mapRegion() in the above example returns the following list: [ ( '1.1', '1.5', [ ] ), # No tags in this region ( '1.5', '1.15', [ 'tag1' ] ), # tag1-bold in this region ( '1.15', '1.24', [ 'tag1', 'tag2' ] ), # etc. ( '1.24', '1.29', [ 'tag2' ] ), ( '1.29', '1.35', [ ] ), ( '1.35', '1.42', [ 'tag1' ] ) ]
Next is to determine which attributes and values are set in each subregion. The obvious way is to have a dict mapping tagName, to Style object, but it's not the only way. We need to avoid tag-name redundancy, criterion 5 (E.g. We don't want to define a new tag for underline every time the user selects a bit of text and applies the underline style. We should use the same underline tag for all cases of underline). To handle this I use a standard naming convention for tags such that the name of the tag encodes the tag's configuration - this is reasonable because of criterion 2 (the names won't get too long). This also eliminates the need for a dictionary since the name of each tag can be decoded to get its configuration. Any tag which sets a ?StylerFont attribute (family, size, weight, slant or offset) has the tag named ast: "-font-%(family)s-%(size)d-%(weight)s-%(slant)s-%(offset)". The remaining attributes have tags named as: "-attribute-%(attributeName)s-%(attributeValue)s".
Now if applyStyleAttribute() gets an assignment to any ?StylerFont attribute, it iterates throught the subregions returned by mapRegion() if it there's a tag that begins "-font-..." (and there can be only one per criterion 3), then it asks ?StylerFont to decode the tag name and create a new ?StylerFont instance, then it deletes the tag from the text widget. Next it call's ?StylerFont's deriveFont(attributeName,newAttributeValue) which returns a new ?StylerFont instance. It calls tagOptions() and fontName() on the new font object to get what's needed to define and configure a new "-font-..." tag for the subregion.
Similarly, if applyStyleAttribute() gets an assignment to any other attribute, it iterates through the subregions returned by mapRegion(), if there's a tag that begins "-attribute-%(attributeName)s-" (and there can be only one per criterion 4), then it decodes the tag name the tag is deleted from the subregion in the underlying text widget, a new tag name and Style instance is creatd which are used to define and configure the new tag in the underlying text widget.
In that cases where applyStyleAttribute() is iterating over the subregions returned by mapRegion, and the subregion is empty or does not contain any styling on attributeName, then applyStyleAttribute assumes the default styling (criterion 1).
The code follows:
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 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 | import Tix as Tk
import tkFont as Font
DIALOG_FONT = 'Times 8'
DEFAULT_TEXT_FONT = ('Lucida Sans Unicode', 12)
class ImageFactory( object ):
_images = { }
@staticmethod
def makeImage( filename ):
if filename not in ImageFactory._images:
ImageFactory._images[ filename ] = Tk.PhotoImage( file=filename )
return ImageFactory._images[ filename ]
class StylerFont( object ):
FIELD_NAMES = [ 'family', 'size', 'weight', 'slant', 'offset', 'bold', 'italic' ]
FONT_TAG_FORMAT = '-font-%(family)s-%(size)d-%(weight)s-%(slant)s-%(offset)s'
FONT_TAG_PREFIX = '-font-'
FONT_LIBRARY = { }
DEFAULT_FONT = None
def __init__( self, fontOpts ):
self._fontOpts = fontOpts
def __setitem__( self, key, value ):
if key == 'bold':
self._fontOpts[ 'weight' ] = 'bold' if value else 'normal'
elif key == 'italic':
self._fontOpts[ 'slant' ] = 'italic' if value else 'roman'
else:
self._fontOpts[ key ] = value
def __getitem__( self, key ):
if key == 'bold':
return self._fontOpts[ 'weight' ] == 'bold'
elif key == 'italic':
return self._fontOpts[ 'slant' ] == 'italic'
else:
return self._fontOpts[ key ]
def fontName( self ):
return StylerFont.FONT_TAG_FORMAT % self._fontOpts
def fontOptions( self ):
return self._fontOpts
def tagOptions( self ):
options = { }
styleList = [ ]
if self._fontOpts['weight'] == 'bold':
styleList.append( 'bold' )
if self._fontOpts['slant'] == 'italic':
styleList.append( 'italic' )
if self._fontOpts['offset'] != 'normal':
# If the region includes an offset, we need to reestablish that
baseSize = self._fontOpts['size']
size = int(baseSize * (3.0 / 5.0) + 0.5)
if self._fontOpts['offset'] == 'superscript':
options[ 'offset' ] = '%dp' % int(baseSize / 2.0 + 0.5)
else:
options[ 'offset' ] = '-%dp' % int(baseSize / 5.0 + 0.5)
else:
size = self._fontOpts['size']
options[ 'font' ] = ( self._fontOpts['family'], size, ' '.join(styleList) )
return options
def deriveFont( self, **newOpts ):
newFont = copy.deepcopy( self )
for key,val in newOpts.iteritems():
newFont[ key ] = val
fontName = newFont.fontName( )
if fontName not in StylerFont.FONT_LIBRARY:
StylerFont.FONT_LIBRARY[ fontName ] = newFont
return StylerFont.FONT_LIBRARY[ fontName ]
def tkFont( self ):
return Font.Font( family=self._fontOpts['family'], size=self._fontOpts['size'], weight=self._fontOpts['weight'], slant=self._fontOpts['slant'] )
@staticmethod
def setup( aTextWidget ):
StylerFont.DEFAULT_FONT = StylerFont.getFont( aTextWidget['font'] )
StylerFont.FONT_LIBRARY[ 'default' ] = StylerFont.DEFAULT_FONT
@staticmethod
def getFont( aFontSpec=None, **options ):
fontOpts = { }
fontStyling = ''
if aFontSpec:
if isinstance( aFontSpec, (str,unicode) ):
if aFontSpec == 'default':
return StylerFont.FONT_LIBRARY[ 'default' ]
elif aFontSpec.startswith( StylerFont.FONT_TAG_PREFIX ):
# We have a font name
try:
return StylerFont.FONT_LIBRARY[ aFontSpec ]
except:
for key,val in zip( ['family','size','weight','slant','offset'], aFontSpec.split( '-' )[2:] ):
fontOpts[ key ] = val
fontOpts['size'] = int(fontOpts['size'])
StylerFont.FONT_LIBRARY[ aFontSpec ] = StylerFont( fontOpts )
return StylerFont.FONT_LIBRARY[ aFontSpec ]
else:
# We need to try to decode a tkinter font string
if aFontSpec[0] == '{':
fontFamilyStringBegin = 1
fontFamilyStringEnd = aFontSpec.find( '}' )
fontSize, sep, fontStyling = aFontSpec[ fontFamilyStringEnd + 2 : ].lower().partition( ' ' )
else:
fontFamilyStringBegin = 0
fontFamilyStringEnd = aFontSpec.find( ' ' )
fontSize, sep, fontStyling = aFontSpec[ fontFamilyStringEnd + 1 : ].lower().partition( ' ' )
fontOpts['family' ] = aFontSpec[ fontFamilyStringBegin : fontFamilyStringEnd ]
fontOpts['size' ] = int(fontSize)
elif isinstance( aFontSpec, (list,tuple) ):
# We need to decode a tkinter font tuple
fontStyling = aFontSpec[2] if len(aFontSpec)==3 else ''
fontOpts['family' ] = aFontSpec[0]
fontOpts['size' ] = aFontSpec[1]
elif options:
if 'family' in options:
if 'bold' in options:
options[ 'weight' ] = 'bold' if options['bold'] else 'normal'
del options[ 'bold' ]
if 'italic' in options:
options[ 'slant' ] = 'italic' if options['italic'] else 'roman'
del options[ 'italic' ]
fontName = StylerFont.FONT_TAG_FORMAT % options
try:
return StylerFont.FONT_LIBRARY[ fontName ]
except:
StylerFont.FONT_LIBRARY[ fontName ] = StylerFont( options )
return StylerFont.FONT_LIBRARY[ fontName ]
else:
fontTuple = options[ 'font' ]
fontStyling = aFontSpec[2] if len(aFontSpec)==3 else ''
fontOpts['family' ] = fontTuple[0]
fontOpts['size' ] = fontTuple[1]
else:
return StylerFont.getFont( 'default' )
fontOpts['weight' ] = 'bold' if 'bold' in fontStyling else 'normal'
fontOpts['slant' ] = 'italic' if 'italic' in fontStyling else 'roman'
fontOpts['underline' ] = False
fontOpts['overstrike'] = False
fontOpts['offset' ] = 'normal'
fontName = StylerFont.FONT_TAG_FORMAT % fontOpts
try:
return StylerFont.FONT_LIBRARY[ fontName ]
except:
theFontObj = StylerFont( fontOpts )
StylerFont.FONT_LIBRARY[ fontName ] = theFontObj
return theFontObj
class Style( dict ):
FIELD_NAMES = [ 'font', 'underline', 'overstrike', 'foreground', 'background' 'fgstipple', 'bgstipple', 'borderwidth', 'relief',
'justify', 'wrap', 'lmargin1', 'lmargin2', 'rmargin', 'spacing1', 'spacing2', 'spacing3', 'tabs' ]
ATTRIBUTE_TAG_FORMAT = '-attribute-%(name)s-%(value)s'
ATTRIBUTE_TAG_PREFIX = '-attribute-'
DEFAULT_STYLE = None
OFF_VALUES = { }
'''Most fields have the exact same set of possible values as the related option for the text widget.
'font' is a legitimate Style field. While any subfield of 'font' is not a style field of Style,
they are accepted by __init__, __setitem__ and __getitem__ but will simply be passed to the
StylerFont subobject. (e.g. family, may be requested of a style instance and will be passed to the
StylerFont object).
The 'offset' and the three 'spacing' options can take any of the usual values available to the text
widget. However, several new values are also possible for these fields.
font: StylerFont
family: string. A font family name
size: int. A font size in points
weight: string. One of: 'normal', 'bold'
bold: boolean. An alternate for weight
slant: string. One of: 'roman', 'italic'
italic: boolean. An alternate for slant
underline: boolean.
overstrike: boolean.
offset: Dimension or string. One of: 'normal', 'subscript', 'superscript'
foreground: Color.
background: Color.
fgstipple: bitmap.
bgstipple: bitmap.
borderwidth: Dimension.
relief: string. One of: 'flat', 'sunken', 'raised', 'groove', 'ridge', 'solid', ''
justify: string. One of: 'left', 'right', 'center', ''
wrap: string. One of: 'none', 'char', 'word', ''
lmargin1: Dimension.
lmargin2: Dimension.
rmargin: Dimension.
spacing1: Dimension or string. One of: 'None', 'Half Line', 'One Line', 'Two Lines'
spacing2: Dimension or string. One of: 'None', 'Half Line', 'One Line', 'Two Lines'
spacing3: Dimension or string. One of: 'None', 'Half Line', 'One Line', 'Two Lines'
tabs: string of Dimension.
'''
def __init__( self, **options ):
dict.__init__( self )
self._font = None
for key,value in options.iteritems( ):
if key == 'font':
if isinstance( value, StylerFont ):
self._font = value
else:
self._font = StylerFont( value )
else:
dict.__setitem__( self, key, value )
def __setitem__( self, key, value ):
if key in StylerFont.FIELD_NAMES:
if key == 'bold':
key = 'weight'
value = 'bold' if value else 'normal'
elif key == 'italic':
key = 'slant'
value = 'italic' if value else 'roman'
self._font[ key ] = value
else:
if (value in Style.OFF_VALUES[key]) or (value == Style.DEFAULT_STYLE[key]):
if key in self:
self.__delitem__( key )
else:
if key == 'font':
if isinstance( value, StylerFont ):
self._font = value
else:
self._font = StylerFont.getFont( value )
else:
dict.__setitem__( self, key, value )
def __getitem__( self, key ):
if key in StylerFont.FIELD_NAMES:
return self._font[ key ]
elif key in self:
return dict.__getitem__( self, key )
elif key == 'font':
return self._font
def tagOptions( self ):
options = { }
options.update( self )
try:
options.update( self._font.tagOptions( ) )
lineHeight = self._font.tkFont().metrics('linespace')
except:
lineHeight = Style.DEFAULT_STYLE._font.tkFont().metrics('linespace')
# Adjust fields with non-tk options
for spacingKind in [ 'spacing1', 'spacing2', 'spacing3' ]:
try:
selectedSpacing = options[ spacingKind ]
if selectedSpacing == 'None':
options[ spacingKind ] = '0'
elif selectedSpacing == 'Half Line':
options[ spacingKind ] = '%dp' % int(float(lineHeight * 0.5 + 0.5))
elif selectedSpacing == 'One Line':
options[ spacingKind ] = '%dp' % int(lineHeight)
elif selectedSpacing == 'Two Lines':
options[ spacingKind ] = '%dp' % int(lineHeight * 2)
else:
options[ spacingKind ] = selectedSpacing
except:
pass
return options
@staticmethod
def setup( aTextWidget ):
StylerFont.setup( aTextWidget )
Style.DEFAULT_STYLE = Style( font = StylerFont.DEFAULT_FONT,
foreground = aTextWidget[ 'foreground' ],
background = aTextWidget[ 'background' ],
fgstipple = '',
bgstipple = '',
borderwidth = 0,
relief = Tk.FLAT,
justify = Tk.LEFT,
wrap = Tk.CHAR,
lmargin1 = 0,
lmargin2 = 0,
rmargin = 0,
spacing1 = 0,
spacing2 = 0,
spacing3 = 0,
tabs = ''
)
Style.OFF_VALUES = {
# Font Attributes
'family': [ StylerFont.DEFAULT_FONT['family'] ],
'size': [ StylerFont.DEFAULT_FONT['size' ] ],
'weight': [ Font.NORMAL, None ],
'slant': [ Font.ROMAN, None ],
'offset': [ 'normal', '0', '0p', '0i', '0c', '0m', '', None ],
# Paragraph Attributes
'justify': [ Tk.LEFT, '', None ],
'wrap': [ Tk.CHAR, '', None ],
'lmargin1': [ '0', '0p', '0i', '0c', '0m', '', None ],
'lmargin2': [ '0', '0p', '0i', '0c', '0m', '', None ],
'rmargin': [ '0', '0p', '0i', '0c', '0m', '', None ],
'spacing1': [ '0', '0p', '0i', '0c', '0m', 'None', '', None ],
'spacing2': [ '0', '0p', '0i', '0c', '0m', 'None', '', None ],
'spacing3': [ '0', '0p', '0i', '0c', '0m', 'None', '', None ],
'tabs': [ '', None ],
# Other Attributes
'underline': [ Tk.FALSE, '0', 'false', 'False', False, '', None ],
'overstrike': [ Tk.FALSE, '0', 'false', 'False', False, '', None ],
'foreground': [ aTextWidget[ 'foreground' ], '', None ],
'background': [ aTextWidget[ 'background' ], '', None ],
'fgstipple': [ '', 'none', None ],
'bgstipple': [ '', 'none', None ],
'borderwidth':[ '0', '0p', '0i', '0c', '0m', '', None ],
'relief': [ Tk.FLAT, '', None ]
}
@staticmethod
def getStyle( aSpec=None, **options ):
if aSpec:
if isinstance( aSpec, str ):
if aSpec.startswith(StylerFont.FONT_TAG_PREFIX):
return StylerFont.getFont( aSpec )
elif aSpec.startswith(Style.ATTRIBUTE_TAG_PREFIX):
key,value = aSpec.replace( '_',' ' ).split('-')[2:]
theStyle = Style( )
theStyle[ key ] = value
return theStyle
if options:
return Style( **options)
class Styler( object ):
ATTRIBUTE_TAG_FORMAT = '-attribute-%s-%s' # name, value
ATTRIBUTE_TAG_PREFIX = '-attribute-'
def __init__( self, aTextWidget ):
self.text = aTextWidget
Style.setup( self.text )
self.reinitizlize( )
def reinitizlize( self, styles=None ):
self.text.delete( '1.0', Tk.END )
if styles:
self._styles = styles
else:
self._styles = { }
def applyStyleAttribute( self, index1, index2, attributeName, attributeValue ):
'''Applies an attribute name:value pair to a given region indicated by
index1, index2. Index1 is part of the region, index2 is not. Valid
values for name and value are the same as those accepted by Style.__setitem__().
'''
try:
index1 = self.text.index( index1 )
index2 = self.text.index( index2 )
except:
return
# Manipulate the styles and tags in the region
if attributeName in ( 'family', 'size', 'weight', 'slant', 'offset', 'bold', 'italic' ):
for beg, end, tagNameList in self.mapRegion( index1, index2 ):
# Get the old font info (oldFontOpts) and delete the styling tag
for oldTagName in tagNameList:
if oldTagName.startswith( StylerFont.FONT_TAG_PREFIX ):
currentFont = StylerFont.getFont( oldTagName )
self.text.tag_remove( oldTagName, beg, end )
break
else:
currentFont = StylerFont.getFont( )
# Calculating & Install new values
newFont = currentFont.deriveFont( **{ attributeName:attributeValue } )
newTagName = newFont.fontName( )
self.text.tag_add( newTagName, beg, end )
self.text.tag_config( newTagName, **newFont.tagOptions() )
else:
for beg, end, tagNameList in self.mapRegion( index1, index2 ):
# If the attribute already exists, remove it.
for oldTagName in tagNameList:
if oldTagName.startswith( Styler.ATTRIBUTE_TAG_PREFIX + attributeName + '-' ):
self.text.tag_remove( oldTagName, beg, end )
break
# If we're just deactivating, then we're done
if attributeValue in Style.OFF_VALUES[ attributeName ]:
continue
# Calculate the new values
newTagName = Styler.ATTRIBUTE_TAG_FORMAT % ( attributeName, str(attributeValue) )
# Install the new values
self.text.tag_add( newTagName, beg, end )
self.text.tag_config( newTagName, **{ attributeName : attributeValue } )
def tagNames( self, index1, index2=None ):
tagNames = list(self.text.tag_names( index ))
if 'sel' in styles:
tagNames.remove( 'sel' )
if not index2:
return tagNames
for action, tagName, index in self.text.dump( '1.0', Tk.END, tag=True ):
if action == 'tagon':
tagNames.append( tagName )
# Rearrange the names into tag stack order
result = [ ]
for name in self.text.tag_names( ):
if name in tagNames:
result.append( name )
return result
def attributesAtIndex( self, index ):
index = self.text.index( index )
styles = self.tagNames( index )
tagOpts = { }
fontOpts = { }
for styleName in styles:
if styleName.startswith( StylerFont.FONT_TAG_PREFIX ):
font = StylerFont.getFont( styleName )
tagOpts.update( **font.tagOptions() )
fontOpts = font.fontOptions( )
else:
attribStyleName = styleName.replace( '_', ' ' )
attribName, attribValue = attribStyleName.split( '-' )[ 2: ]
tagOpts[ attribName ] = attribValue
return tagOpts, fontOpts
def mapRegion( self, index1, index2 ):
'''This method returns a map of the styles for a given region. The result
is a list of 'subregion' style descriptions of the form:
( beginIndex, endIndex, [ activeStyleNames ] )
The list is guaranteed complete. beginIndex of the first subregion
description will always equal index1, and endIndex of the last subregion
will always equal index2. Further, for any two adjacent subregion
descriptions endIndex of the first will always equal beginIndex of the
second. Thus no gaps occur in the map.
'''
# Build a complete dump of the region
index1 = self.text.index( index1 )
index2 = self.text.index( index2 )
theDump = self.text.dump( index1, index2, tag=True )
if len(theDump) == 0:
return theDump
# Consolidate the Dump
finalReport = [ ]
activeTags = list( self.text.tag_names( index1 ) )
if 'sel' in activeTags:
activeTags.remove( 'sel' )
currentIndex = index1
for action, tag, index in theDump:
if tag == 'sel':
continue
if index != currentIndex:
finalReport.append( ( currentIndex, index, copy.copy(activeTags) ) )
currentIndex = index
if action == 'tagon':
if tag not in activeTags:
activeTags.append( tag )
elif action == 'tagoff':
activeTags.remove( tag )
if len(finalReport) == 0:
finalReport = [ ( index1, index2, activeTags ) ]
else:
if finalReport[-1][1] != index2:
finalReport.append( ( finalReport[-1][1], index2, copy.copy(activeTags) ) )
return finalReport
class Edit( Tk.Frame ):
NAME_COUNTER = 1
def __init__( self, parent, **options ):
Tk.Frame.__init__( self, parent )
self.text = None
self.styler = None
self._images = { }
self._windows = { }
self._fgColorBtn = None
self._bgColorBtn = None
self._styleCombo = None
self._currentFontName = Tk.StringVar( )
self._currentFontSize = Tk.StringVar( )
self._currentFontOffset = Tk.StringVar( )
self._currentFGStipple = Tk.StringVar( )
self._currentBGStipple = Tk.StringVar( )
self._currentBorder = Tk.StringVar( )
self._currentRelief = Tk.StringVar( )
self._currentJustify = Tk.StringVar( )
self._currentWrap = Tk.StringVar( )
self._currentLMargin1 = Tk.StringVar( )
self._currentLMargin2 = Tk.StringVar( )
self._currentRMargin = Tk.StringVar( )
self._currentSpacing1 = Tk.StringVar( )
self._currentSpacing2 = Tk.StringVar( )
self._currentSpacing3 = Tk.StringVar( )
self._currentTabs = Tk.StringVar( )
self._currentStyle = Tk.StringVar( )
self.buildGUI( **options )
def reinitialize( self, styles=None ):
self |