PageRenderTime 317ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

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

https://github.com/akesling/chromium
Python | 267 lines | 226 code | 19 blank | 22 comment | 6 complexity | ecf6145e42eb9818a851e9322008968b MD5 | raw file
  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', 'use_name_for_id']:
  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. 'use_name_for_id' : 'false',
  59. }
  60. def GetTextualIds(self):
  61. '''
  62. Returns the concatenation of the parent's node first_id and
  63. this node's offset if it has one, otherwise just call the
  64. superclass' implementation
  65. '''
  66. if 'offset' in self.attrs:
  67. # we search for the first grouping node in the parents' list
  68. # to take care of the case where the first parent is an <if> node
  69. grouping_parent = self.parent
  70. import grit.node.empty
  71. while grouping_parent and not isinstance(grouping_parent,
  72. grit.node.empty.GroupingNode):
  73. grouping_parent = grouping_parent.parent
  74. assert 'first_id' in grouping_parent.attrs
  75. return [grouping_parent.attrs['first_id'] + '_' + self.attrs['offset']]
  76. else:
  77. return super(type(self), self).GetTextualIds()
  78. def IsTranslateable(self):
  79. return self.attrs['translateable'] == 'true'
  80. def ItemFormatter(self, t):
  81. if t == 'rc_header':
  82. return grit.format.rc_header.Item()
  83. elif (t in ['rc_all', 'rc_translateable', 'rc_nontranslateable'] and
  84. self.SatisfiesOutputCondition()):
  85. return grit.format.rc.Message()
  86. else:
  87. return super(type(self), self).ItemFormatter(t)
  88. def EndParsing(self):
  89. super(type(self), self).EndParsing()
  90. # Make the text (including placeholder references) and list of placeholders,
  91. # then strip and store leading and trailing whitespace and create the
  92. # tclib.Message() and a clique to contain it.
  93. text = ''
  94. placeholders = []
  95. for item in self.mixed_content:
  96. if isinstance(item, types.StringTypes):
  97. text += item
  98. else:
  99. presentation = item.attrs['name'].upper()
  100. text += presentation
  101. ex = ' '
  102. if len(item.children):
  103. ex = item.children[0].GetCdata()
  104. original = item.GetCdata()
  105. placeholders.append(tclib.Placeholder(presentation, original, ex))
  106. m = _WHITESPACE.match(text)
  107. if m:
  108. self.ws_at_start = m.group('start')
  109. self.ws_at_end = m.group('end')
  110. text = m.group('body')
  111. self.shortcut_groups_ = self._SPLIT_RE.split(self.attrs['shortcut_groups'])
  112. self.shortcut_groups_ = [i for i in self.shortcut_groups_ if i != '']
  113. description_or_id = self.attrs['desc']
  114. if description_or_id == '' and 'name' in self.attrs:
  115. description_or_id = 'ID: %s' % self.attrs['name']
  116. assigned_id = None
  117. if self.attrs['use_name_for_id'] == 'true':
  118. assigned_id = self.attrs['name']
  119. message = tclib.Message(text=text, placeholders=placeholders,
  120. description=description_or_id,
  121. meaning=self.attrs['meaning'],
  122. assigned_id=assigned_id)
  123. self.clique = self.UberClique().MakeClique(message, self.IsTranslateable())
  124. for group in self.shortcut_groups_:
  125. self.clique.AddToShortcutGroup(group)
  126. if self.attrs['custom_type'] != '':
  127. self.clique.SetCustomType(util.NewClassInstance(self.attrs['custom_type'],
  128. clique.CustomType))
  129. elif self.attrs['validation_expr'] != '':
  130. self.clique.SetCustomType(
  131. clique.OneOffCustomType(self.attrs['validation_expr']))
  132. def GetCliques(self):
  133. if self.clique:
  134. return [self.clique]
  135. else:
  136. return []
  137. def Translate(self, lang):
  138. '''Returns a translated version of this message.
  139. '''
  140. assert self.clique
  141. msg = self.clique.MessageForLanguage(lang,
  142. self.PseudoIsAllowed(),
  143. self.ShouldFallbackToEnglish()
  144. ).GetRealContent()
  145. return msg.replace('[GRITLANGCODE]', lang)
  146. def NameOrOffset(self):
  147. if 'name' in self.attrs:
  148. return self.attrs['name']
  149. else:
  150. return self.attrs['offset']
  151. def GetDataPackPair(self, output_dir, lang):
  152. '''Returns a (id, string) pair that represents the string id and the string
  153. in utf8. This is used to generate the data pack data file.
  154. '''
  155. from grit.format import rc_header
  156. id_map = rc_header.Item.tids_
  157. id = id_map[self.GetTextualIds()[0]]
  158. message = self.ws_at_start + self.Translate(lang) + self.ws_at_end
  159. # |message| is a python unicode string, so convert to a utf16 byte stream
  160. # because that's the format of datapacks. We skip the first 2 bytes
  161. # because it is the BOM.
  162. return id, message.encode('utf16')[2:]
  163. # static method
  164. def Construct(parent, message, name, desc='', meaning='', translateable=True):
  165. '''Constructs a new message node that is a child of 'parent', with the
  166. name, desc, meaning and translateable attributes set using the same-named
  167. parameters and the text of the message and any placeholders taken from
  168. 'message', which must be a tclib.Message() object.'''
  169. # Convert type to appropriate string
  170. if translateable:
  171. translateable = 'true'
  172. else:
  173. translateable = 'false'
  174. node = MessageNode()
  175. node.StartParsing('message', parent)
  176. node.HandleAttribute('name', name)
  177. node.HandleAttribute('desc', desc)
  178. node.HandleAttribute('meaning', meaning)
  179. node.HandleAttribute('translateable', translateable)
  180. items = message.GetContent()
  181. for ix in range(len(items)):
  182. if isinstance(items[ix], types.StringTypes):
  183. text = items[ix]
  184. # Ensure whitespace at front and back of message is correctly handled.
  185. if ix == 0:
  186. text = "'''" + text
  187. if ix == len(items) - 1:
  188. text = text + "'''"
  189. node.AppendContent(text)
  190. else:
  191. phnode = PhNode()
  192. phnode.StartParsing('ph', node)
  193. phnode.HandleAttribute('name', items[ix].GetPresentation())
  194. phnode.AppendContent(items[ix].GetOriginal())
  195. if len(items[ix].GetExample()) and items[ix].GetExample() != ' ':
  196. exnode = ExNode()
  197. exnode.StartParsing('ex', phnode)
  198. exnode.AppendContent(items[ix].GetExample())
  199. exnode.EndParsing()
  200. phnode.AddChild(exnode)
  201. phnode.EndParsing()
  202. node.AddChild(phnode)
  203. node.EndParsing()
  204. return node
  205. Construct = staticmethod(Construct)
  206. class PhNode(base.ContentNode):
  207. '''A <ph> element.'''
  208. def _IsValidChild(self, child):
  209. return isinstance(child, ExNode)
  210. def MandatoryAttributes(self):
  211. return ['name']
  212. def EndParsing(self):
  213. super(type(self), self).EndParsing()
  214. # We only allow a single example for each placeholder
  215. if len(self.children) > 1:
  216. raise exception.TooManyExamples()
  217. class ExNode(base.ContentNode):
  218. '''An <ex> element.'''
  219. pass