2 # This file is used to collect all defined strings in multiple uni files
5 # Copyright (c) 2014 Hewlett-Packard Development Company, L.P.<BR>
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
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.
19 from __future__
import print_function
20 import Common
.LongFilePathOs
as os
, codecs
, re
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 *
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'
38 NARROW_CHAR
= u
'\uFFF0'
40 NON_BREAKING_CHAR
= u
'\uFFF2'
45 BACK_SLASH_PLACEHOLDER
= u
'\u0006'
47 gIncludePattern
= re
.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re
.MULTILINE | re
.UNICODE
)
49 ## Convert a unicode string to a Hex list
51 # Convert a unicode string to a Hex list
52 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
54 # @param Uni: The python unicode string
56 # @retval List: The formatted hex list
58 def UniToHexList(Uni
):
61 Temp
= '%04X' % ord(Item
)
62 List
.append('0x' + Temp
[2:4])
63 List
.append('0x' + Temp
[0:2])
66 LangConvTable
= {'eng':'en', 'fra':'fr', \
67 'aar':'aa', 'abk':'ab', 'ave':'ae', 'afr':'af', 'aka':'ak', 'amh':'am', \
68 'arg':'an', 'ara':'ar', 'asm':'as', 'ava':'av', 'aym':'ay', 'aze':'az', \
69 'bak':'ba', 'bel':'be', 'bul':'bg', 'bih':'bh', 'bis':'bi', 'bam':'bm', \
70 'ben':'bn', 'bod':'bo', 'bre':'br', 'bos':'bs', 'cat':'ca', 'che':'ce', \
71 'cha':'ch', 'cos':'co', 'cre':'cr', 'ces':'cs', 'chu':'cu', 'chv':'cv', \
72 'cym':'cy', 'dan':'da', 'deu':'de', 'div':'dv', 'dzo':'dz', 'ewe':'ee', \
73 'ell':'el', 'epo':'eo', 'spa':'es', 'est':'et', 'eus':'eu', 'fas':'fa', \
74 'ful':'ff', 'fin':'fi', 'fij':'fj', 'fao':'fo', 'fry':'fy', 'gle':'ga', \
75 'gla':'gd', 'glg':'gl', 'grn':'gn', 'guj':'gu', 'glv':'gv', 'hau':'ha', \
76 'heb':'he', 'hin':'hi', 'hmo':'ho', 'hrv':'hr', 'hat':'ht', 'hun':'hu', \
77 'hye':'hy', 'her':'hz', 'ina':'ia', 'ind':'id', 'ile':'ie', 'ibo':'ig', \
78 'iii':'ii', 'ipk':'ik', 'ido':'io', 'isl':'is', 'ita':'it', 'iku':'iu', \
79 'jpn':'ja', 'jav':'jv', 'kat':'ka', 'kon':'kg', 'kik':'ki', 'kua':'kj', \
80 'kaz':'kk', 'kal':'kl', 'khm':'km', 'kan':'kn', 'kor':'ko', 'kau':'kr', \
81 'kas':'ks', 'kur':'ku', 'kom':'kv', 'cor':'kw', 'kir':'ky', 'lat':'la', \
82 'ltz':'lb', 'lug':'lg', 'lim':'li', 'lin':'ln', 'lao':'lo', 'lit':'lt', \
83 'lub':'lu', 'lav':'lv', 'mlg':'mg', 'mah':'mh', 'mri':'mi', 'mkd':'mk', \
84 'mal':'ml', 'mon':'mn', 'mar':'mr', 'msa':'ms', 'mlt':'mt', 'mya':'my', \
85 'nau':'na', 'nob':'nb', 'nde':'nd', 'nep':'ne', 'ndo':'ng', 'nld':'nl', \
86 'nno':'nn', 'nor':'no', 'nbl':'nr', 'nav':'nv', 'nya':'ny', 'oci':'oc', \
87 'oji':'oj', 'orm':'om', 'ori':'or', 'oss':'os', 'pan':'pa', 'pli':'pi', \
88 'pol':'pl', 'pus':'ps', 'por':'pt', 'que':'qu', 'roh':'rm', 'run':'rn', \
89 'ron':'ro', 'rus':'ru', 'kin':'rw', 'san':'sa', 'srd':'sc', 'snd':'sd', \
90 'sme':'se', 'sag':'sg', 'sin':'si', 'slk':'sk', 'slv':'sl', 'smo':'sm', \
91 'sna':'sn', 'som':'so', 'sqi':'sq', 'srp':'sr', 'ssw':'ss', 'sot':'st', \
92 'sun':'su', 'swe':'sv', 'swa':'sw', 'tam':'ta', 'tel':'te', 'tgk':'tg', \
93 'tha':'th', 'tir':'ti', 'tuk':'tk', 'tgl':'tl', 'tsn':'tn', 'ton':'to', \
94 'tur':'tr', 'tso':'ts', 'tat':'tt', 'twi':'tw', 'tah':'ty', 'uig':'ug', \
95 'ukr':'uk', 'urd':'ur', 'uzb':'uz', 'ven':'ve', 'vie':'vi', 'vol':'vo', \
96 'wln':'wa', 'wol':'wo', 'xho':'xh', 'yid':'yi', 'yor':'yo', 'zha':'za', \
97 'zho':'zh', 'zul':'zu'}
101 # Check the language code read from .UNI file and convert ISO 639-2 codes to RFC 4646 codes if appropriate
102 # ISO 639-2 language codes supported in compatiblity mode
103 # RFC 4646 language codes supported in native mode
105 # @param LangName: Language codes read from .UNI file
107 # @retval LangName: Valid lanugage code in RFC 4646 format or None
109 def GetLanguageCode(LangName
, IsCompatibleMode
, File
):
110 length
= len(LangName
)
112 if length
== 3 and LangName
.isalpha():
113 TempLangName
= LangConvTable
.get(LangName
.lower())
114 if TempLangName
is not None:
118 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid ISO 639-2 language code : %s" % LangName
, File
)
120 if (LangName
[0] == 'X' or LangName
[0] == 'x') and LangName
[1] == '-':
123 if LangName
.isalpha():
126 if LangName
.isalpha() and LangConvTable
.get(LangName
.lower()) is None:
129 if LangName
[0:2].isalpha() and LangName
[2] == '-':
132 if LangName
[0:2].isalpha() and LangName
[2] == '-':
134 if LangName
[0:3].isalpha() and LangConvTable
.get(LangName
.lower()) is None and LangName
[3] == '-':
137 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid RFC 4646 language code : %s" % LangName
, File
)
141 # This is only a partial codec implementation. It only supports
142 # encoding, and is primarily used to check that all the characters are
145 class Ucs2Codec(codecs
.Codec
):
147 self
.__utf
16 = codecs
.lookup('utf-16')
149 def encode(self
, input, errors
='strict'):
151 CodePoint
= ord(Char
)
152 if CodePoint
>= 0xd800 and CodePoint
<= 0xdfff:
153 raise ValueError("Code Point is in range reserved for " +
154 "UTF-16 surrogate pairs")
155 elif CodePoint
> 0xffff:
156 raise ValueError("Code Point too large to encode in UCS-2")
157 return self
.__utf
16.encode(input)
159 TheUcs2Codec
= Ucs2Codec()
160 def Ucs2Search(name
):
162 return codecs
.CodecInfo(
164 encode
=TheUcs2Codec
.encode
,
165 decode
=TheUcs2Codec
.decode
)
168 codecs
.register(Ucs2Search
)
170 ## StringDefClassObject
172 # A structure for language definition
174 class StringDefClassObject(object):
175 def __init__(self
, Name
= None, Value
= None, Referenced
= False, Token
= None, UseOtherLangDef
= ''):
177 self
.StringNameByteList
= []
178 self
.StringValue
= ''
179 self
.StringValueByteList
= ''
181 self
.Referenced
= Referenced
182 self
.UseOtherLangDef
= UseOtherLangDef
186 self
.StringName
= Name
187 self
.StringNameByteList
= UniToHexList(Name
)
188 if Value
is not None:
189 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
190 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
191 self
.Length
= len(self
.StringValueByteList
)
192 if Token
is not None:
196 return repr(self
.StringName
) + ' ' + \
197 repr(self
.Token
) + ' ' + \
198 repr(self
.Referenced
) + ' ' + \
199 repr(self
.StringValue
) + ' ' + \
200 repr(self
.UseOtherLangDef
)
202 def UpdateValue(self
, Value
= None):
203 if Value
is not None:
204 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
205 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
206 self
.Length
= len(self
.StringValueByteList
)
208 def StripComments(Line
):
210 CommentPos
= Line
.find(Comment
)
211 while CommentPos
>= 0:
212 # if there are non matched quotes before the comment header
213 # then we are in the middle of a string
214 # but we need to ignore the escaped quotes and backslashes.
215 if ((Line
.count(u
'"', 0, CommentPos
) - Line
.count(u
'\\"', 0, CommentPos
)) & 1) == 1:
216 CommentPos
= Line
.find (Comment
, CommentPos
+ 1)
218 return Line
[:CommentPos
].strip()
221 ## UniFileClassObject
223 # A structure for .uni file definition
225 class UniFileClassObject(object):
226 def __init__(self
, FileList
= [], IsCompatibleMode
= False, IncludePathList
= []):
227 self
.FileList
= FileList
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
)
239 # Get Language definition
241 def GetLangDef(self
, File
, Line
):
242 Lang
= distutils
.util
.split_quoted((Line
.split(u
"//")[0]))
245 FileIn
= UniFileClassObject
.OpenUniFile(LongFilePath(File
.Path
))
246 except UnicodeError as X
:
247 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
);
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
)
254 LangName
= GetLanguageCode(Lang
[1], self
.IsCompatibleMode
, self
.File
)
255 LangPrintName
= Lang
[2]
258 for Item
in self
.LanguageDef
:
259 if Item
[0] == LangName
:
264 self
.LanguageDef
.append([LangName
, LangPrintName
])
267 # Add language string
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)
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.
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
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
290 def OpenUniFile(FileName
):
295 UniFile
= open(FileName
, mode
='rb')
296 FileIn
= UniFile
.read()
299 EdkLogger
.Error("build", FILE_OPEN_FAILURE
, ExtraData
=File
)
302 # Detect Byte Order Mark at beginning of file. Default to UTF-8
305 if (FileIn
.startswith(codecs
.BOM_UTF16_BE
) or
306 FileIn
.startswith(codecs
.BOM_UTF16_LE
)):
309 UniFileClassObject
.VerifyUcs2Data(FileIn
, FileName
, Encoding
)
311 UniFile
= BytesIO(FileIn
)
312 Info
= codecs
.lookup(Encoding
)
313 (Reader
, Writer
) = (Info
.streamreader
, Info
.streamwriter
)
314 return codecs
.StreamReaderWriter(UniFile
, Reader
, Writer
)
317 def VerifyUcs2Data(FileIn
, FileName
, Encoding
):
318 Ucs2Info
= codecs
.lookup('ucs-2')
323 FileDecoded
= codecs
.decode(FileIn
, Encoding
)
324 Ucs2Info
.encode(FileDecoded
)
326 UniFile
= BytesIO(FileIn
)
327 Info
= codecs
.lookup(Encoding
)
328 (Reader
, Writer
) = (Info
.streamreader
, Info
.streamwriter
)
329 File
= codecs
.StreamReaderWriter(UniFile
, Reader
, Writer
)
331 ErrMsg
= lambda Encoding
, LineNumber
: \
332 '%s contains invalid %s characters on line %d.' % \
333 (FileName
, Encoding
, LineNumber
)
335 LineNumber
= LineNumber
+ 1
337 Line
= File
.readline()
339 EdkLogger
.error('Unicode File Parser', PARSER_ERROR
,
340 ErrMsg(Encoding
, LineNumber
))
341 Ucs2Info
.encode(Line
)
343 EdkLogger
.error('Unicode File Parser', PARSER_ERROR
,
344 ErrMsg('UCS-2', LineNumber
))
347 # Get String name and value
349 def GetStringObject(self
, Item
):
353 Name
= Item
.split()[1]
354 # Check the string name
356 MatchString
= gIdentifierPattern
.match(Name
)
357 if MatchString
is None:
358 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name
, self
.File
))
359 LanguageList
= Item
.split(u
'#language ')
360 for IndexI
in range(len(LanguageList
)):
364 Language
= LanguageList
[IndexI
].split()[0]
365 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
366 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
367 self
.AddStringToList(Name
, Language
, Value
)
370 # Get include file list and load them
372 def GetIncludeFile(self
, Item
, Dir
):
373 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
374 self
.LoadUniFile(FileName
)
377 # Pre-process before parse .uni file
379 def PreProcess(self
, File
):
380 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
381 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
384 FileIn
= UniFileClassObject
.OpenUniFile(LongFilePath(File
.Path
))
385 except UnicodeError as X
:
386 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
388 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
392 # Use unique identifier
396 Line
= Line
.replace(u
'\\\\', BACK_SLASH_PLACEHOLDER
)
397 Line
= StripComments(Line
)
406 Line
= Line
.replace(u
'/langdef', u
'#langdef')
407 Line
= Line
.replace(u
'/string', u
'#string')
408 Line
= Line
.replace(u
'/language', u
'#language')
409 Line
= Line
.replace(u
'/include', u
'#include')
411 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
412 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
413 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
415 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
416 Line
= Line
.replace(u
'\\n', CR
+ LF
)
417 Line
= Line
.replace(u
'\\r', CR
)
418 Line
= Line
.replace(u
'\\t', u
' ')
419 Line
= Line
.replace(u
'\t', u
' ')
420 Line
= Line
.replace(u
'\\"', u
'"')
421 Line
= Line
.replace(u
"\\'", u
"'")
422 Line
= Line
.replace(BACK_SLASH_PLACEHOLDER
, u
'\\')
424 StartPos
= Line
.find(u
'\\x')
425 while (StartPos
!= -1):
426 EndPos
= Line
.find(u
'\\', StartPos
+ 1, StartPos
+ 7)
427 if EndPos
!= -1 and EndPos
- StartPos
== 6 :
428 if g4HexChar
.match(Line
[StartPos
+ 2 : EndPos
], re
.UNICODE
):
429 EndStr
= Line
[EndPos
: ]
430 UniStr
= Line
[StartPos
+ 2: EndPos
]
431 if EndStr
.startswith(u
'\\x') and len(EndStr
) >= 7:
432 if EndStr
[6] == u
'\\' and g4HexChar
.match(EndStr
[2 : 6], re
.UNICODE
):
433 Line
= Line
[0 : StartPos
] + UniStr
+ EndStr
435 Line
= Line
[0 : StartPos
] + UniStr
+ EndStr
[1:]
436 StartPos
= Line
.find(u
'\\x', StartPos
+ 1)
438 IncList
= gIncludePattern
.findall(Line
)
439 if len(IncList
) == 1:
440 for Dir
in [File
.Dir
] + self
.IncludePathList
:
441 IncFile
= PathClass(str(IncList
[0]), Dir
)
442 if os
.path
.isfile(IncFile
.Path
):
443 Lines
.extend(self
.PreProcess(IncFile
))
446 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, Message
="Cannot find include file", ExtraData
=str(IncList
[0]))
456 def LoadUniFile(self
, File
= None):
458 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
461 # Process special char in file
463 Lines
= self
.PreProcess(File
)
466 # Get Unicode Information
468 for IndexI
in range(len(Lines
)):
470 if (IndexI
+ 1) < len(Lines
):
471 SecondLine
= Lines
[IndexI
+ 1]
472 if (IndexI
+ 2) < len(Lines
):
473 ThirdLine
= Lines
[IndexI
+ 2]
476 # Get Language def information
478 if Line
.find(u
'#langdef ') >= 0:
479 self
.GetLangDef(File
, Line
)
486 # Get string def information format 1 as below
488 # #string MY_STRING_1
490 # My first English string line 1
491 # My first English string line 2
492 # #string MY_STRING_1
494 # Mi segunda secuencia 1
495 # Mi segunda secuencia 2
497 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
498 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
499 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
500 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
501 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
502 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
503 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
504 Value
= Value
+ Lines
[IndexJ
]
508 # Value = Value.replace(u'\r\n', u'')
509 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
510 # Check the string name
511 if not self
.IsCompatibleMode
and Name
!= '':
512 MatchString
= gIdentifierPattern
.match(Name
)
513 if MatchString
is None:
514 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name
, self
.File
))
515 self
.AddStringToList(Name
, Language
, Value
)
519 # Get string def information format 2 as below
521 # #string MY_STRING_1 #language eng "My first English string line 1"
522 # "My first English string line 2"
523 # #language spa "Mi segunda secuencia 1"
524 # "Mi segunda secuencia 2"
525 # #string MY_STRING_2 #language eng "My first English string line 1"
526 # "My first English string line 2"
527 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
528 # "Mi segunda secuencia 2"
530 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
532 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
533 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
536 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
537 StringItem
= StringItem
+ Lines
[IndexJ
]
538 elif Lines
[IndexJ
].count(u
'\"') >= 2:
539 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
540 self
.GetStringObject(StringItem
)
544 # Load multiple .uni files
546 def LoadUniFiles(self
, FileList
):
547 if len(FileList
) > 0:
548 for File
in FileList
:
549 self
.LoadUniFile(File
)
552 # Add a string to list
554 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
555 for LangNameItem
in self
.LanguageDef
:
556 if Language
== LangNameItem
[0]:
559 EdkLogger
.error('Unicode File Parser', FORMAT_NOT_SUPPORTED
, "The language '%s' for %s is not defined in Unicode file %s." \
560 % (Language
, Name
, self
.File
))
562 if Language
not in self
.OrderedStringList
:
563 self
.OrderedStringList
[Language
] = []
564 self
.OrderedStringDict
[Language
] = {}
567 if Name
in self
.OrderedStringDict
[Language
]:
569 if Value
is not None:
570 ItemIndexInList
= self
.OrderedStringDict
[Language
][Name
]
571 Item
= self
.OrderedStringList
[Language
][ItemIndexInList
]
572 Item
.UpdateValue(Value
)
573 Item
.UseOtherLangDef
= ''
576 Token
= len(self
.OrderedStringList
[Language
])
578 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
579 self
.OrderedStringDict
[Language
][Name
] = Token
580 for LangName
in self
.LanguageDef
:
582 # New STRING token will be added into all language string lists.
583 # so that the unique STRING identifier is reserved for all languages in the package list.
585 if LangName
[0] != Language
:
586 if UseOtherLangDef
!= '':
587 OtherLangDef
= UseOtherLangDef
589 OtherLangDef
= Language
590 self
.OrderedStringList
[LangName
[0]].append(StringDefClassObject(Name
, '', Referenced
, Token
, OtherLangDef
))
591 self
.OrderedStringDict
[LangName
[0]][Name
] = len(self
.OrderedStringList
[LangName
[0]]) - 1
593 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
594 self
.OrderedStringDict
[Language
][Name
] = Index
597 # Set the string as referenced
599 def SetStringReferenced(self
, Name
):
601 # String stoken are added in the same order in all language string lists.
602 # So, only update the status of string stoken in first language string list.
604 Lang
= self
.LanguageDef
[0][0]
605 if Name
in self
.OrderedStringDict
[Lang
]:
606 ItemIndexInList
= self
.OrderedStringDict
[Lang
][Name
]
607 Item
= self
.OrderedStringList
[Lang
][ItemIndexInList
]
608 Item
.Referenced
= True
611 # Search the string in language definition by Name
613 def FindStringValue(self
, Name
, Lang
):
614 if Name
in self
.OrderedStringDict
[Lang
]:
615 ItemIndexInList
= self
.OrderedStringDict
[Lang
][Name
]
616 return self
.OrderedStringList
[Lang
][ItemIndexInList
]
621 # Search the string in language definition by Token
623 def FindByToken(self
, Token
, Lang
):
624 for Item
in self
.OrderedStringList
[Lang
]:
625 if Item
.Token
== Token
:
631 # Re-order strings and re-generate tokens
635 # Retoken all language strings according to the status of string stoken in the first language string.
637 FirstLangName
= self
.LanguageDef
[0][0]
639 # Convert the OrderedStringList to be OrderedStringListByToken in order to faciliate future search by token
640 for LangNameItem
in self
.LanguageDef
:
641 self
.OrderedStringListByToken
[LangNameItem
[0]] = {}
644 # Use small token for all referred string stoken.
647 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
648 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
649 if FirstLangItem
.Referenced
== True:
650 for LangNameItem
in self
.LanguageDef
:
651 LangName
= LangNameItem
[0]
652 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
653 OtherLangItem
.Referenced
= True
654 OtherLangItem
.Token
= RefToken
655 self
.OrderedStringListByToken
[LangName
][OtherLangItem
.Token
] = OtherLangItem
656 RefToken
= RefToken
+ 1
659 # Use big token for all unreferred string stoken.
662 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
663 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
664 if FirstLangItem
.Referenced
== False:
665 for LangNameItem
in self
.LanguageDef
:
666 LangName
= LangNameItem
[0]
667 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
668 OtherLangItem
.Token
= RefToken
+ UnRefToken
669 self
.OrderedStringListByToken
[LangName
][OtherLangItem
.Token
] = OtherLangItem
670 UnRefToken
= UnRefToken
+ 1
673 # Show the instance itself
676 print(self
.LanguageDef
)
677 #print self.OrderedStringList
678 for Item
in self
.OrderedStringList
:
680 for Member
in self
.OrderedStringList
[Item
]:
683 # This acts like the main() function for the script, unless it is 'import'ed into another
685 if __name__
== '__main__':
686 EdkLogger
.Initialize()
687 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
688 a
= UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])