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 def UpdateValue(self
, Value
= None):
182 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
183 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
184 self
.Length
= len(self
.StringValueByteList
)
186 ## UniFileClassObject
188 # A structure for .uni file definition
190 class UniFileClassObject(object):
191 def __init__(self
, FileList
= [], IsCompatibleMode
= False, IncludePathList
= []):
192 self
.FileList
= FileList
194 self
.LanguageDef
= [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
195 self
.OrderedStringList
= {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
196 self
.IsCompatibleMode
= IsCompatibleMode
197 self
.IncludePathList
= IncludePathList
198 if len(self
.FileList
) > 0:
199 self
.LoadUniFiles(FileList
)
202 # Get Language definition
204 def GetLangDef(self
, File
, Line
):
205 Lang
= distutils
.util
.split_quoted((Line
.split(u
"//")[0]))
208 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').read()
209 except UnicodeError, X
:
210 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
);
212 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
);
213 LineNo
= GetLineNo(FileIn
, Line
, False)
214 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, "Wrong language definition",
215 ExtraData
="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line
, File
= File
, Line
= LineNo
)
217 LangName
= GetLanguageCode(Lang
[1], self
.IsCompatibleMode
, self
.File
)
218 LangPrintName
= Lang
[2]
221 for Item
in self
.LanguageDef
:
222 if Item
[0] == LangName
:
227 self
.LanguageDef
.append([LangName
, LangPrintName
])
230 # Add language string
232 self
.AddStringToList(u
'$LANGUAGE_NAME', LangName
, LangName
, 0, True, Index
=0)
233 self
.AddStringToList(u
'$PRINTABLE_LANGUAGE_NAME', LangName
, LangPrintName
, 1, True, Index
=1)
237 # The found STRING tokens will be added into new language string list
238 # so that the unique STRING identifier is reserved for all languages in the package list.
240 FirstLangName
= self
.LanguageDef
[0][0]
241 if LangName
!= FirstLangName
:
242 for Index
in range (2, len (self
.OrderedStringList
[FirstLangName
])):
243 Item
= self
.OrderedStringList
[FirstLangName
][Index
]
244 if Item
.UseOtherLangDef
!= '':
245 OtherLang
= Item
.UseOtherLangDef
247 OtherLang
= FirstLangName
248 self
.OrderedStringList
[LangName
].append (StringDefClassObject(Item
.StringName
, '', Item
.Referenced
, Item
.Token
, OtherLang
))
253 # Get String name and value
255 def GetStringObject(self
, Item
):
260 Name
= Item
.split()[1]
261 # Check the string name is the upper character
262 if not self
.IsCompatibleMode
and Name
!= '':
263 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
264 if MatchString
== None or MatchString
.end(0) != len(Name
):
265 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
))
266 LanguageList
= Item
.split(u
'#language ')
267 for IndexI
in range(len(LanguageList
)):
271 Language
= LanguageList
[IndexI
].split()[0]
272 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
273 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
274 self
.AddStringToList(Name
, Language
, Value
)
277 # Get include file list and load them
279 def GetIncludeFile(self
, Item
, Dir
):
280 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
281 self
.LoadUniFile(FileName
)
284 # Pre-process before parse .uni file
286 def PreProcess(self
, File
):
287 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
288 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
291 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').readlines()
292 except UnicodeError, X
:
293 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
295 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
299 # Use unique identifier
304 Line
= FileIn
[LineCount
]
308 # Ignore comment line and empty line
310 if Line
== u
'' or Line
.startswith(u
'//'):
314 # Process comment embeded in string define lines
316 FindFlag
= Line
.find(u
'//')
318 Line
= Line
.replace(Line
[FindFlag
:], u
' ')
319 if FileIn
[LineCount
].strip().startswith('#language'):
320 Line
= Line
+ FileIn
[LineCount
]
321 FileIn
[LineCount
-1] = Line
322 FileIn
[LineCount
] = os
.linesep
324 for Index
in xrange (LineCount
+ 1, len (FileIn
) - 1):
325 if (Index
== len(FileIn
) -1):
326 FileIn
[Index
] = os
.linesep
328 FileIn
[Index
] = FileIn
[Index
+ 1]
331 Line
= Line
.replace(u
'/langdef', u
'#langdef')
332 Line
= Line
.replace(u
'/string', u
'#string')
333 Line
= Line
.replace(u
'/language', u
'#language')
334 Line
= Line
.replace(u
'/include', u
'#include')
336 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
337 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
338 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
340 Line
= Line
.replace(u
'\\\\', u
'\u0006')
341 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
342 Line
= Line
.replace(u
'\\n', CR
+ LF
)
343 Line
= Line
.replace(u
'\\r', CR
)
344 Line
= Line
.replace(u
'\\t', u
'\t')
345 Line
= Line
.replace(u
'''\"''', u
'''"''')
346 Line
= Line
.replace(u
'\t', u
' ')
347 Line
= Line
.replace(u
'\u0006', u
'\\')
349 # if Line.find(u'\\x'):
350 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
351 # hex = "u'\\u" + hex + "'"
353 IncList
= gIncludePattern
.findall(Line
)
354 if len(IncList
) == 1:
355 for Dir
in [File
.Dir
] + self
.IncludePathList
:
356 IncFile
= PathClass(str(IncList
[0]), Dir
)
357 if os
.path
.isfile(IncFile
.Path
):
358 Lines
.extend(self
.PreProcess(IncFile
))
361 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, Message
="Cannot find include file", ExtraData
=str(IncList
[0]))
371 def LoadUniFile(self
, File
= None):
373 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
376 # Process special char in file
378 Lines
= self
.PreProcess(File
)
381 # Get Unicode Information
383 for IndexI
in range(len(Lines
)):
385 if (IndexI
+ 1) < len(Lines
):
386 SecondLine
= Lines
[IndexI
+ 1]
387 if (IndexI
+ 2) < len(Lines
):
388 ThirdLine
= Lines
[IndexI
+ 2]
391 # Get Language def information
393 if Line
.find(u
'#langdef ') >= 0:
394 self
.GetLangDef(File
, Line
)
401 # Get string def information format 1 as below
403 # #string MY_STRING_1
405 # My first English string line 1
406 # My first English string line 2
407 # #string MY_STRING_1
409 # Mi segunda secuencia 1
410 # Mi segunda secuencia 2
412 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
413 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
414 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
415 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
416 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
417 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
418 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
419 Value
= Value
+ Lines
[IndexJ
]
423 # Value = Value.replace(u'\r\n', u'')
424 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
425 # Check the string name is the upper character
426 if not self
.IsCompatibleMode
and Name
!= '':
427 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
428 if MatchString
== None or MatchString
.end(0) != len(Name
):
429 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
))
430 self
.AddStringToList(Name
, Language
, Value
)
434 # Get string def information format 2 as below
436 # #string MY_STRING_1 #language eng "My first English string line 1"
437 # "My first English string line 2"
438 # #language spa "Mi segunda secuencia 1"
439 # "Mi segunda secuencia 2"
440 # #string MY_STRING_2 #language eng "My first English string line 1"
441 # "My first English string line 2"
442 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
443 # "Mi segunda secuencia 2"
445 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
447 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
448 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
451 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
452 StringItem
= StringItem
+ Lines
[IndexJ
]
453 elif Lines
[IndexJ
].count(u
'\"') >= 2:
454 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
455 self
.GetStringObject(StringItem
)
459 # Load multiple .uni files
461 def LoadUniFiles(self
, FileList
):
462 if len(FileList
) > 0:
463 for File
in FileList
:
464 self
.LoadUniFile(File
)
467 # Add a string to list
469 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
470 for LangNameItem
in self
.LanguageDef
:
471 if Language
== LangNameItem
[0]:
474 EdkLogger
.error('Unicode File Parser', FORMAT_NOT_SUPPORTED
, "The language '%s' for %s is not defined in Unicode file %s." \
475 % (Language
, Name
, self
.File
))
477 if Language
not in self
.OrderedStringList
:
478 self
.OrderedStringList
[Language
] = []
481 for Item
in self
.OrderedStringList
[Language
]:
482 if Name
== Item
.StringName
:
485 Item
.UpdateValue(Value
)
486 Item
.UseOtherLangDef
= ''
490 Token
= len(self
.OrderedStringList
[Language
])
492 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
493 for LangName
in self
.LanguageDef
:
495 # New STRING token will be added into all language string lists.
496 # so that the unique STRING identifier is reserved for all languages in the package list.
498 if LangName
[0] != Language
:
499 if UseOtherLangDef
!= '':
500 OtherLangDef
= UseOtherLangDef
502 OtherLangDef
= Language
503 self
.OrderedStringList
[LangName
[0]].append(StringDefClassObject(Name
, '', Referenced
, Token
, OtherLangDef
))
505 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
508 # Set the string as referenced
510 def SetStringReferenced(self
, Name
):
512 # String stoken are added in the same order in all language string lists.
513 # So, only update the status of string stoken in first language string list.
515 Lang
= self
.LanguageDef
[0][0]
516 for Item
in self
.OrderedStringList
[Lang
]:
517 if Name
== Item
.StringName
:
518 Item
.Referenced
= True
521 # Search the string in language definition by Name
523 def FindStringValue(self
, Name
, Lang
):
524 for Item
in self
.OrderedStringList
[Lang
]:
525 if Item
.StringName
== Name
:
531 # Search the string in language definition by Token
533 def FindByToken(self
, Token
, Lang
):
534 for Item
in self
.OrderedStringList
[Lang
]:
535 if Item
.Token
== Token
:
541 # Re-order strings and re-generate tokens
545 # Retoken all language strings according to the status of string stoken in the first language string.
547 FirstLangName
= self
.LanguageDef
[0][0]
550 # Use small token for all referred string stoken.
553 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
554 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
555 if FirstLangItem
.Referenced
== True:
556 for LangNameItem
in self
.LanguageDef
:
557 LangName
= LangNameItem
[0]
558 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
559 OtherLangItem
.Referenced
= True
560 OtherLangItem
.Token
= RefToken
561 RefToken
= RefToken
+ 1
564 # Use big token for all unreferred string stoken.
567 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
568 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
569 if FirstLangItem
.Referenced
== False:
570 for LangNameItem
in self
.LanguageDef
:
571 LangName
= LangNameItem
[0]
572 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
573 OtherLangItem
.Token
= RefToken
+ UnRefToken
574 UnRefToken
= UnRefToken
+ 1
577 # Show the instance itself
580 print self
.LanguageDef
581 #print self.OrderedStringList
582 for Item
in self
.OrderedStringList
:
584 for Member
in self
.OrderedStringList
[Item
]:
587 # This acts like the main() function for the script, unless it is 'import'ed into another
589 if __name__
== '__main__':
590 EdkLogger
.Initialize()
591 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
592 a
= UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])