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 import Common
.LongFilePathOs
as os
, codecs
, re
21 import Common
.EdkLogger
as EdkLogger
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 *
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'
37 NARROW_CHAR
= u
'\uFFF0'
39 NON_BREAKING_CHAR
= u
'\uFFF2'
44 BACK_SLASH_PLACEHOLDER
= u
'\u0006'
46 gIncludePattern
= re
.compile("^#include +[\"<]+([^\"< >]+)[>\"]+$", re
.MULTILINE | re
.UNICODE
)
48 ## Convert a python unicode string to a normal string
50 # Convert a python unicode string to a normal string
51 # UniToStr(u'I am a string') is 'I am a string'
53 # @param Uni: The python unicode string
55 # @retval: The formatted normal string
58 return repr(Uni
)[2:-1]
60 ## Convert a unicode string to a Hex list
62 # Convert a unicode string to a Hex list
63 # UniToHexList('ABC') is ['0x41', '0x00', '0x42', '0x00', '0x43', '0x00']
65 # @param Uni: The python unicode string
67 # @retval List: The formatted hex list
69 def UniToHexList(Uni
):
72 Temp
= '%04X' % ord(Item
)
73 List
.append('0x' + Temp
[2:4])
74 List
.append('0x' + Temp
[0:2])
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'}
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
116 # @param LangName: Language codes read from .UNI file
118 # @retval LangName: Valid lanugage code in RFC 4646 format or None
120 def GetLanguageCode(LangName
, IsCompatibleMode
, File
):
121 length
= len(LangName
)
123 if length
== 3 and LangName
.isalpha():
124 TempLangName
= LangConvTable
.get(LangName
.lower())
125 if TempLangName
is not None:
129 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid ISO 639-2 language code : %s" % LangName
, File
)
131 if (LangName
[0] == 'X' or LangName
[0] == 'x') and LangName
[1] == '-':
134 if LangName
.isalpha():
137 if LangName
.isalpha() and LangConvTable
.get(LangName
.lower()) is None:
140 if LangName
[0:2].isalpha() and LangName
[2] == '-':
143 if LangName
[0:2].isalpha() and LangName
[2] == '-':
145 if LangName
[0:3].isalpha() and LangConvTable
.get(LangName
.lower()) is None and LangName
[3] == '-':
148 EdkLogger
.error("Unicode File Parser", FORMAT_INVALID
, "Invalid RFC 4646 language code : %s" % LangName
, File
)
152 # This is only a partial codec implementation. It only supports
153 # encoding, and is primarily used to check that all the characters are
156 class Ucs2Codec(codecs
.Codec
):
158 self
.__utf
16 = codecs
.lookup('utf-16')
160 def encode(self
, input, errors
='strict'):
162 CodePoint
= ord(Char
)
163 if CodePoint
>= 0xd800 and CodePoint
<= 0xdfff:
164 raise ValueError("Code Point is in range reserved for " +
165 "UTF-16 surrogate pairs")
166 elif CodePoint
> 0xffff:
167 raise ValueError("Code Point too large to encode in UCS-2")
168 return self
.__utf
16.encode(input)
170 TheUcs2Codec
= Ucs2Codec()
171 def Ucs2Search(name
):
173 return codecs
.CodecInfo(
175 encode
=TheUcs2Codec
.encode
,
176 decode
=TheUcs2Codec
.decode
)
179 codecs
.register(Ucs2Search
)
181 ## StringDefClassObject
183 # A structure for language definition
185 class StringDefClassObject(object):
186 def __init__(self
, Name
= None, Value
= None, Referenced
= False, Token
= None, UseOtherLangDef
= ''):
188 self
.StringNameByteList
= []
189 self
.StringValue
= ''
190 self
.StringValueByteList
= ''
192 self
.Referenced
= Referenced
193 self
.UseOtherLangDef
= UseOtherLangDef
197 self
.StringName
= Name
198 self
.StringNameByteList
= UniToHexList(Name
)
199 if Value
is not None:
200 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
201 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
202 self
.Length
= len(self
.StringValueByteList
)
203 if Token
is not None:
207 return repr(self
.StringName
) + ' ' + \
208 repr(self
.Token
) + ' ' + \
209 repr(self
.Referenced
) + ' ' + \
210 repr(self
.StringValue
) + ' ' + \
211 repr(self
.UseOtherLangDef
)
213 def UpdateValue(self
, Value
= None):
214 if Value
is not None:
215 self
.StringValue
= Value
+ u
'\x00' # Add a NULL at string tail
216 self
.StringValueByteList
= UniToHexList(self
.StringValue
)
217 self
.Length
= len(self
.StringValueByteList
)
219 def StripComments(Line
):
221 CommentPos
= Line
.find(Comment
)
222 while CommentPos
>= 0:
223 # if there are non matched quotes before the comment header
224 # then we are in the middle of a string
225 # but we need to ignore the escaped quotes and backslashes.
226 if ((Line
.count(u
'"', 0, CommentPos
) - Line
.count(u
'\\"', 0, CommentPos
)) & 1) == 1:
227 CommentPos
= Line
.find (Comment
, CommentPos
+ 1)
229 return Line
[:CommentPos
].strip()
232 ## UniFileClassObject
234 # A structure for .uni file definition
236 class UniFileClassObject(object):
237 def __init__(self
, FileList
= [], IsCompatibleMode
= False, IncludePathList
= []):
238 self
.FileList
= FileList
240 self
.LanguageDef
= [] #[ [u'LanguageIdentifier', u'PrintableName'], ... ]
241 self
.OrderedStringList
= {} #{ u'LanguageIdentifier' : [StringDefClassObject] }
242 self
.OrderedStringDict
= {} #{ u'LanguageIdentifier' : {StringName:(IndexInList)} }
243 self
.OrderedStringListByToken
= {} #{ u'LanguageIdentifier' : {Token: StringDefClassObject} }
244 self
.IsCompatibleMode
= IsCompatibleMode
245 self
.IncludePathList
= IncludePathList
246 if len(self
.FileList
) > 0:
247 self
.LoadUniFiles(FileList
)
250 # Get Language definition
252 def GetLangDef(self
, File
, Line
):
253 Lang
= distutils
.util
.split_quoted((Line
.split(u
"//")[0]))
256 FileIn
= self
.OpenUniFile(LongFilePath(File
.Path
))
257 except UnicodeError, X
:
258 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
);
260 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
);
261 LineNo
= GetLineNo(FileIn
, Line
, False)
262 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, "Wrong language definition",
263 ExtraData
="""%s\n\t*Correct format is like '#langdef en-US "English"'""" % Line
, File
=File
, Line
=LineNo
)
265 LangName
= GetLanguageCode(Lang
[1], self
.IsCompatibleMode
, self
.File
)
266 LangPrintName
= Lang
[2]
269 for Item
in self
.LanguageDef
:
270 if Item
[0] == LangName
:
275 self
.LanguageDef
.append([LangName
, LangPrintName
])
278 # Add language string
280 self
.AddStringToList(u
'$LANGUAGE_NAME', LangName
, LangName
, 0, True, Index
=0)
281 self
.AddStringToList(u
'$PRINTABLE_LANGUAGE_NAME', LangName
, LangPrintName
, 1, True, Index
=1)
285 # The found STRING tokens will be added into new language string list
286 # so that the unique STRING identifier is reserved for all languages in the package list.
288 FirstLangName
= self
.LanguageDef
[0][0]
289 if LangName
!= FirstLangName
:
290 for Index
in range (2, len (self
.OrderedStringList
[FirstLangName
])):
291 Item
= self
.OrderedStringList
[FirstLangName
][Index
]
292 if Item
.UseOtherLangDef
!= '':
293 OtherLang
= Item
.UseOtherLangDef
295 OtherLang
= FirstLangName
296 self
.OrderedStringList
[LangName
].append (StringDefClassObject(Item
.StringName
, '', Item
.Referenced
, Item
.Token
, OtherLang
))
297 self
.OrderedStringDict
[LangName
][Item
.StringName
] = len(self
.OrderedStringList
[LangName
]) - 1
300 def OpenUniFile(self
, FileName
):
305 UniFile
= open(FileName
, mode
='rb')
306 FileIn
= UniFile
.read()
309 EdkLogger
.Error("build", FILE_OPEN_FAILURE
, ExtraData
=File
)
312 # Detect Byte Order Mark at beginning of file. Default to UTF-8
315 if (FileIn
.startswith(codecs
.BOM_UTF16_BE
) or
316 FileIn
.startswith(codecs
.BOM_UTF16_LE
)):
319 self
.VerifyUcs2Data(FileIn
, FileName
, Encoding
)
321 UniFile
= StringIO
.StringIO(FileIn
)
322 Info
= codecs
.lookup(Encoding
)
323 (Reader
, Writer
) = (Info
.streamreader
, Info
.streamwriter
)
324 return codecs
.StreamReaderWriter(UniFile
, Reader
, Writer
)
326 def VerifyUcs2Data(self
, FileIn
, FileName
, Encoding
):
327 Ucs2Info
= codecs
.lookup('ucs-2')
332 FileDecoded
= codecs
.decode(FileIn
, Encoding
)
333 Ucs2Info
.encode(FileDecoded
)
335 UniFile
= StringIO
.StringIO(FileIn
)
336 Info
= codecs
.lookup(Encoding
)
337 (Reader
, Writer
) = (Info
.streamreader
, Info
.streamwriter
)
338 File
= codecs
.StreamReaderWriter(UniFile
, Reader
, Writer
)
340 ErrMsg
= lambda Encoding
, LineNumber
: \
341 '%s contains invalid %s characters on line %d.' % \
342 (FileName
, Encoding
, LineNumber
)
344 LineNumber
= LineNumber
+ 1
346 Line
= File
.readline()
348 EdkLogger
.error('Unicode File Parser', PARSER_ERROR
,
349 ErrMsg(Encoding
, LineNumber
))
350 Ucs2Info
.encode(Line
)
352 EdkLogger
.error('Unicode File Parser', PARSER_ERROR
,
353 ErrMsg('UCS-2', LineNumber
))
356 # Get String name and value
358 def GetStringObject(self
, Item
):
362 Name
= Item
.split()[1]
363 # Check the string name
365 MatchString
= gIdentifierPattern
.match(Name
)
366 if MatchString
is None:
367 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name
, self
.File
))
368 LanguageList
= Item
.split(u
'#language ')
369 for IndexI
in range(len(LanguageList
)):
373 Language
= LanguageList
[IndexI
].split()[0]
374 Value
= LanguageList
[IndexI
][LanguageList
[IndexI
].find(u
'\"') + len(u
'\"') : LanguageList
[IndexI
].rfind(u
'\"')] #.replace(u'\r\n', u'')
375 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
376 self
.AddStringToList(Name
, Language
, Value
)
379 # Get include file list and load them
381 def GetIncludeFile(self
, Item
, Dir
):
382 FileName
= Item
[Item
.find(u
'#include ') + len(u
'#include ') :Item
.find(u
' ', len(u
'#include '))][1:-1]
383 self
.LoadUniFile(FileName
)
386 # Pre-process before parse .uni file
388 def PreProcess(self
, File
):
389 if not os
.path
.exists(File
.Path
) or not os
.path
.isfile(File
.Path
):
390 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, ExtraData
=File
.Path
)
393 FileIn
= self
.OpenUniFile(LongFilePath(File
.Path
))
394 except UnicodeError, X
:
395 EdkLogger
.error("build", FILE_READ_FAILURE
, "File read failure: %s" % str(X
), ExtraData
=File
.Path
);
397 EdkLogger
.error("build", FILE_OPEN_FAILURE
, ExtraData
=File
.Path
);
401 # Use unique identifier
405 Line
= Line
.replace(u
'\\\\', BACK_SLASH_PLACEHOLDER
)
406 Line
= StripComments(Line
)
415 Line
= Line
.replace(u
'/langdef', u
'#langdef')
416 Line
= Line
.replace(u
'/string', u
'#string')
417 Line
= Line
.replace(u
'/language', u
'#language')
418 Line
= Line
.replace(u
'/include', u
'#include')
420 Line
= Line
.replace(UNICODE_WIDE_CHAR
, WIDE_CHAR
)
421 Line
= Line
.replace(UNICODE_NARROW_CHAR
, NARROW_CHAR
)
422 Line
= Line
.replace(UNICODE_NON_BREAKING_CHAR
, NON_BREAKING_CHAR
)
424 Line
= Line
.replace(u
'\\r\\n', CR
+ LF
)
425 Line
= Line
.replace(u
'\\n', CR
+ LF
)
426 Line
= Line
.replace(u
'\\r', CR
)
427 Line
= Line
.replace(u
'\\t', u
' ')
428 Line
= Line
.replace(u
'\t', u
' ')
429 Line
= Line
.replace(u
'\\"', u
'"')
430 Line
= Line
.replace(u
"\\'", u
"'")
431 Line
= Line
.replace(BACK_SLASH_PLACEHOLDER
, u
'\\')
433 StartPos
= Line
.find(u
'\\x')
434 while (StartPos
!= -1):
435 EndPos
= Line
.find(u
'\\', StartPos
+ 1, StartPos
+ 7)
436 if EndPos
!= -1 and EndPos
- StartPos
== 6 :
437 if g4HexChar
.match(Line
[StartPos
+ 2 : EndPos
], re
.UNICODE
):
438 EndStr
= Line
[EndPos
: ]
439 UniStr
= ('\u' + (Line
[StartPos
+ 2 : EndPos
])).decode('unicode_escape')
440 if EndStr
.startswith(u
'\\x') and len(EndStr
) >= 7:
441 if EndStr
[6] == u
'\\' and g4HexChar
.match(EndStr
[2 : 6], re
.UNICODE
):
442 Line
= Line
[0 : StartPos
] + UniStr
+ EndStr
444 Line
= Line
[0 : StartPos
] + UniStr
+ EndStr
[1:]
445 StartPos
= Line
.find(u
'\\x', StartPos
+ 1)
447 IncList
= gIncludePattern
.findall(Line
)
448 if len(IncList
) == 1:
449 for Dir
in [File
.Dir
] + self
.IncludePathList
:
450 IncFile
= PathClass(str(IncList
[0]), Dir
)
451 if os
.path
.isfile(IncFile
.Path
):
452 Lines
.extend(self
.PreProcess(IncFile
))
455 EdkLogger
.error("Unicode File Parser", FILE_NOT_FOUND
, Message
="Cannot find include file", ExtraData
=str(IncList
[0]))
465 def LoadUniFile(self
, File
= None):
467 EdkLogger
.error("Unicode File Parser", PARSER_ERROR
, 'No unicode file is given')
470 # Process special char in file
472 Lines
= self
.PreProcess(File
)
475 # Get Unicode Information
477 for IndexI
in range(len(Lines
)):
479 if (IndexI
+ 1) < len(Lines
):
480 SecondLine
= Lines
[IndexI
+ 1]
481 if (IndexI
+ 2) < len(Lines
):
482 ThirdLine
= Lines
[IndexI
+ 2]
485 # Get Language def information
487 if Line
.find(u
'#langdef ') >= 0:
488 self
.GetLangDef(File
, Line
)
495 # Get string def information format 1 as below
497 # #string MY_STRING_1
499 # My first English string line 1
500 # My first English string line 2
501 # #string MY_STRING_1
503 # Mi segunda secuencia 1
504 # Mi segunda secuencia 2
506 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') < 0 and \
507 SecondLine
.find(u
'#string ') < 0 and SecondLine
.find(u
'#language ') >= 0 and \
508 ThirdLine
.find(u
'#string ') < 0 and ThirdLine
.find(u
'#language ') < 0:
509 Name
= Line
[Line
.find(u
'#string ') + len(u
'#string ') : ].strip(' ')
510 Language
= SecondLine
[SecondLine
.find(u
'#language ') + len(u
'#language ') : ].strip(' ')
511 for IndexJ
in range(IndexI
+ 2, len(Lines
)):
512 if Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') < 0:
513 Value
= Value
+ Lines
[IndexJ
]
517 # Value = Value.replace(u'\r\n', u'')
518 Language
= GetLanguageCode(Language
, self
.IsCompatibleMode
, self
.File
)
519 # Check the string name
520 if not self
.IsCompatibleMode
and Name
!= '':
521 MatchString
= gIdentifierPattern
.match(Name
)
522 if MatchString
is None:
523 EdkLogger
.error('Unicode File Parser', FORMAT_INVALID
, 'The string token name %s defined in UNI file %s contains the invalid character.' % (Name
, self
.File
))
524 self
.AddStringToList(Name
, Language
, Value
)
528 # Get string def information format 2 as below
530 # #string MY_STRING_1 #language eng "My first English string line 1"
531 # "My first English string line 2"
532 # #language spa "Mi segunda secuencia 1"
533 # "Mi segunda secuencia 2"
534 # #string MY_STRING_2 #language eng "My first English string line 1"
535 # "My first English string line 2"
536 # #string MY_STRING_2 #language spa "Mi segunda secuencia 1"
537 # "Mi segunda secuencia 2"
539 if Line
.find(u
'#string ') >= 0 and Line
.find(u
'#language ') >= 0:
541 for IndexJ
in range(IndexI
+ 1, len(Lines
)):
542 if Lines
[IndexJ
].find(u
'#string ') >= 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
545 elif Lines
[IndexJ
].find(u
'#string ') < 0 and Lines
[IndexJ
].find(u
'#language ') >= 0:
546 StringItem
= StringItem
+ Lines
[IndexJ
]
547 elif Lines
[IndexJ
].count(u
'\"') >= 2:
548 StringItem
= StringItem
[ : StringItem
.rfind(u
'\"')] + Lines
[IndexJ
][Lines
[IndexJ
].find(u
'\"') + len(u
'\"') : ]
549 self
.GetStringObject(StringItem
)
553 # Load multiple .uni files
555 def LoadUniFiles(self
, FileList
):
556 if len(FileList
) > 0:
557 for File
in FileList
:
558 self
.LoadUniFile(File
)
561 # Add a string to list
563 def AddStringToList(self
, Name
, Language
, Value
, Token
= None, Referenced
= False, UseOtherLangDef
= '', Index
= -1):
564 for LangNameItem
in self
.LanguageDef
:
565 if Language
== LangNameItem
[0]:
568 EdkLogger
.error('Unicode File Parser', FORMAT_NOT_SUPPORTED
, "The language '%s' for %s is not defined in Unicode file %s." \
569 % (Language
, Name
, self
.File
))
571 if Language
not in self
.OrderedStringList
:
572 self
.OrderedStringList
[Language
] = []
573 self
.OrderedStringDict
[Language
] = {}
576 if Name
in self
.OrderedStringDict
[Language
]:
578 if Value
is not None:
579 ItemIndexInList
= self
.OrderedStringDict
[Language
][Name
]
580 Item
= self
.OrderedStringList
[Language
][ItemIndexInList
]
581 Item
.UpdateValue(Value
)
582 Item
.UseOtherLangDef
= ''
585 Token
= len(self
.OrderedStringList
[Language
])
587 self
.OrderedStringList
[Language
].append(StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
588 self
.OrderedStringDict
[Language
][Name
] = Token
589 for LangName
in self
.LanguageDef
:
591 # New STRING token will be added into all language string lists.
592 # so that the unique STRING identifier is reserved for all languages in the package list.
594 if LangName
[0] != Language
:
595 if UseOtherLangDef
!= '':
596 OtherLangDef
= UseOtherLangDef
598 OtherLangDef
= Language
599 self
.OrderedStringList
[LangName
[0]].append(StringDefClassObject(Name
, '', Referenced
, Token
, OtherLangDef
))
600 self
.OrderedStringDict
[LangName
[0]][Name
] = len(self
.OrderedStringList
[LangName
[0]]) - 1
602 self
.OrderedStringList
[Language
].insert(Index
, StringDefClassObject(Name
, Value
, Referenced
, Token
, UseOtherLangDef
))
603 self
.OrderedStringDict
[Language
][Name
] = Index
606 # Set the string as referenced
608 def SetStringReferenced(self
, Name
):
610 # String stoken are added in the same order in all language string lists.
611 # So, only update the status of string stoken in first language string list.
613 Lang
= self
.LanguageDef
[0][0]
614 if Name
in self
.OrderedStringDict
[Lang
]:
615 ItemIndexInList
= self
.OrderedStringDict
[Lang
][Name
]
616 Item
= self
.OrderedStringList
[Lang
][ItemIndexInList
]
617 Item
.Referenced
= True
620 # Search the string in language definition by Name
622 def FindStringValue(self
, Name
, Lang
):
623 if Name
in self
.OrderedStringDict
[Lang
]:
624 ItemIndexInList
= self
.OrderedStringDict
[Lang
][Name
]
625 return self
.OrderedStringList
[Lang
][ItemIndexInList
]
630 # Search the string in language definition by Token
632 def FindByToken(self
, Token
, Lang
):
633 for Item
in self
.OrderedStringList
[Lang
]:
634 if Item
.Token
== Token
:
640 # Re-order strings and re-generate tokens
644 # Retoken all language strings according to the status of string stoken in the first language string.
646 FirstLangName
= self
.LanguageDef
[0][0]
648 # Convert the OrderedStringList to be OrderedStringListByToken in order to faciliate future search by token
649 for LangNameItem
in self
.LanguageDef
:
650 self
.OrderedStringListByToken
[LangNameItem
[0]] = {}
653 # Use small token for all referred string stoken.
656 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
657 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
658 if FirstLangItem
.Referenced
== True:
659 for LangNameItem
in self
.LanguageDef
:
660 LangName
= LangNameItem
[0]
661 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
662 OtherLangItem
.Referenced
= True
663 OtherLangItem
.Token
= RefToken
664 self
.OrderedStringListByToken
[LangName
][OtherLangItem
.Token
] = OtherLangItem
665 RefToken
= RefToken
+ 1
668 # Use big token for all unreferred string stoken.
671 for Index
in range (0, len (self
.OrderedStringList
[FirstLangName
])):
672 FirstLangItem
= self
.OrderedStringList
[FirstLangName
][Index
]
673 if FirstLangItem
.Referenced
== False:
674 for LangNameItem
in self
.LanguageDef
:
675 LangName
= LangNameItem
[0]
676 OtherLangItem
= self
.OrderedStringList
[LangName
][Index
]
677 OtherLangItem
.Token
= RefToken
+ UnRefToken
678 self
.OrderedStringListByToken
[LangName
][OtherLangItem
.Token
] = OtherLangItem
679 UnRefToken
= UnRefToken
+ 1
682 # Show the instance itself
685 print self
.LanguageDef
686 #print self.OrderedStringList
687 for Item
in self
.OrderedStringList
:
689 for Member
in self
.OrderedStringList
[Item
]:
692 # This acts like the main() function for the script, unless it is 'import'ed into another
694 if __name__
== '__main__':
695 EdkLogger
.Initialize()
696 EdkLogger
.SetLevel(EdkLogger
.DEBUG_0
)
697 a
= UniFileClassObject([PathClass("C:\\Edk\\Strings.uni"), PathClass("C:\\Edk\\Strings2.uni")])