1 # Copyright (c) 2007, Intel Corporation
2 # All rights reserved. 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
18 import Common
.EdkLogger
as EdkLogger
19 from Common
.BuildToolError
import *
20 from Common
.String
import GetLineNo
21 from Common
.Misc
import PathClass
26 UNICODE_WIDE_CHAR
= u
'\\wide'
27 UNICODE_NARROW_CHAR
= u
'\\narrow'
28 UNICODE_NON_BREAKING_CHAR
= u
'\\nbr'
29 UNICODE_UNICODE_CR
= '\r'
30 UNICODE_UNICODE_LF
= '\n'
32 NARROW_CHAR
= u
'\uFFF0'
34 NON_BREAKING_CHAR
= u
'\uFFF2'
41 gIncludePattern
= re
.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re
.MULTILINE | re
.UNICODE
)
43 ## Convert a python unicode string to a normal string
45 # Convert a python unicode string to a normal string
46 # UniToStr(u'I am a string') is 'I am a string'
48 # @param Uni: The python unicode string
50 # @retval: The formatted normal string
53 return repr(Uni
)[2:-1]
55 ## Convert a unicode string to a Hex list
57 # Convert a unicode string to a Hex list
58 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
60 # @param Uni: The python unicode string
62 # @retval List: The formatted hex list
64 def UniToHexList(Uni
):
67 Temp
= '%04X' % ord(Item
)
68 List
.append('0x' + Temp
[2:4])
69 List
.append('0x' + Temp
[0:2])
72 LangConvTable
= {'eng':'en', 'fra':'fr', \
73 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
74 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
75 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
76 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
77 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
78 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
79 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
80 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
81 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
82 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
83 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
84 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
85 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
86 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
87 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
88 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
89 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
90 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
91 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
92 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
93 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
94 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
95 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
96 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
97 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
98 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
99 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
100 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
101 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
102 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
103 'zho':'zh', 'zul':'zu'}
107 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
108 # ISO 639-2 language codes supported in compatiblity mode
109 # RFC 4646 language codes supported in native mode
111 # @param LangName: Language codes read from .UNI file
113 # @retval LangName: Valid lanugage code in RFC 4646 format or None
115 def GetLanguageCode(LangName
, IsCompatibleMode
, File
):
118 length
= len(LangName
)
120 if length
== 3 and LangName
.isalpha():
121 TempLangName
= LangConvTable
.get(LangName
.lower())
122 if TempLangName
!= None:
126 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid ISO 639-2 language code : %s" % LangName
, File
)
129 if LangName
.isalpha():
132 if LangName
.isalpha() and LangConvTable
.get(LangName
.lower()) == None:
135 if LangName
[0:2].isalpha() and LangName
[2] == '-':
138 if LangName
[0:2].isalpha() and LangName
[2] == '-':
140 if LangName
[0:3].isalpha() and LangConvTable
.get(LangName
.lower()) == None and LangName
[3] == '-':
143 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid RFC 4646 language code : %s" % LangName
, File
)
145 ## StringDefClassObject
147 # A structure for language definition
149 class StringDefClassObject(object):
150 def __init__(self
, Name
= None, Value
= None, Referenced
= False, Token
= None, UseOtherLangDef
= ''):
152 self
.StringNameByteList
= []
153 self
.StringValue
= ''
154 self
.StringValueByteList
= ''
156 self
.Referenced
= Referenced
157 self
.UseOtherLangDef
= UseOtherLangDef
161 self
.StringName
= Name
162 self
.StringNameByteList
= UniToHexList(Name
)
164 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
165 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
166 self
.Length
= len(self
.StringValueByteList
)
171 return repr(self
.StringName
) + ' ' + \
172 repr(self
.Token
) + ' ' + \
173 repr(self
.Referenced
) + ' ' + \
174 repr(self
.StringValue
) + ' ' + \
175 repr(self
.UseOtherLangDef
)
177 ## UniFileClassObject
179 # A structure for .uni file definition
181 class UniFileClassObject(object):
182 def __init__(self
, FileList
= [], IsCompatibleMode
= False):
183 self
.FileList
= FileList
185 self
.LanguageDef
= [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
186 self
.OrderedStringList
= {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
187 self
.IsCompatibleMode
= IsCompatibleMode
189 if len(self
.FileList
) > 0:
190 self
.LoadUniFiles(FileList
)
193 # Get Language definition
195 def GetLangDef(self
, File
, Line
):
199 FileIn
= codecs
.open(File
, mode
='rb', encoding
='utf-16').read()
200 except UnicodeError, X
:
201 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
);
203 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
);
204 LineNo
= GetLineNo(FileIn
, Line
, False)
205 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, "Wrong language definition",
206 ExtraData
="""%s\n\t*Correct format is like '#langdef eng "English"'""" % Line
, File
= File
, Line
= LineNo
)
208 LangName
= GetLanguageCode(Lang
[1], self
.IsCompatibleMode
, self
.File
)
209 LangPrintName
= Lang
[2][1:-1]
212 for Item
in self
.LanguageDef
:
213 if Item
[0] == LangName
:
218 self
.LanguageDef
.append([LangName
, LangPrintName
])
221 # Add language string
223 self
.AddStringToList(u
'$LANGUAGE_NAME', LangName
, LangName
, 0, True, Index
=0)
224 self
.AddStringToList(u
'$PRINTABLE_LANGUAGE_NAME', LangName
, LangPrintName
, 1, True, Index
=1)
229 # Get String name and value
231 def GetStringObject(self
, Item
):
236 Name
= Item
.split()[1]
237 # Check the string name is the upper character
238 if not self
.IsCompatibleMode
and Name
!= '':
239 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
240 if MatchString
== None or MatchString
.end(0) != len(Name
):
241 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
))
242 LanguageList
= Item
.split(u
'#language ')
243 for IndexI
in range(len(LanguageList
)):
247 Language
= LanguageList
[IndexI
].split()[0]
248 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
249 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
250 self
.AddStringToList(Name
, Language
, Value
)
253 # Get include file list and load them
255 def GetIncludeFile(self
, Item
, Dir
):
256 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
257 self
.LoadUniFile(FileName
)
260 # Pre-process before parse .uni file
262 def PreProcess(self
, File
):
263 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
264 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
268 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').readlines()
269 except UnicodeError, X
:
270 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
272 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
276 # Use unique identifier
281 # Ignore comment line and empty line
283 if Line
== u
'' or Line
.startswith(u
'//'):
285 Line
= Line
.replace(u
'/langdef', u
'#langdef')
286 Line
= Line
.replace(u
'/string', u
'#string')
287 Line
= Line
.replace(u
'/language', u
'#language')
288 Line
= Line
.replace(u
'/include', u
'#include')
290 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
291 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
292 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
294 Line
= Line
.replace(u
'\\\\', u
'\u0006')
295 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
296 Line
= Line
.replace(u
'\\n', CR
+ LF
)
297 Line
= Line
.replace(u
'\\r', CR
)
298 Line
= Line
.replace(u
'\\t', u
'\t')
299 Line
= Line
.replace(u
'''\"''', u
'''"''')
300 Line
= Line
.replace(u
'\t', u
' ')
301 Line
= Line
.replace(u
'\u0006', u
'\\')
303 # if Line.find(u'\\x'):
304 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
305 # hex = "u'\\u" + hex + "'"
307 IncList
= gIncludePattern
.findall(Line
)
308 if len(IncList
) == 1:
309 Lines
.extend(self
.PreProcess(PathClass(str(IncList
[0]), Dir
)))
319 def LoadUniFile(self
, File
= None):
321 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
324 # Process special char in file
326 Lines
= self
.PreProcess(File
)
329 # Get Unicode Information
331 for IndexI
in range(len(Lines
)):
333 if (IndexI
+ 1) < len(Lines
):
334 SecondLine
= Lines
[IndexI
+ 1]
335 if (IndexI
+ 2) < len(Lines
):
336 ThirdLine
= Lines
[IndexI
+ 2]
339 # Get Language def information
341 if Line
.find(u
'#langdef ') >= 0:
342 self
.GetLangDef(File
, Line
)
349 # Get string def information format 1 as below
351 # #string MY_STRING_1
353 # My first English string line 1
354 # My first English string line 2
355 # #string MY_STRING_1
357 # Mi segunda secuencia 1
358 # Mi segunda secuencia 2
360 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
361 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
362 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
363 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
364 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
365 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
366 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
367 Value
= Value
+ Lines
[IndexJ
]
371 # Value = Value.replace(u'\r\n', u'')
372 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
373 # Check the string name is the upper character
374 if not self
.IsCompatibleMode
and Name
!= '':
375 MatchString
= re
.match('[A-Z0-9_]+', Name
, re
.UNICODE
)
376 if MatchString
== None or MatchString
.end(0) != len(Name
):
377 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
))
378 self
.AddStringToList(Name
, Language
, Value
)
382 # Get string def information format 2 as below
384 # #string MY_STRING_1 #language eng "My first English string line 1"
385 # "My first English string line 2"
386 # #language spa "Mi segunda secuencia 1"
387 # "Mi segunda secuencia 2"
388 # #string MY_STRING_2 #language eng "My first English string line 1"
389 # "My first English string line 2"
390 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
391 # "Mi segunda secuencia 2"
393 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
395 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
396 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
399 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
400 StringItem
= StringItem
+ Lines
[IndexJ
]
401 elif Lines
[IndexJ
].count(u
'\"') >= 2:
402 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
403 self
.GetStringObject(StringItem
)
407 # Load multiple .uni files
409 def LoadUniFiles(self
, FileList
):
410 if len(FileList
) > 0:
411 for File
in FileList
:
412 self
.LoadUniFile(File
)
415 # Add a string to list
417 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
418 if Language
not in self
.OrderedStringList
:
419 self
.OrderedStringList
[Language
] = []
422 for Item
in self
.OrderedStringList
[Language
]:
423 if Name
== Item
.StringName
:
427 Token
= len(self
.OrderedStringList
[Language
])
429 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
431 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
434 # Set the string as referenced
436 def SetStringReferenced(self
, Name
):
437 for Lang
in self
.OrderedStringList
:
438 for Item
in self
.OrderedStringList
[Lang
]:
439 if Name
== Item
.StringName
:
440 Item
.Referenced
= True
443 # Search the string in language definition by Name
445 def FindStringValue(self
, Name
, Lang
):
446 for Item
in self
.OrderedStringList
[Lang
]:
447 if Item
.StringName
== Name
:
453 # Search the string in language definition by Token
455 def FindByToken(self
, Token
, Lang
):
456 for Item
in self
.OrderedStringList
[Lang
]:
457 if Item
.Token
== Token
:
463 # Re-order strings and re-generate tokens
467 # Search each string to find if it is defined for each language
468 # Use secondary language value to replace if missing in any one language
470 for IndexI
in range(0, len(self
.LanguageDef
)):
471 LangKey
= self
.LanguageDef
[IndexI
][0]
472 for Item
in self
.OrderedStringList
[LangKey
]:
473 Name
= Item
.StringName
474 Value
= Item
.StringValue
[0:-1]
475 Referenced
= Item
.Referenced
476 Index
= self
.OrderedStringList
[LangKey
].index(Item
)
477 for IndexJ
in range(0, len(self
.LanguageDef
)):
478 LangFind
= self
.LanguageDef
[IndexJ
][0]
479 if self
.FindStringValue(Name
, LangFind
) == None:
480 EdkLogger
.debug(EdkLogger
.DEBUG_5
, Name
)
481 Token
= len(self
.OrderedStringList
[LangFind
])
482 self
.AddStringToList(Name
, LangFind
, Value
, Token
, Referenced
, LangKey
, Index
)
486 # First re-token the first language
487 LangName
= self
.LanguageDef
[0][0]
488 ReferencedStringList
= []
489 NotReferencedStringList
= []
493 # Order UNI token by their String Name
496 for Item
in self
.OrderedStringList
[LangName
]:
497 StringNameList
.append (Item
.StringName
)
498 StringNameList
.sort()
500 for Name
in StringNameList
:
501 Item
= self
.FindStringValue (Name
, LangName
)
502 if Item
.Referenced
== True:
504 ReferencedStringList
.append(Item
)
507 NotReferencedStringList
.append(Item
)
508 self
.OrderedStringList
[LangName
] = ReferencedStringList
509 for Index
in range(len(NotReferencedStringList
)):
510 NotReferencedStringList
[Index
].Token
= Token
+ Index
511 self
.OrderedStringList
[LangName
].append(NotReferencedStringList
[Index
])
514 # Adjust the orders of other languages
516 for IndexOfLanguage
in range(1, len(self
.LanguageDef
)):
517 for OrderedString
in self
.OrderedStringList
[LangName
]:
518 for UnOrderedString
in self
.OrderedStringList
[self
.LanguageDef
[IndexOfLanguage
][0]]:
519 if OrderedString
.StringName
== UnOrderedString
.StringName
:
520 UnOrderedString
.Token
= OrderedString
.Token
524 # Show the instance itself
527 print self
.LanguageDef
528 #print self.OrderedStringList
529 for Item
in self
.OrderedStringList
:
531 for Member
in self
.OrderedStringList
[Item
]:
534 # This acts like the main() function for the script, unless it is 'import'ed into another
536 if __name__
== '__main__':
537 EdkLogger
.Initialize()
538 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
539 a
= UniFileClassObject(['C:\\Edk\\Strings.uni', 'C:\\Edk\\Strings2.uni'])