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