PageRenderTime 366ms CodeModel.GetById 31ms RepoModel.GetById 1ms app.codeStats 0ms

/tools/grit/grit/node/message.py

https://github.com/bluebellzhy/chromium
Python | 247 lines | 209 code | 18 blank | 20 comment | 6 complexity | 32cd81c601a6f060ae18b2695141b2a2 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-3.0, BSD-3-Clause, MPL-2.0-no-copyleft-exception, LGPL-2.1
  1. #!/usr/bin/python2.4
  2. # Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
  3. # Use of this source code is governed by a BSD-style license that can be
  4. # found in the LICENSE file.
  5. '''Handling of the <message> element.
  6. '''
  7. import re
  8. import types
  9. from grit.node import base
  10. import grit.format.rc_header
  11. import grit.format.rc
  12. from grit import clique
  13. from grit import exception
  14. from grit import tclib
  15. from grit import util
  16. # Finds whitespace at the start and end of a string which can be multiline.
  17. _WHITESPACE = re.compile('(?P<start>\s*)(?P<body>.+?)(?P<end>\s*)\Z',
  18. re.DOTALL | re.MULTILINE)
  19. class MessageNode(base.ContentNode):
  20. '''A <message> element.'''
  21. # For splitting a list of things that can be separated by commas or
  22. # whitespace
  23. _SPLIT_RE = re.compile('\s*,\s*|\s+')
  24. def __init__(self):
  25. super(type(self), self).__init__()
  26. # Valid after EndParsing, this is the MessageClique that contains the
  27. # source message and any translations of it that have been loaded.
  28. self.clique = None
  29. # We don't send leading and trailing whitespace into the translation
  30. # console, but rather tack it onto the source message and any
  31. # translations when formatting them into RC files or what have you.
  32. self.ws_at_start = '' # Any whitespace characters at the start of the text
  33. self.ws_at_end = '' # --"-- at the end of the text
  34. # A list of "shortcut groups" this message is in. We check to make sure
  35. # that shortcut keys (e.g. &J) within each shortcut group are unique.
  36. self.shortcut_groups_ = []
  37. def _IsValidChild(self, child):
  38. return isinstance(child, (PhNode))
  39. def _IsValidAttribute(self, name, value):
  40. if name not in ['name', 'offset', 'translateable', 'desc', 'meaning',
  41. 'internal_comment', 'shortcut_groups', 'custom_type',
  42. 'validation_expr']:
  43. return False
  44. if name == 'translateable' and value not in ['true', 'false']:
  45. return False
  46. return True
  47. def MandatoryAttributes(self):
  48. return ['name|offset']
  49. def DefaultAttributes(self):
  50. return {
  51. 'translateable' : 'true',
  52. 'desc' : '',
  53. 'meaning' : '',
  54. 'internal_comment' : '',
  55. 'shortcut_groups' : '',
  56. 'custom_type' : '',
  57. 'validation_expr' : '',
  58. }
  59. def GetTextualIds(self):
  60. '''
  61. Returns the concatenation of the parent's node first_id and
  62. this node's offset if it has one, otherwise just call the
  63. superclass' implementation
  64. '''
  65. if 'offset' in self.attrs:
  66. # we search for the first grouping node in the parents' list
  67. # to take care of the case where the first parent is an <if> node
  68. grouping_parent = self.parent
  69. import grit.node.empty
  70. while grouping_parent and not isinstance(grouping_parent,
  71. grit.node.empty.GroupingNode):
  72. grouping_parent = grouping_parent.parent
  73. assert 'first_id' in grouping_parent.attrs
  74. return [grouping_parent.attrs['first_id'] + '_' + self.attrs['offset']]
  75. else:
  76. return super(type(self), self).GetTextualIds()
  77. def IsTranslateable(self):
  78. return self.attrs['translateable'] == 'true'
  79. def ItemFormatter(self, t):
  80. if t == 'rc_header':
  81. return grit.format.rc_header.Item()
  82. elif (t in ['rc_all', 'rc_translateable', 'rc_nontranslateable'] and
  83. self.SatisfiesOutputCondition()):
  84. return grit.format.rc.Message()
  85. else:
  86. return super(type(self), self).ItemFormatter(t)
  87. def EndParsing(self):
  88. super(type(self), self).EndParsing()
  89. # Make the text (including placeholder references) and list of placeholders,
  90. # then strip and store leading and trailing whitespace and create the
  91. # tclib.Message() and a clique to contain it.
  92. text = ''
  93. placeholders = []
  94. for item in self.mixed_content:
  95. if isinstance(item, types.StringTypes):
  96. text += item
  97. else:
  98. presentation = item.attrs['name'].upper()
  99. text += presentation
  100. ex = ' '
  101. if len(item.children):
  102. ex = item.children[0].GetCdata()
  103. original = item.GetCdata()
  104. placeholders.append(tclib.Placeholder(presentation, original, ex))
  105. m = _WHITESPACE.match(text)
  106. if m:
  107. self.ws_at_start = m.group('start')
  108. self.ws_at_end = m.group('end')
  109. text = m.group('body')
  110. self.shortcut_groups_ = self._SPLIT_RE.split(self.attrs['shortcut_groups'])
  111. self.shortcut_groups_ = [i for i in self.shortcut_groups_ if i != '']
  112. description_or_id = self.attrs['desc']
  113. if description_or_id == '' and 'name' in self.attrs:
  114. description_or_id = 'ID: %s' % self.attrs['name']
  115. message = tclib.Message(text=text, placeholders=placeholders,
  116. description=description_or_id,
  117. meaning=self.attrs['meaning'])
  118. self.clique = self.UberClique().MakeClique(message, self.IsTranslateable())
  119. for group in self.shortcut_groups_:
  120. self.clique.AddToShortcutGroup(group)
  121. if self.attrs['custom_type'] != '':
  122. self.clique.SetCustomType(util.NewClassInstance(self.attrs['custom_type'],
  123. clique.CustomType))
  124. elif self.attrs['validation_expr'] != '':
  125. self.clique.SetCustomType(
  126. clique.OneOffCustomType(self.attrs['validation_expr']))
  127. def GetCliques(self):
  128. if self.clique:
  129. return [self.clique]
  130. else:
  131. return []
  132. def Translate(self, lang):
  133. '''Returns a translated version of this message.
  134. '''
  135. assert self.clique
  136. return self.clique.MessageForLanguage(lang,
  137. self.PseudoIsAllowed(),
  138. self.ShouldFallbackToEnglish()
  139. ).GetRealContent()
  140. def NameOrOffset(self):
  141. if 'name' in self.attrs:
  142. return self.attrs['name']
  143. else:
  144. return self.attrs['offset']
  145. # static method
  146. def Construct(parent, message, name, desc='', meaning='', translateable=True):
  147. '''Constructs a new message node that is a child of 'parent', with the
  148. name, desc, meaning and translateable attributes set using the same-named
  149. parameters and the text of the message and any placeholders taken from
  150. 'message', which must be a tclib.Message() object.'''
  151. # Convert type to appropriate string
  152. if translateable:
  153. translateable = 'true'
  154. else:
  155. translateable = 'false'
  156. node = MessageNode()
  157. node.StartParsing('message', parent)
  158. node.HandleAttribute('name', name)
  159. node.HandleAttribute('desc', desc)
  160. node.HandleAttribute('meaning', meaning)
  161. node.HandleAttribute('translateable', translateable)
  162. items = message.GetContent()
  163. for ix in range(len(items)):
  164. if isinstance(items[ix], types.StringTypes):
  165. text = items[ix]
  166. # Ensure whitespace at front and back of message is correctly handled.
  167. if ix == 0:
  168. text = "'''" + text
  169. if ix == len(items) - 1:
  170. text = text + "'''"
  171. node.AppendContent(text)
  172. else:
  173. phnode = PhNode()
  174. phnode.StartParsing('ph', node)
  175. phnode.HandleAttribute('name', items[ix].GetPresentation())
  176. phnode.AppendContent(items[ix].GetOriginal())
  177. if len(items[ix].GetExample()) and items[ix].GetExample() != ' ':
  178. exnode = ExNode()
  179. exnode.StartParsing('ex', phnode)
  180. exnode.AppendContent(items[ix].GetExample())
  181. exnode.EndParsing()
  182. phnode.AddChild(exnode)
  183. phnode.EndParsing()
  184. node.AddChild(phnode)
  185. node.EndParsing()
  186. return node
  187. Construct = staticmethod(Construct)
  188. class PhNode(base.ContentNode):
  189. '''A <ph> element.'''
  190. def _IsValidChild(self, child):
  191. return isinstance(child, ExNode)
  192. def MandatoryAttributes(self):
  193. return ['name']
  194. def EndParsing(self):
  195. super(type(self), self).EndParsing()
  196. # We only allow a single example for each placeholder
  197. if len(self.children) > 1:
  198. raise exception.TooManyExamples()
  199. class ExNode(base.ContentNode):
  200. '''An <ex> element.'''
  201. pass