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