]> git.proxmox.com Git - mirror_edk2.git/blob - BaseTools/Source/Python/AutoGen/UniClassObject.py
BaseTools/UniClassObject: Verify valid UCS-2 chars in UTF-16 .uni files
[mirror_edk2.git] / BaseTools / Source / Python / AutoGen / UniClassObject.py
1 ## @file
2 # This file is used to collect all defined strings in multiple uni files
3 #
4 #
5 # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.<BR>
6 #
7 # Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>
8 # This program and the accompanying materials
9 # are licensed and made available under the terms and conditions of the BSD License
10 # which accompanies this distribution. The full text of the license may be found at
11 # http://opensource.org/licenses/bsd-license.php
12 #
13 # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
15
16 ##
17 # Import Modules
18 #
19 import Common.LongFilePathOs as os, codecs, re
20 import distutils.util
21 import Common.EdkLogger as EdkLogger
22 import StringIO
23 from Common.BuildToolError import *
24 from Common.String import GetLineNo
25 from Common.Misc import PathClass
26 from Common.LongFilePathSupport import LongFilePath
27 ##
28 # Static definitions
29 #
30 UNICODE_WIDE_CHAR = u'\\wide'
31 UNICODE_NARROW_CHAR = u'\\narrow'
32 UNICODE_NON_BREAKING_CHAR = u'\\nbr'
33 UNICODE_UNICODE_CR = '\r'
34 UNICODE_UNICODE_LF = '\n'
35
36 NARROW_CHAR = u'\uFFF0'
37 WIDE_CHAR = u'\uFFF1'
38 NON_BREAKING_CHAR = u'\uFFF2'
39 CR = u'\u000D'
40 LF = u'\u000A'
41 NULL = u'\u0000'
42 TAB = u'\t'
43 BACK_SLASH_PLACEHOLDER = u'\u0006'
44
45 gIncludePattern = re.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re.MULTILINE | re.UNICODE)
46
47 ## Convert a python unicode string to a normal string
48 #
49 # Convert a python unicode string to a normal string
50 # UniToStr(u'I am a string') is 'I am a string'
51 #
52 # @param Uni: The python unicode string
53 #
54 # @retval: The formatted normal string
55 #
56 def UniToStr(Uni):
57 return repr(Uni)[2:-1]
58
59 ## Convert a unicode string to a Hex list
60 #
61 # Convert a unicode string to a Hex list
62 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
63 #
64 # @param Uni: The python unicode string
65 #
66 # @retval List: The formatted hex list
67 #
68 def UniToHexList(Uni):
69 List = []
70 for Item in Uni:
71 Temp = '%04X' % ord(Item)
72 List.append('0x' + Temp[2:4])
73 List.append('0x' + Temp[0:2])
74 return List
75
76 LangConvTable = {'eng':'en', 'fra':'fr', \
77 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
78 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
79 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
80 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
81 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
82 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
83 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
84 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
85 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
86 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
87 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
88 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
89 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
90 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
91 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
92 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
93 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
94 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
95 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
96 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
97 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
98 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
99 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
100 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
101 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
102 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
103 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
104 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
105 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
106 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
107 'zho':'zh', 'zul':'zu'}
108
109 ## GetLanguageCode
110 #
111 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
112 # ISO 639-2 language codes supported in compatiblity mode
113 # RFC 4646 language codes supported in native mode
114 #
115 # @param LangName: Language codes read from .UNI file
116 #
117 # @retval LangName: Valid lanugage code in RFC 4646 format or None
118 #
119 def GetLanguageCode(LangName, IsCompatibleMode, File):
120 global LangConvTable
121
122 length = len(LangName)
123 if IsCompatibleMode:
124 if length == 3 and LangName.isalpha():
125 TempLangName = LangConvTable.get(LangName.lower())
126 if TempLangName != None:
127 return TempLangName
128 return LangName
129 else:
130 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid ISO 639-2 language code : %s" % LangName, File)
131
132 if (LangName[0] == 'X' or LangName[0] == 'x') and LangName[1] == '-':
133 return LangName
134 if length == 2:
135 if LangName.isalpha():
136 return LangName
137 elif length == 3:
138 if LangName.isalpha() and LangConvTable.get(LangName.lower()) == None:
139 return LangName
140 elif length == 5:
141 if LangName[0:2].isalpha() and LangName[2] == '-':
142 return LangName
143 elif length >= 6:
144 if LangName[0:2].isalpha() and LangName[2] == '-':
145 return LangName
146 if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) == None and LangName[3] == '-':
147 return LangName
148
149 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid RFC 4646 language code : %s" % LangName, File)
150
151 ## Ucs2Codec
152 #
153 # This is only a partial codec implementation. It only supports
154 # encoding, and is primarily used to check that all the characters are
155 # valid for UCS-2.
156 #
157 class Ucs2Codec(codecs.Codec):
158 def __init__(self):
159 self.__utf16 = codecs.lookup('utf-16')
160
161 def encode(self, input, errors='strict'):
162 for Char in input:
163 CodePoint = ord(Char)
164 if CodePoint >= 0xd800 and CodePoint <= 0xdfff:
165 raise ValueError("Code Point is in range reserved for " +
166 "UTF-16 surrogate pairs")
167 elif CodePoint > 0xffff:
168 raise ValueError("Code Point too large to encode in UCS-2")
169 return self.__utf16.encode(input)
170
171 TheUcs2Codec = Ucs2Codec()
172 def Ucs2Search(name):
173 if name == 'ucs-2':
174 return codecs.CodecInfo(
175 name=name,
176 encode=TheUcs2Codec.encode,
177 decode=TheUcs2Codec.decode)
178 else:
179 return None
180 codecs.register(Ucs2Search)
181
182 ## StringDefClassObject
183 #
184 # A structure for language definition
185 #
186 class StringDefClassObject(object):
187 def __init__(self, Name = None, Value = None, Referenced = False, Token = None, UseOtherLangDef = ''):
188 self.StringName = ''
189 self.StringNameByteList = []
190 self.StringValue = ''
191 self.StringValueByteList = ''
192 self.Token = 0
193 self.Referenced = Referenced
194 self.UseOtherLangDef = UseOtherLangDef
195 self.Length = 0
196
197 if Name != None:
198 self.StringName = Name
199 self.StringNameByteList = UniToHexList(Name)
200 if Value != None:
201 self.StringValue = Value + u'\x00' # Add a NULL at string tail
202 self.StringValueByteList = UniToHexList(self.StringValue)
203 self.Length = len(self.StringValueByteList)
204 if Token != None:
205 self.Token = Token
206
207 def __str__(self):
208 return repr(self.StringName) + ' ' + \
209 repr(self.Token) + ' ' + \
210 repr(self.Referenced) + ' ' + \
211 repr(self.StringValue) + ' ' + \
212 repr(self.UseOtherLangDef)
213
214 def UpdateValue(self, Value = None):
215 if Value != None:
216 self.StringValue = Value + u'\x00' # Add a NULL at string tail
217 self.StringValueByteList = UniToHexList(self.StringValue)
218 self.Length = len(self.StringValueByteList)
219
220 ## UniFileClassObject
221 #
222 # A structure for .uni file definition
223 #
224 class UniFileClassObject(object):
225 def __init__(self, FileList = [], IsCompatibleMode = False, IncludePathList = []):
226 self.FileList = FileList
227 self.Token = 2
228 self.LanguageDef = [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
229 self.OrderedStringList = {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
230 self.OrderedStringDict = {} #{ u'LanguageIdentifier' : {StringName:(IndexInList)} }
231 self.OrderedStringListByToken = {} #{ u'LanguageIdentifier' : {Token: StringDefClassObject} }
232 self.IsCompatibleMode = IsCompatibleMode
233 self.IncludePathList = IncludePathList
234 if len(self.FileList) > 0:
235 self.LoadUniFiles(FileList)
236
237 #
238 # Get Language definition
239 #
240 def GetLangDef(self, File, Line):
241 Lang = distutils.util.split_quoted((Line.split(u"//")[0]))
242 if len(Lang) != 3:
243 try:
244 FileIn = self.OpenUniFile(LongFilePath(File.Path))
245 except UnicodeError, X:
246 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File);
247 except:
248 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File);
249 LineNo = GetLineNo(FileIn, Line, False)
250 EdkLogger.error("Unicode File Parser", PARSER_ERROR, "Wrong language definition",
251 ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File = File, Line = LineNo)
252 else:
253 LangName = GetLanguageCode(Lang[1], self.IsCompatibleMode, self.File)
254 LangPrintName = Lang[2]
255
256 IsLangInDef = False
257 for Item in self.LanguageDef:
258 if Item[0] == LangName:
259 IsLangInDef = True
260 break;
261
262 if not IsLangInDef:
263 self.LanguageDef.append([LangName, LangPrintName])
264
265 #
266 # Add language string
267 #
268 self.AddStringToList(u'$LANGUAGE_NAME', LangName, LangName, 0, True, Index=0)
269 self.AddStringToList(u'$PRINTABLE_LANGUAGE_NAME', LangName, LangPrintName, 1, True, Index=1)
270
271 if not IsLangInDef:
272 #
273 # The found STRING tokens will be added into new language string list
274 # so that the unique STRING identifier is reserved for all languages in the package list.
275 #
276 FirstLangName = self.LanguageDef[0][0]
277 if LangName != FirstLangName:
278 for Index in range (2, len (self.OrderedStringList[FirstLangName])):
279 Item = self.OrderedStringList[FirstLangName][Index]
280 if Item.UseOtherLangDef != '':
281 OtherLang = Item.UseOtherLangDef
282 else:
283 OtherLang = FirstLangName
284 self.OrderedStringList[LangName].append (StringDefClassObject(Item.StringName, '', Item.Referenced, Item.Token, OtherLang))
285 self.OrderedStringDict[LangName][Item.StringName] = len(self.OrderedStringList[LangName]) - 1
286 return True
287
288 def OpenUniFile(self, FileName):
289 #
290 # Read file
291 #
292 try:
293 UniFile = open(FileName, mode='rb')
294 FileIn = UniFile.read()
295 UniFile.close()
296 except:
297 EdkLogger.Error("build", FILE_OPEN_FAILURE, ExtraData=File)
298
299 #
300 # We currently only support UTF-16
301 #
302 Encoding = 'utf-16'
303
304 self.VerifyUcs2Data(FileIn, FileName, Encoding)
305
306 UniFile = StringIO.StringIO(FileIn)
307 Info = codecs.lookup(Encoding)
308 (Reader, Writer) = (Info.streamreader, Info.streamwriter)
309 return codecs.StreamReaderWriter(UniFile, Reader, Writer)
310
311 def VerifyUcs2Data(self, FileIn, FileName, Encoding):
312 Ucs2Info = codecs.lookup('ucs-2')
313 #
314 # Convert to unicode
315 #
316 try:
317 FileDecoded = codecs.decode(FileIn, Encoding)
318 Ucs2Info.encode(FileDecoded)
319 except:
320 UniFile = StringIO.StringIO(FileIn)
321 Info = codecs.lookup(Encoding)
322 (Reader, Writer) = (Info.streamreader, Info.streamwriter)
323 File = codecs.StreamReaderWriter(UniFile, Reader, Writer)
324 LineNumber = 0
325 ErrMsg = lambda Encoding, LineNumber: \
326 '%s contains invalid %s characters on line %d.' % \
327 (FileName, Encoding, LineNumber)
328 while True:
329 LineNumber = LineNumber + 1
330 try:
331 Line = File.readline()
332 if Line == '':
333 EdkLogger.error('Unicode File Parser', PARSER_ERROR,
334 ErrMsg(Encoding, LineNumber))
335 Ucs2Info.encode(Line)
336 except:
337 EdkLogger.error('Unicode File Parser', PARSER_ERROR,
338 ErrMsg('UCS-2', LineNumber))
339
340 #
341 # Get String name and value
342 #
343 def GetStringObject(self, Item):
344 Language = ''
345 Value = ''
346
347 Name = Item.split()[1]
348 # Check the string name is the upper character
349 if Name != '':
350 MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
351 if MatchString == None or MatchString.end(0) != len(Name):
352 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))
353 LanguageList = Item.split(u'#language ')
354 for IndexI in range(len(LanguageList)):
355 if IndexI == 0:
356 continue
357 else:
358 Language = LanguageList[IndexI].split()[0]
359 Value = LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')] #.replace(u'\r\n', u'')
360 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
361 self.AddStringToList(Name, Language, Value)
362
363 #
364 # Get include file list and load them
365 #
366 def GetIncludeFile(self, Item, Dir):
367 FileName = Item[Item.find(u'#include ') + len(u'#include ') :Item.find(u' ', len(u'#include '))][1:-1]
368 self.LoadUniFile(FileName)
369
370 def StripComments(self, Line):
371 Comment = u'//'
372 CommentPos = Line.find(Comment)
373 while CommentPos >= 0:
374 # if there are non matched quotes before the comment header
375 # then we are in the middle of a string
376 # but we need to ignore the escaped quotes and backslashes.
377 if ((Line.count(u'"', 0, CommentPos) - Line.count(u'\\"', 0, CommentPos)) & 1) == 1:
378 CommentPos = Line.find (Comment, CommentPos + 1)
379 else:
380 return Line[:CommentPos].strip()
381 return Line.strip()
382
383
384 #
385 # Pre-process before parse .uni file
386 #
387 def PreProcess(self, File):
388 if not os.path.exists(File.Path) or not os.path.isfile(File.Path):
389 EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, ExtraData=File.Path)
390
391 try:
392 FileIn = self.OpenUniFile(LongFilePath(File.Path))
393 except UnicodeError, X:
394 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File.Path);
395 except:
396 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File.Path);
397
398 Lines = []
399 #
400 # Use unique identifier
401 #
402 for Line in FileIn:
403 Line = Line.strip()
404 Line = Line.replace(u'\\\\', BACK_SLASH_PLACEHOLDER)
405 Line = self.StripComments(Line)
406
407 #
408 # Ignore empty line
409 #
410 if len(Line) == 0:
411 continue
412
413
414 Line = Line.replace(u'/langdef', u'#langdef')
415 Line = Line.replace(u'/string', u'#string')
416 Line = Line.replace(u'/language', u'#language')
417 Line = Line.replace(u'/include', u'#include')
418
419 Line = Line.replace(UNICODE_WIDE_CHAR, WIDE_CHAR)
420 Line = Line.replace(UNICODE_NARROW_CHAR, NARROW_CHAR)
421 Line = Line.replace(UNICODE_NON_BREAKING_CHAR, NON_BREAKING_CHAR)
422
423 Line = Line.replace(u'\\r\\n', CR + LF)
424 Line = Line.replace(u'\\n', CR + LF)
425 Line = Line.replace(u'\\r', CR)
426 Line = Line.replace(u'\\t', u' ')
427 Line = Line.replace(u'\t', u' ')
428 Line = Line.replace(u'\\"', u'"')
429 Line = Line.replace(u"\\'", u"'")
430 Line = Line.replace(BACK_SLASH_PLACEHOLDER, u'\\')
431
432 # if Line.find(u'\\x'):
433 # hex = Line[Line.find(u'\\x') + 2 : Line.find(u'\\x') + 6]
434 # hex = "u'\\u" + hex + "'"
435
436 IncList = gIncludePattern.findall(Line)
437 if len(IncList) == 1:
438 for Dir in [File.Dir] + self.IncludePathList:
439 IncFile = PathClass(str(IncList[0]), Dir)
440 if os.path.isfile(IncFile.Path):
441 Lines.extend(self.PreProcess(IncFile))
442 break
443 else:
444 EdkLogger.error("Unicode File Parser", FILE_NOT_FOUND, Message="Cannot find include file", ExtraData=str(IncList[0]))
445 continue
446
447 Lines.append(Line)
448
449 return Lines
450
451 #
452 # Load a .uni file
453 #
454 def LoadUniFile(self, File = None):
455 if File == None:
456 EdkLogger.error("Unicode File Parser", PARSER_ERROR, 'No unicode file is given')
457 self.File = File
458 #
459 # Process special char in file
460 #
461 Lines = self.PreProcess(File)
462
463 #
464 # Get Unicode Information
465 #
466 for IndexI in range(len(Lines)):
467 Line = Lines[IndexI]
468 if (IndexI + 1) < len(Lines):
469 SecondLine = Lines[IndexI + 1]
470 if (IndexI + 2) < len(Lines):
471 ThirdLine = Lines[IndexI + 2]
472
473 #
474 # Get Language def information
475 #
476 if Line.find(u'#langdef ') >= 0:
477 self.GetLangDef(File, Line)
478 continue
479
480 Name = ''
481 Language = ''
482 Value = ''
483 #
484 # Get string def information format 1 as below
485 #
486 # #string MY_STRING_1
487 # #language eng
488 # My first English string line 1
489 # My first English string line 2
490 # #string MY_STRING_1
491 # #language spa
492 # Mi segunda secuencia 1
493 # Mi segunda secuencia 2
494 #
495 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') < 0 and \
496 SecondLine.find(u'#string ') < 0 and SecondLine.find(u'#language ') >= 0 and \
497 ThirdLine.find(u'#string ') < 0 and ThirdLine.find(u'#language ') < 0:
498 Name = Line[Line.find(u'#string ') + len(u'#string ') : ].strip(' ')
499 Language = SecondLine[SecondLine.find(u'#language ') + len(u'#language ') : ].strip(' ')
500 for IndexJ in range(IndexI + 2, len(Lines)):
501 if Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') < 0:
502 Value = Value + Lines[IndexJ]
503 else:
504 IndexI = IndexJ
505 break
506 # Value = Value.replace(u'\r\n', u'')
507 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
508 # Check the string name is the upper character
509 if not self.IsCompatibleMode and Name != '':
510 MatchString = re.match('[A-Z0-9_]+', Name, re.UNICODE)
511 if MatchString == None or MatchString.end(0) != len(Name):
512 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))
513 self.AddStringToList(Name, Language, Value)
514 continue
515
516 #
517 # Get string def information format 2 as below
518 #
519 # #string MY_STRING_1 #language eng "My first English string line 1"
520 # "My first English string line 2"
521 # #language spa "Mi segunda secuencia 1"
522 # "Mi segunda secuencia 2"
523 # #string MY_STRING_2 #language eng "My first English string line 1"
524 # "My first English string line 2"
525 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
526 # "Mi segunda secuencia 2"
527 #
528 if Line.find(u'#string ') >= 0 and Line.find(u'#language ') >= 0:
529 StringItem = Line
530 for IndexJ in range(IndexI + 1, len(Lines)):
531 if Lines[IndexJ].find(u'#string ') >= 0 and Lines[IndexJ].find(u'#language ') >= 0:
532 IndexI = IndexJ
533 break
534 elif Lines[IndexJ].find(u'#string ') < 0 and Lines[IndexJ].find(u'#language ') >= 0:
535 StringItem = StringItem + Lines[IndexJ]
536 elif Lines[IndexJ].count(u'\"') >= 2:
537 StringItem = StringItem[ : StringItem.rfind(u'\"')] + Lines[IndexJ][Lines[IndexJ].find(u'\"') + len(u'\"') : ]
538 self.GetStringObject(StringItem)
539 continue
540
541 #
542 # Load multiple .uni files
543 #
544 def LoadUniFiles(self, FileList):
545 if len(FileList) > 0:
546 for File in FileList:
547 self.LoadUniFile(File)
548
549 #
550 # Add a string to list
551 #
552 def AddStringToList(self, Name, Language, Value, Token = None, Referenced = False, UseOtherLangDef = '', Index = -1):
553 for LangNameItem in self.LanguageDef:
554 if Language == LangNameItem[0]:
555 break
556 else:
557 EdkLogger.error('Unicode File Parser', FORMAT_NOT_SUPPORTED, "The language '%s' for %s is not defined in Unicode file %s." \
558 % (Language, Name, self.File))
559
560 if Language not in self.OrderedStringList:
561 self.OrderedStringList[Language] = []
562 self.OrderedStringDict[Language] = {}
563
564 IsAdded = True
565 if Name in self.OrderedStringDict[Language]:
566 IsAdded = False
567 if Value != None:
568 ItemIndexInList = self.OrderedStringDict[Language][Name]
569 Item = self.OrderedStringList[Language][ItemIndexInList]
570 Item.UpdateValue(Value)
571 Item.UseOtherLangDef = ''
572
573 if IsAdded:
574 Token = len(self.OrderedStringList[Language])
575 if Index == -1:
576 self.OrderedStringList[Language].append(StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
577 self.OrderedStringDict[Language][Name] = Token
578 for LangName in self.LanguageDef:
579 #
580 # New STRING token will be added into all language string lists.
581 # so that the unique STRING identifier is reserved for all languages in the package list.
582 #
583 if LangName[0] != Language:
584 if UseOtherLangDef != '':
585 OtherLangDef = UseOtherLangDef
586 else:
587 OtherLangDef = Language
588 self.OrderedStringList[LangName[0]].append(StringDefClassObject(Name, '', Referenced, Token, OtherLangDef))
589 self.OrderedStringDict[LangName[0]][Name] = len(self.OrderedStringList[LangName[0]]) - 1
590 else:
591 self.OrderedStringList[Language].insert(Index, StringDefClassObject(Name, Value, Referenced, Token, UseOtherLangDef))
592 self.OrderedStringDict[Language][Name] = Index
593
594 #
595 # Set the string as referenced
596 #
597 def SetStringReferenced(self, Name):
598 #
599 # String stoken are added in the same order in all language string lists.
600 # So, only update the status of string stoken in first language string list.
601 #
602 Lang = self.LanguageDef[0][0]
603 if Name in self.OrderedStringDict[Lang]:
604 ItemIndexInList = self.OrderedStringDict[Lang][Name]
605 Item = self.OrderedStringList[Lang][ItemIndexInList]
606 Item.Referenced = True
607
608 #
609 # Search the string in language definition by Name
610 #
611 def FindStringValue(self, Name, Lang):
612 if Name in self.OrderedStringDict[Lang]:
613 ItemIndexInList = self.OrderedStringDict[Lang][Name]
614 return self.OrderedStringList[Lang][ItemIndexInList]
615
616 return None
617
618 #
619 # Search the string in language definition by Token
620 #
621 def FindByToken(self, Token, Lang):
622 for Item in self.OrderedStringList[Lang]:
623 if Item.Token == Token:
624 return Item
625
626 return None
627
628 #
629 # Re-order strings and re-generate tokens
630 #
631 def ReToken(self):
632 #
633 # Retoken all language strings according to the status of string stoken in the first language string.
634 #
635 FirstLangName = self.LanguageDef[0][0]
636
637 # Convert the OrderedStringList to be OrderedStringListByToken in order to faciliate future search by token
638 for LangNameItem in self.LanguageDef:
639 self.OrderedStringListByToken[LangNameItem[0]] = {}
640
641 #
642 # Use small token for all referred string stoken.
643 #
644 RefToken = 0
645 for Index in range (0, len (self.OrderedStringList[FirstLangName])):
646 FirstLangItem = self.OrderedStringList[FirstLangName][Index]
647 if FirstLangItem.Referenced == True:
648 for LangNameItem in self.LanguageDef:
649 LangName = LangNameItem[0]
650 OtherLangItem = self.OrderedStringList[LangName][Index]
651 OtherLangItem.Referenced = True
652 OtherLangItem.Token = RefToken
653 self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem
654 RefToken = RefToken + 1
655
656 #
657 # Use big token for all unreferred string stoken.
658 #
659 UnRefToken = 0
660 for Index in range (0, len (self.OrderedStringList[FirstLangName])):
661 FirstLangItem = self.OrderedStringList[FirstLangName][Index]
662 if FirstLangItem.Referenced == False:
663 for LangNameItem in self.LanguageDef:
664 LangName = LangNameItem[0]
665 OtherLangItem = self.OrderedStringList[LangName][Index]
666 OtherLangItem.Token = RefToken + UnRefToken
667 self.OrderedStringListByToken[LangName][OtherLangItem.Token] = OtherLangItem
668 UnRefToken = UnRefToken + 1
669
670 #
671 # Show the instance itself
672 #
673 def ShowMe(self):
674 print self.LanguageDef
675 #print self.OrderedStringList
676 for Item in self.OrderedStringList:
677 print Item
678 for Member in self.OrderedStringList[Item]:
679 print str(Member)
680
681 # This acts like the main() function for the script, unless it is 'import'ed into another
682 # script.
683 if __name__ == '__main__':
684 EdkLogger.Initialize()
685 EdkLogger.SetLevel(EdkLogger.DEBUG_0)
686 a = UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])
687 a.ReToken()
688 a.ShowMe()