BaseTools: Use precompiled RegExp
[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 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 from Common.GlobalData import *
28 ##
29 # Static definitions
30 #
31 UNICODE_WIDE_CHAR = u'\\wide'
32 UNICODE_NARROW_CHAR = u'\\narrow'
33 UNICODE_NON_BREAKING_CHAR = u'\\nbr'
34 UNICODE_UNICODE_CR = '\r'
35 UNICODE_UNICODE_LF = '\n'
36
37 NARROW_CHAR = u'\uFFF0'
38 WIDE_CHAR = u'\uFFF1'
39 NON_BREAKING_CHAR = u'\uFFF2'
40 CR = u'\u000D'
41 LF = u'\u000A'
42 NULL = u'\u0000'
43 TAB = u'\t'
44 BACK_SLASH_PLACEHOLDER = u'\u0006'
45
46 gIncludePattern = re.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re.MULTILINE | re.UNICODE)
47
48 ## Convert a python unicode string to a normal string
49 #
50 # Convert a python unicode string to a normal string
51 # UniToStr(u'I am a string') is 'I am a string'
52 #
53 # @param Uni: The python unicode string
54 #
55 # @retval: The formatted normal string
56 #
57 def UniToStr(Uni):
58 return repr(Uni)[2:-1]
59
60 ## Convert a unicode string to a Hex list
61 #
62 # Convert a unicode string to a Hex list
63 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
64 #
65 # @param Uni: The python unicode string
66 #
67 # @retval List: The formatted hex list
68 #
69 def UniToHexList(Uni):
70 List = []
71 for Item in Uni:
72 Temp = '%04X' % ord(Item)
73 List.append('0x' + Temp[2:4])
74 List.append('0x' + Temp[0:2])
75 return List
76
77 LangConvTable = {'eng':'en', 'fra':'fr', \
78 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
79 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
80 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
81 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
82 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
83 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
84 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
85 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
86 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
87 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
88 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
89 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
90 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
91 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
92 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
93 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
94 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
95 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
96 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
97 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
98 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
99 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
100 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
101 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
102 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
103 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
104 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
105 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
106 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
107 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
108 'zho':'zh', 'zul':'zu'}
109
110 ## GetLanguageCode
111 #
112 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
113 # ISO 639-2 language codes supported in compatiblity mode
114 # RFC 4646 language codes supported in native mode
115 #
116 # @param LangName: Language codes read from .UNI file
117 #
118 # @retval LangName: Valid lanugage code in RFC 4646 format or None
119 #
120 def GetLanguageCode(LangName, IsCompatibleMode, File):
121 global LangConvTable
122
123 length = len(LangName)
124 if IsCompatibleMode:
125 if length == 3 and LangName.isalpha():
126 TempLangName = LangConvTable.get(LangName.lower())
127 if TempLangName != None:
128 return TempLangName
129 return LangName
130 else:
131 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid ISO 639-2 language code : %s" % LangName, File)
132
133 if (LangName[0] == 'X' or LangName[0] == 'x') and LangName[1] == '-':
134 return LangName
135 if length == 2:
136 if LangName.isalpha():
137 return LangName
138 elif length == 3:
139 if LangName.isalpha() and LangConvTable.get(LangName.lower()) == None:
140 return LangName
141 elif length == 5:
142 if LangName[0:2].isalpha() and LangName[2] == '-':
143 return LangName
144 elif length >= 6:
145 if LangName[0:2].isalpha() and LangName[2] == '-':
146 return LangName
147 if LangName[0:3].isalpha() and LangConvTable.get(LangName.lower()) == None and LangName[3] == '-':
148 return LangName
149
150 EdkLogger.error("Unicode File Parser", FORMAT_INVALID, "Invalid RFC 4646 language code : %s" % LangName, File)
151
152 ## Ucs2Codec
153 #
154 # This is only a partial codec implementation. It only supports
155 # encoding, and is primarily used to check that all the characters are
156 # valid for UCS-2.
157 #
158 class Ucs2Codec(codecs.Codec):
159 def __init__(self):
160 self.__utf16 = codecs.lookup('utf-16')
161
162 def encode(self, input, errors='strict'):
163 for Char in input:
164 CodePoint = ord(Char)
165 if CodePoint >= 0xd800 and CodePoint <= 0xdfff:
166 raise ValueError("Code Point is in range reserved for " +
167 "UTF-16 surrogate pairs")
168 elif CodePoint > 0xffff:
169 raise ValueError("Code Point too large to encode in UCS-2")
170 return self.__utf16.encode(input)
171
172 TheUcs2Codec = Ucs2Codec()
173 def Ucs2Search(name):
174 if name == 'ucs-2':
175 return codecs.CodecInfo(
176 name=name,
177 encode=TheUcs2Codec.encode,
178 decode=TheUcs2Codec.decode)
179 else:
180 return None
181 codecs.register(Ucs2Search)
182
183 ## StringDefClassObject
184 #
185 # A structure for language definition
186 #
187 class StringDefClassObject(object):
188 def __init__(self, Name = None, Value = None, Referenced = False, Token = None, UseOtherLangDef = ''):
189 self.StringName = ''
190 self.StringNameByteList = []
191 self.StringValue = ''
192 self.StringValueByteList = ''
193 self.Token = 0
194 self.Referenced = Referenced
195 self.UseOtherLangDef = UseOtherLangDef
196 self.Length = 0
197
198 if Name != None:
199 self.StringName = Name
200 self.StringNameByteList = UniToHexList(Name)
201 if Value != None:
202 self.StringValue = Value + u'\x00' # Add a NULL at string tail
203 self.StringValueByteList = UniToHexList(self.StringValue)
204 self.Length = len(self.StringValueByteList)
205 if Token != None:
206 self.Token = Token
207
208 def __str__(self):
209 return repr(self.StringName) + ' ' + \
210 repr(self.Token) + ' ' + \
211 repr(self.Referenced) + ' ' + \
212 repr(self.StringValue) + ' ' + \
213 repr(self.UseOtherLangDef)
214
215 def UpdateValue(self, Value = None):
216 if Value != None:
217 self.StringValue = Value + u'\x00' # Add a NULL at string tail
218 self.StringValueByteList = UniToHexList(self.StringValue)
219 self.Length = len(self.StringValueByteList)
220
221 ## UniFileClassObject
222 #
223 # A structure for .uni file definition
224 #
225 class UniFileClassObject(object):
226 def __init__(self, FileList = [], IsCompatibleMode = False, IncludePathList = []):
227 self.FileList = FileList
228 self.Token = 2
229 self.LanguageDef = [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
230 self.OrderedStringList = {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
231 self.OrderedStringDict = {} #{ u'LanguageIdentifier' : {StringName:(IndexInList)} }
232 self.OrderedStringListByToken = {} #{ u'LanguageIdentifier' : {Token: StringDefClassObject} }
233 self.IsCompatibleMode = IsCompatibleMode
234 self.IncludePathList = IncludePathList
235 if len(self.FileList) > 0:
236 self.LoadUniFiles(FileList)
237
238 #
239 # Get Language definition
240 #
241 def GetLangDef(self, File, Line):
242 Lang = distutils.util.split_quoted((Line.split(u"//")[0]))
243 if len(Lang) != 3:
244 try:
245 FileIn = self.OpenUniFile(LongFilePath(File.Path))
246 except UnicodeError, X:
247 EdkLogger.error("build", FILE_READ_FAILURE, "File read failure: %s" % str(X), ExtraData=File);
248 except:
249 EdkLogger.error("build", FILE_OPEN_FAILURE, ExtraData=File);
250 LineNo = GetLineNo(FileIn, Line, False)
251 EdkLogger.error("Unicode File Parser", PARSER_ERROR, "Wrong language definition",
252 ExtraData="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line, File=File, Line=LineNo)
253 else:
254 LangName = GetLanguageCode(Lang[1], self.IsCompatibleMode, self.File)
255 LangPrintName = Lang[2]
256
257 IsLangInDef = False
258 for Item in self.LanguageDef:
259 if Item[0] == LangName:
260 IsLangInDef = True
261 break;
262
263 if not IsLangInDef:
264 self.LanguageDef.append([LangName, LangPrintName])
265
266 #
267 # Add language string
268 #
269 self.AddStringToList(u'$LANGUAGE_NAME', LangName, LangName, 0, True, Index=0)
270 self.AddStringToList(u'$PRINTABLE_LANGUAGE_NAME', LangName, LangPrintName, 1, True, Index=1)
271
272 if not IsLangInDef:
273 #
274 # The found STRING tokens will be added into new language string list
275 # so that the unique STRING identifier is reserved for all languages in the package list.
276 #
277 FirstLangName = self.LanguageDef[0][0]
278 if LangName != FirstLangName:
279 for Index in range (2, len (self.OrderedStringList[FirstLangName])):
280 Item = self.OrderedStringList[FirstLangName][Index]
281 if Item.UseOtherLangDef != '':
282 OtherLang = Item.UseOtherLangDef
283 else:
284 OtherLang = FirstLangName
285 self.OrderedStringList[LangName].append (StringDefClassObject(Item.StringName, '', Item.Referenced, Item.Token, OtherLang))
286 self.OrderedStringDict[LangName][Item.StringName] = len(self.OrderedStringList[LangName]) - 1
287 return True
288
289 def OpenUniFile(self, FileName):
290 #
291 # Read file
292 #
293 try:
294 UniFile = open(FileName, mode='rb')
295 FileIn = UniFile.read()
296 UniFile.close()
297 except:
298 EdkLogger.Error("build", FILE_OPEN_FAILURE, ExtraData=File)
299
300 #
301 # Detect Byte Order Mark at beginning of file. Default to UTF-8
302 #
303 Encoding = 'utf-8'
304 if (FileIn.startswith(codecs.BOM_UTF16_BE) or
305 FileIn.startswith(codecs.BOM_UTF16_LE)):
306 Encoding = 'utf-16'
307
308 self.VerifyUcs2Data(FileIn, FileName, Encoding)
309
310 UniFile = StringIO.StringIO(FileIn)
311 Info = codecs.lookup(Encoding)
312 (Reader, Writer) = (Info.streamreader, Info.streamwriter)
313 return codecs.StreamReaderWriter(UniFile, Reader, Writer)
314
315 def VerifyUcs2Data(self, FileIn, FileName, Encoding):
316 Ucs2Info = codecs.lookup('ucs-2')
317 #
318 # Convert to unicode
319 #
320 try:
321 FileDecoded = codecs.decode(FileIn, Encoding)
322 Ucs2Info.encode(FileDecoded)
323 except:
324 UniFile = StringIO.StringIO(FileIn)
325 Info = codecs.lookup(Encoding)
326 (Reader, Writer) = (Info.streamreader, Info.streamwriter)
327 File = codecs.StreamReaderWriter(UniFile, Reader, Writer)
328 LineNumber = 0
329 ErrMsg = lambda Encoding, LineNumber: \
330 '%s contains invalid %s characters on line %d.' % \
331 (FileName, Encoding, LineNumber)
332 while True:
333 LineNumber = LineNumber + 1
334 try:
335 Line = File.readline()
336 if Line == '':
337 EdkLogger.error('Unicode File Parser', PARSER_ERROR,
338 ErrMsg(Encoding, LineNumber))
339 Ucs2Info.encode(Line)
340 except:
341 EdkLogger.error('Unicode File Parser', PARSER_ERROR,
342 ErrMsg('UCS-2', LineNumber))
343
344 #
345 # Get String name and value
346 #
347 def GetStringObject(self, Item):
348 Language = ''
349 Value = ''
350
351 Name = Item.split()[1]
352 # Check the string name
353 if Name != '':
354 MatchString = re.match('^[a-zA-Z][a-zA-Z0-9_]*$', Name, re.UNICODE)
355 if MatchString == None or MatchString.end(0) != len(Name):
356 EdkLogger.error('Unicode File Parser', FORMAT_INVALID, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name, self.File))
357 LanguageList = Item.split(u'#language ')
358 for IndexI in range(len(LanguageList)):
359 if IndexI == 0:
360 continue
361 else:
362 Language = LanguageList[IndexI].split()[0]
363 Value = LanguageList[IndexI][LanguageList[IndexI].find(u'\"') + len(u'\"') : LanguageList[IndexI].rfind(u'\"')] #.replace(u'\r\n', u'')
364 Language = GetLanguageCode(Language, self.IsCompatibleMode, self.File)
365 self.AddStringToList(Name, Language, Value)
366
367 #
368 # Get include file list and load them
369 #
370 def GetIncludeFile(self, Item, Dir):
371 FileName = Item[Item.find(u'#include ') + len(u'#include ') :Item.find(u' ', len(u'#include '))][1:-1]
372 self.LoadUniFile(FileName)
373
374 def StripComments(self, Line):
375 Comment = u'//'
376 CommentPos = Line.find(Comment)
377 while CommentPos >= 0:
378 # if there are non matched quotes before the comment header
379 # then we are in the middle of a string
380 # but we need to ignore the escaped quotes and backslashes.
381 if ((Line.count(u'"', 0, CommentPos) - Line.count(u'\\"', 0, CommentPos)) & 1) == 1:
382 CommentPos = Line.find (Comment, CommentPos + 1)
383 else:
384 return Line[:CommentPos].strip()
385 return Line.strip()
386
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 = self.OpenUniFile(LongFilePath(File.Path))
397 except UnicodeError, 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 = self.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 == 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 = re.match('^[a-zA-Z][a-zA-Z0-9_]*$', Name, re.UNICODE)
525 if MatchString == None or MatchString.end(0) != len(Name):
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 != 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()