Using <font> (font tag) within pys60 Text widget
difficult to use. You need to set each attribute
(font, style, highlight, color) of the widget
before adding more text with differert style.
So, I make a function that make it a bit easier.
The font tag (<font></font>) is used (borrowed from HTML).
Attributes allowed are
- color ( #RRGGBB or 0xRRGGBB or color name)
- face ( both font and size eg. albi17b )
- style ( bold, italic, underline or strikethrough )
(styles can be combined using comma)
- highlight ( standard, rounded, shadow)
- hcolor ( highlight color )
1 2 from appuifw import * 3 4 def process_color(color): 5 color_name = { 6 'red': 0xff0000, 'green': 0x008000, 'blue':0x0000ff, 7 'black': 0, 'white':0xffffff, 'yellow': 0xffff00 8 } 9 if color.startswith('#'): # HTML format #000000 10 return int(color[1:], 16) 11 if color.startswith('0x'): # pys60 format 0x000000 12 return int(color, 16) 13 return color_name[color] 14 15 def set_ml(t, s): 16 stack = [] 17 t.clear() 18 t.font = 'normal' 19 i = 0 20 while i < len(s): 21 if s.startswith('<', i): # tag end or tag begin 22 j = s.find('>', i) + 1 23 if s[i:i+7] == '</font>' or s[i:i+3] == '</>': 24 t.color, t.font, t.style, t.highlight_color = stack.pop() 25 else: 26 stack.append([t.color, t.font, t.style, t.highlight_color]) 27 to_style = 0 28 for attr_val in s[i:j-1].split(' '): 29 if '=' in attr_val: 30 attr, val = attr_val.split('=') 31 if attr == 'color': 32 t.color = process_color(val) 33 elif attr == 'face': 34 t.font = unicode(val) 35 elif attr == 'hcolor': 36 t.highlight_color = process_color(val) 37 elif attr == 'style': # style and highlight go together 38 to_style |= eval('|'.join(['STYLE_' + st.upper() for st in val.split(',')])) 39 elif attr == 'highlight': 40 to_style |= eval("HIGHLIGHT_" + val.upper()) 41 if to_style: 42 t.style = to_style 43 else: # normal text 44 j = s.find('<', i) 45 if j == -1: j = len(s) 46 text = u'' + s[i:j].replace('<', '<') 47 t.add(text) 48 i = j # go next chunk 49
Now you can use it easily
1 2 >>> t = app.body # use the default Text widget that start pys60 3 >>> set_ml(t, '<font color=red>Hello</font> <font style=bold>World</font>.') 4 >>> # a stylish 'Hello World' is displayed
Notice:
- Quotation marks are not used to specify attribute values.
- A </> shorthand can be used for </font>
- <font> can be nested.