1 # Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR>
2 # This program and the accompanying materials
3 # are licensed and made available under the terms and conditions of the BSD License
4 # which accompanies this distribution. The full text of the license may be found at
5 # http://opensource.org/licenses/bsd-license.php
7 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
8 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11 #This file is used to collect all defined strings in multiple uni files
19 import Common
.EdkLogger
as EdkLogger
20 from Common
.BuildToolError
import *
21 from Common
.String
import GetLineNo
22 from Common
.Misc
import PathClass
27 UNICODE_WIDE_CHAR
= u
'\\wide'
28 UNICODE_NARROW_CHAR
= u
'\\narrow'
29 UNICODE_NON_BREAKING_CHAR
= u
'\\nbr'
30 UNICODE_UNICODE_CR
= '\r'
31 UNICODE_UNICODE_LF
= '\n'
33 NARROW_CHAR
= u
'\uFFF0'
35 NON_BREAKING_CHAR
= u
'\uFFF2'
42 gIncludePattern
= re
.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re
.MULTILINE | re
.UNICODE
)
44 ## Convert a python unicode string to a normal string
46 # Convert a python unicode string to a normal string
47 # UniToStr(u'I am a string') is 'I am a string'
49 # @param Uni: The python unicode string
51 # @retval: The formatted normal string
54 return repr(Uni
)[2:-1]
56 ## Convert a unicode string to a Hex list
58 # Convert a unicode string to a Hex list
59 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
61 # @param Uni: The python unicode string
63 # @retval List: The formatted hex list
65 def UniToHexList(Uni
):
68 Temp
= '%04X' % ord(Item
)
69 List
.append('0x' + Temp
[2:4])
70 List
.append('0x' + Temp
[0:2])
73 LangConvTable
= {'eng':'en', 'fra':'fr', \
74 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
75 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
76 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
77 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
78 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
79 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
80 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
81 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
82 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
83 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
84 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
85 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
86 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
87 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
88 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
89 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
90 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
91 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
92 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
93 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
94 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
95 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
96 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
97 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
98 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
99 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
100 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
101 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
102 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
103 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
104 'zho':'zh', 'zul':'zu'}
108 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
109 # ISO 639-2 language codes supported in compatiblity mode
110 # RFC 4646 language codes supported in native mode
112 # @param LangName: Language codes read from .UNI file
114 # @retval LangName: Valid lanugage code in RFC 4646 format or None
116 def GetLanguageCode(LangName
, IsCompatibleMode
, File
):
119 length
= len(LangName
)
121 if length
== 3 and LangName
.isalpha():
122 TempLangName
= LangConvTable
.get(LangName
.lower())
123 if TempLangName
!= None:
127 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid ISO 639-2 language code : %s" % LangName
, File
)
129 if (LangName
[0] == 'X' or LangName
[0] == 'x') and LangName
[1] == '-':
132 if LangName
.isalpha():
135 if LangName
.isalpha() and LangConvTable
.get(LangName
.lower()) == None:
138 if LangName
[0:2].isalpha() and LangName
[2] == '-':
141 if LangName
[0:2].isalpha() and LangName
[2] == '-':
143 if LangName
[0:3].isalpha() and LangConvTable
.get(LangName
.lower()) == None and LangName
[3] == '-':
146 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid RFC 4646 language code : %s" % LangName
, File
)
148 ## StringDefClassObject
150 # A structure for language definition
152 class StringDefClassObject(object):
153 def __init__(self
, Name
= None, Value
= None, Referenced
= False, Token
= None, UseOtherLangDef
= ''):
155 self
.StringNameByteList
= []
156 self
.StringValue
= ''
157 self
.StringValueByteList
= ''
159 self
.Referenced
= Referenced
160 self
.UseOtherLangDef
= UseOtherLangDef
164 self
.StringName
= Name
165 self
.StringNameByteList
= UniToHexList(Name
)
167 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
168 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
169 self
.Length
= len(self
.StringValueByteList
)
174 return repr(self
.StringName
) + ' ' + \
175 repr(self
.Token
) + ' ' + \
176 repr(self
.Referenced
) + ' ' + \
177 repr(self
.StringValue
) + ' ' + \
178 repr(self
.UseOtherLangDef
)
180 ## UniFileClassObject
182 # A structure for .uni file definition
184 class UniFileClassObject(object):
185 def __init__(self
, FileList
= [], IsCompatibleMode
= False):
186 self
.FileList
= FileList
188 self
.LanguageDef
= [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
189 self
.OrderedStringList
= {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
190 self
.IsCompatibleMode
= IsCompatibleMode
192 if len(self
.FileList
) > 0:
193 self
.LoadUniFiles(FileList
)
196 # Get Language definition
198 def GetLangDef(self
, File
, Line
):
199 Lang
= distutils
.util
.split_quoted((Line
.split(u
"//")[0]))
202 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').read()
203 except UnicodeError, X
:
204 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
);
206 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
);
207 LineNo
= GetLineNo(FileIn
, Line
, False)
208 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, "Wrong language definition",
209 ExtraData
="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line
, File
= File
, Line
= LineNo
)
211 LangName
= GetLanguageCode(Lang
[1], self
.IsCompatibleMode
, self
.File
)
212 LangPrintName
= Lang
[2]
215 for Item
in self
.LanguageDef
:
216 if Item
[0] == LangName
:
221 self
.LanguageDef
.append([LangName
, LangPrintName
])
224 # Add language string
226 self
.AddStringToList(u
'$LANGUAGE_NAME', LangName
, LangName
, 0, True, Index
=0)
227 self
.AddStringToList(u
'$PRINTABLE_LANGUAGE_NAME', LangName
, LangPrintName
, 1, True, Index
=1)
232 # Get String name and value
234 def GetStringObject(self
, Item
):
239 Name
= Item
.split()[1]
240 # Check the string name is the upper character
241 if not self
.IsCompatibleMode
and Name
!= '':
242 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
243 if MatchString
== None or MatchString
.end(0) != len(Name
):
244 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid lower case character.' %(Name
, self
.File
))
245 LanguageList
= Item
.split(u
'#language ')
246 for IndexI
in range(len(LanguageList
)):
250 Language
= LanguageList
[IndexI
].split()[0]
251 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
252 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
253 self
.AddStringToList(Name
, Language
, Value
)
256 # Get include file list and load them
258 def GetIncludeFile(self
, Item
, Dir
):
259 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
260 self
.LoadUniFile(FileName
)
263 # Pre-process before parse .uni file
265 def PreProcess(self
, File
):
266 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
267 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
271 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').readlines()
272 except UnicodeError, X
:
273 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
275 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
279 # Use unique identifier
284 # Ignore comment line and empty line
286 if Line
== u
'' or Line
.startswith(u
'//'):
288 Line
= Line
.replace(u
'/langdef', u
'#langdef')
289 Line
= Line
.replace(u
'/string', u
'#string')
290 Line
= Line
.replace(u
'/language', u
'#language')
291 Line
= Line
.replace(u
'/include', u
'#include')
293 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
294 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
295 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
297 Line
= Line
.replace(u
'\\\\', u
'\u0006')
298 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
299 Line
= Line
.replace(u
'\\n', CR
+ LF
)
300 Line
= Line
.replace(u
'\\r', CR
)
301 Line
= Line
.replace(u
'\\t', u
'\t')
302 Line
= Line
.replace(u
'''\"''', u
'''"''')
303 Line
= Line
.replace(u
'\t', u
' ')
304 Line
= Line
.replace(u
'\u0006', u
'\\')
306 # if Line.find(u'\\x'):
307 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
308 # hex = "u'\\u" + hex + "'"
310 IncList
= gIncludePattern
.findall(Line
)
311 if len(IncList
) == 1:
312 Lines
.extend(self
.PreProcess(PathClass(str(IncList
[0]), Dir
)))
322 def LoadUniFile(self
, File
= None):
324 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
327 # Process special char in file
329 Lines
= self
.PreProcess(File
)
332 # Get Unicode Information
334 for IndexI
in range(len(Lines
)):
336 if (IndexI
+ 1) < len(Lines
):
337 SecondLine
= Lines
[IndexI
+ 1]
338 if (IndexI
+ 2) < len(Lines
):
339 ThirdLine
= Lines
[IndexI
+ 2]
342 # Get Language def information
344 if Line
.find(u
'#langdef ') >= 0:
345 self
.GetLangDef(File
, Line
)
352 # Get string def information format 1 as below
354 # #string MY_STRING_1
356 # My first English string line 1
357 # My first English string line 2
358 # #string MY_STRING_1
360 # Mi segunda secuencia 1
361 # Mi segunda secuencia 2
363 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
364 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
365 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
366 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
367 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
368 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
369 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
370 Value
= Value
+ Lines
[IndexJ
]
374 # Value = Value.replace(u'\r\n', u'')
375 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
376 # Check the string name is the upper character
377 if not self
.IsCompatibleMode
and Name
!= '':
378 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
379 if MatchString
== None or MatchString
.end(0) != len(Name
):
380 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid lower case character.' %(Name
, self
.File
))
381 self
.AddStringToList(Name
, Language
, Value
)
385 # Get string def information format 2 as below
387 # #string MY_STRING_1 #language eng "My first English string line 1"
388 # "My first English string line 2"
389 # #language spa "Mi segunda secuencia 1"
390 # "Mi segunda secuencia 2"
391 # #string MY_STRING_2 #language eng "My first English string line 1"
392 # "My first English string line 2"
393 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
394 # "Mi segunda secuencia 2"
396 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
398 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
399 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
402 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
403 StringItem
= StringItem
+ Lines
[IndexJ
]
404 elif Lines
[IndexJ
].count(u
'\"') >= 2:
405 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
406 self
.GetStringObject(StringItem
)
410 # Load multiple .uni files
412 def LoadUniFiles(self
, FileList
):
413 if len(FileList
) > 0:
414 for File
in FileList
:
415 self
.LoadUniFile(File
)
418 # Add a string to list
420 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
421 if Language
not in self
.OrderedStringList
:
422 self
.OrderedStringList
[Language
] = []
425 for Item
in self
.OrderedStringList
[Language
]:
426 if Name
== Item
.StringName
:
430 Token
= len(self
.OrderedStringList
[Language
])
432 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
434 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
437 # Set the string as referenced
439 def SetStringReferenced(self
, Name
):
440 for Lang
in self
.OrderedStringList
:
441 for Item
in self
.OrderedStringList
[Lang
]:
442 if Name
== Item
.StringName
:
443 Item
.Referenced
= True
446 # Search the string in language definition by Name
448 def FindStringValue(self
, Name
, Lang
):
449 for Item
in self
.OrderedStringList
[Lang
]:
450 if Item
.StringName
== Name
:
456 # Search the string in language definition by Token
458 def FindByToken(self
, Token
, Lang
):
459 for Item
in self
.OrderedStringList
[Lang
]:
460 if Item
.Token
== Token
:
466 # Re-order strings and re-generate tokens
470 # Search each string to find if it is defined for each language
471 # Use secondary language value to replace if missing in any one language
473 for IndexI
in range(0, len(self
.LanguageDef
)):
474 LangKey
= self
.LanguageDef
[IndexI
][0]
475 for Item
in self
.OrderedStringList
[LangKey
]:
476 Name
= Item
.StringName
477 Value
= Item
.StringValue
[0:-1]
478 Referenced
= Item
.Referenced
479 Index
= self
.OrderedStringList
[LangKey
].index(Item
)
480 for IndexJ
in range(0, len(self
.LanguageDef
)):
481 LangFind
= self
.LanguageDef
[IndexJ
][0]
482 if self
.FindStringValue(Name
, LangFind
) == None:
483 EdkLogger
.debug(EdkLogger
.DEBUG_5
, Name
)
484 Token
= len(self
.OrderedStringList
[LangFind
])
485 self
.AddStringToList(Name
, LangFind
, Value
, Token
, Referenced
, LangKey
, Index
)
489 # First re-token the first language
490 LangName
= self
.LanguageDef
[0][0]
491 ReferencedStringList
= []
492 NotReferencedStringList
= []
496 # Order UNI token by their String Name
499 for Item
in self
.OrderedStringList
[LangName
]:
500 StringNameList
.append (Item
.StringName
)
501 StringNameList
.sort()
503 for Name
in StringNameList
:
504 Item
= self
.FindStringValue (Name
, LangName
)
505 if Item
.Referenced
== True:
507 ReferencedStringList
.append(Item
)
510 NotReferencedStringList
.append(Item
)
511 self
.OrderedStringList
[LangName
] = ReferencedStringList
512 for Index
in range(len(NotReferencedStringList
)):
513 NotReferencedStringList
[Index
].Token
= Token
+ Index
514 self
.OrderedStringList
[LangName
].append(NotReferencedStringList
[Index
])
517 # Adjust the orders of other languages
519 for IndexOfLanguage
in range(1, len(self
.LanguageDef
)):
520 for OrderedString
in self
.OrderedStringList
[LangName
]:
521 for UnOrderedString
in self
.OrderedStringList
[self
.LanguageDef
[IndexOfLanguage
][0]]:
522 if OrderedString
.StringName
== UnOrderedString
.StringName
:
523 UnOrderedString
.Token
= OrderedString
.Token
527 # Show the instance itself
530 print self
.LanguageDef
531 #print self.OrderedStringList
532 for Item
in self
.OrderedStringList
:
534 for Member
in self
.OrderedStringList
[Item
]:
537 # This acts like the main() function for the script, unless it is 'import'ed into another
539 if __name__
== '__main__':
540 EdkLogger
.Initialize()
541 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
542 a
= UniFileClassObject(['C:\\Edk\\Strings.uni', 'C:\\Edk\\Strings2.uni'])