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 LanguageList
= Item
.split(u
'#language ')
238 for IndexI
in range(len(LanguageList
)):
242 Language
= LanguageList
[IndexI
].split()[0]
243 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
244 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
245 self
.AddStringToList(Name
, Language
, Value
)
248 # Get include file list and load them
250 def GetIncludeFile(self
, Item
, Dir
):
251 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
252 self
.LoadUniFile(FileName
)
255 # Pre-process before parse .uni file
257 def PreProcess(self
, File
):
258 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
259 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
263 FileIn
= codecs
.open(File
.Path
, mode
='rb', encoding
='utf-16').readlines()
264 except UnicodeError, X
:
265 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
267 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
271 # Use unique identifier
276 # Ignore comment line and empty line
278 if Line
== u
'' or Line
.startswith(u
'//'):
280 Line
= Line
.replace(u
'/langdef', u
'#langdef')
281 Line
= Line
.replace(u
'/string', u
'#string')
282 Line
= Line
.replace(u
'/language', u
'#language')
283 Line
= Line
.replace(u
'/include', u
'#include')
285 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
286 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
287 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
289 Line
= Line
.replace(u
'\\\\', u
'\u0006')
290 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
291 Line
= Line
.replace(u
'\\n', CR
+ LF
)
292 Line
= Line
.replace(u
'\\r', CR
)
293 Line
= Line
.replace(u
'\\t', u
'\t')
294 Line
= Line
.replace(u
'''\"''', u
'''"''')
295 Line
= Line
.replace(u
'\t', u
' ')
296 Line
= Line
.replace(u
'\u0006', u
'\\')
298 # if Line.find(u'\\x'):
299 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
300 # hex = "u'\\u" + hex + "'"
302 IncList
= gIncludePattern
.findall(Line
)
303 if len(IncList
) == 1:
304 Lines
.extend(self
.PreProcess(PathClass(str(IncList
[0]), Dir
)))
314 def LoadUniFile(self
, File
= None):
316 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
319 # Process special char in file
321 Lines
= self
.PreProcess(File
)
324 # Get Unicode Information
326 for IndexI
in range(len(Lines
)):
328 if (IndexI
+ 1) < len(Lines
):
329 SecondLine
= Lines
[IndexI
+ 1]
330 if (IndexI
+ 2) < len(Lines
):
331 ThirdLine
= Lines
[IndexI
+ 2]
334 # Get Language def information
336 if Line
.find(u
'#langdef ') >= 0:
337 self
.GetLangDef(File
, Line
)
344 # Get string def information format 1 as below
346 # #string MY_STRING_1
348 # My first English string line 1
349 # My first English string line 2
350 # #string MY_STRING_1
352 # Mi segunda secuencia 1
353 # Mi segunda secuencia 2
355 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
356 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
357 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
358 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
359 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
360 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
361 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
362 Value
= Value
+ Lines
[IndexJ
]
366 # Value = Value.replace(u'\r\n', u'')
367 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
368 self
.AddStringToList(Name
, Language
, Value
)
372 # Get string def information format 2 as below
374 # #string MY_STRING_1 #language eng "My first English string line 1"
375 # "My first English string line 2"
376 # #language spa "Mi segunda secuencia 1"
377 # "Mi segunda secuencia 2"
378 # #string MY_STRING_2 #language eng "My first English string line 1"
379 # "My first English string line 2"
380 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
381 # "Mi segunda secuencia 2"
383 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
385 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
386 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
389 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
390 StringItem
= StringItem
+ Lines
[IndexJ
]
391 elif Lines
[IndexJ
].count(u
'\"') >= 2:
392 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
393 self
.GetStringObject(StringItem
)
397 # Load multiple .uni files
399 def LoadUniFiles(self
, FileList
= []):
400 if len(FileList
) > 0:
401 if len(FileList
) > 1:
403 for File
in FileList
:
404 NewList
.append (File
)
407 self
.LoadUniFile(File
)
409 for File
in FileList
:
410 self
.LoadUniFile(File
)
413 # Add a string to list
415 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
416 if Language
not in self
.OrderedStringList
:
417 self
.OrderedStringList
[Language
] = []
420 for Item
in self
.OrderedStringList
[Language
]:
421 if Name
== Item
.StringName
:
425 Token
= len(self
.OrderedStringList
[Language
])
427 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
429 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
432 # Set the string as referenced
434 def SetStringReferenced(self
, Name
):
435 for Lang
in self
.OrderedStringList
:
436 for Item
in self
.OrderedStringList
[Lang
]:
437 if Name
== Item
.StringName
:
438 Item
.Referenced
= True
441 # Search the string in language definition by Name
443 def FindStringValue(self
, Name
, Lang
):
444 for Item
in self
.OrderedStringList
[Lang
]:
445 if Item
.StringName
== Name
:
451 # Search the string in language definition by Token
453 def FindByToken(self
, Token
, Lang
):
454 for Item
in self
.OrderedStringList
[Lang
]:
455 if Item
.Token
== Token
:
461 # Re-order strings and re-generate tokens
465 # Search each string to find if it is defined for each language
466 # Use secondary language value to replace if missing in any one language
468 for IndexI
in range(0, len(self
.LanguageDef
)):
469 LangKey
= self
.LanguageDef
[IndexI
][0]
470 for Item
in self
.OrderedStringList
[LangKey
]:
471 Name
= Item
.StringName
472 Value
= Item
.StringValue
[0:-1]
473 Referenced
= Item
.Referenced
474 Index
= self
.OrderedStringList
[LangKey
].index(Item
)
475 for IndexJ
in range(0, len(self
.LanguageDef
)):
476 LangFind
= self
.LanguageDef
[IndexJ
][0]
477 if self
.FindStringValue(Name
, LangFind
) == None:
478 EdkLogger
.debug(EdkLogger
.DEBUG_5
, Name
)
479 Token
= len(self
.OrderedStringList
[LangFind
])
480 self
.AddStringToList(Name
, LangFind
, Value
, Token
, Referenced
, LangKey
, Index
)
485 # First re-token the first language
486 LangName
= self
.LanguageDef
[0][0]
487 ReferencedStringList
= []
488 NotReferencedStringList
= []
490 for Item
in self
.OrderedStringList
[LangName
]:
491 if Item
.Referenced
== True:
493 ReferencedStringList
.append(Item
)
496 NotReferencedStringList
.append(Item
)
497 self
.OrderedStringList
[LangName
] = ReferencedStringList
498 for Index
in range(len(NotReferencedStringList
)):
499 NotReferencedStringList
[Index
].Token
= Token
+ Index
500 self
.OrderedStringList
[LangName
].append(NotReferencedStringList
[Index
])
503 # Adjust the orders of other languages
505 for IndexOfLanguage
in range(1, len(self
.LanguageDef
)):
506 for OrderedString
in self
.OrderedStringList
[LangName
]:
507 for UnOrderedString
in self
.OrderedStringList
[self
.LanguageDef
[IndexOfLanguage
][0]]:
508 if OrderedString
.StringName
== UnOrderedString
.StringName
:
509 UnOrderedString
.Token
= OrderedString
.Token
513 # Show the instance itself
516 print self
.LanguageDef
517 #print self.OrderedStringList
518 for Item
in self
.OrderedStringList
:
520 for Member
in self
.OrderedStringList
[Item
]:
523 # This acts like the main() function for the script, unless it is 'import'ed into another
525 if __name__
== '__main__':
526 EdkLogger
.Initialize()
527 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
528 a
= UniFileClassObject(['C:\\Edk\\Strings.uni', 'C:\\Edk\\Strings2.uni'])