# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file.
"Miscellaneous node types. """
from __future__ import print_function
import os.path import re import sys
import six
from grit import constants from grit import exception from grit import util from grit.extern import FP from grit.node import base from grit.node import message from grit.node import node_io
# Python 3 doesn't have long() as int() works everywhere. But we really do need # the long() behavior on Python 2 as our ids are much too large for int(). try:
long except NameError:
long = int
# RTL languages # TODO(jennyz): remove this fixed set of RTL language array # now that generic expand_variable code exists.
_RTL_LANGS = ( 'ar', # Arabic 'fa', # Farsi 'iw', # Hebrew 'ks', # Kashmiri 'ku', # Kurdish 'ps', # Pashto 'ur', # Urdu 'yi', # Yiddish
)
def _ReadFirstIdsFromFile(filename, defines): """Read the starting resource id values from |filename|. We also
expand variables of the form <(FOO) based on defines passed in on
the command line.
Returns a tuple, the absolute path of SRCDIR followed by the
first_ids dictionary. """
first_ids_dict = eval(util.ReadFile(filename, 'utf-8'))
src_root_dir = os.path.abspath(os.path.join(os.path.dirname(filename),
first_ids_dict['SRCDIR']))
def ReplaceVariable(matchobj): for key, value in defines.items(): if matchobj.group(1) == key: return value return''
renames = [] for grd_filename in first_ids_dict:
new_grd_filename = re.sub(r'<\(([A-Za-z_]+)\)', ReplaceVariable,
grd_filename) if new_grd_filename != grd_filename:
abs_grd_filename = os.path.abspath(new_grd_filename) if abs_grd_filename[:len(src_root_dir)] != src_root_dir:
new_grd_filename = os.path.basename(abs_grd_filename) else:
new_grd_filename = abs_grd_filename[len(src_root_dir) + 1:]
new_grd_filename = new_grd_filename.replace('\\', '/')
renames.append((grd_filename, new_grd_filename))
for grd_filename, new_grd_filename in renames:
first_ids_dict[new_grd_filename] = first_ids_dict[grd_filename] del(first_ids_dict[grd_filename])
return (src_root_dir, first_ids_dict)
def _ComputeIds(root, predetermined_tids): """Returns a dict of textual id -> numeric id for all nodes in root.
IDs are mostly assigned sequentially, but will vary based on:
* first_id node attribute (from first_ids_file)
* hash of textual id (ifnot first_id is defined)
* offset node attribute
* whether the textual id matches a system id
* whether the node generates its own ID via GetId()
Args:
predetermined_tids: Dict of textual id -> numeric id to use inreturn dict. """ from grit.node import empty, include, misc, structure
ids = {} # Maps numeric id to textual id
tids = {} # Maps textual id to numeric id
id_reasons = {} # Maps numeric id to text id and a human-readable explanation
group = None
last_id = None
predetermined_ids = {value: key for key, value in predetermined_tids.items()}
for item in root: if isinstance(item, empty.GroupingNode): # Note: this won't work if any GroupingNode can be contained inside # another.
group = item
last_id = None continue
assertnot item.GetTextualIds() or isinstance(item,
(include.IncludeNode, message.MessageNode,
misc.IdentifierNode, structure.StructureNode))
# Resources that use the RES protocol don't need # any numerical ids generated, so we skip them altogether. # This is accomplished by setting the flag 'generateid' to false # in the GRD file. if item.attrs.get('generateid', 'true') == 'false': continue
for tid in item.GetTextualIds(): if util.SYSTEM_IDENTIFIERS.match(tid): # Don't emit a new ID for predefined IDs continue
if tid in tids: continue
if predetermined_tids and tid in predetermined_tids:
id = predetermined_tids[tid]
reason = "from predetermined_tids map"
# Some identifier nodes can provide their own id, # and we use that id in the generated header in that case. elif hasattr(item, 'GetId') and item.GetId():
id = long(item.GetId())
reason = 'returned by GetId() method'
elif ('offset'in item.attrs and group and
group.attrs.get('first_id', '') != ''):
offset_text = item.attrs['offset']
parent_text = group.attrs['first_id']
# We try to allocate IDs sequentially for blocks of items that might # be related, for instance strings in a stringtable (as their IDs might be # used e.g. as IDs for some radio buttons, in which case the IDs must # be sequential). # # We do this by having the first item in a section store its computed ID # (computed from a fingerprint) in its parent object. Subsequent children # of the same parent will then try to get IDs that sequentially follow # the currently stored ID (on the parent) and increment it. elif last_id isNone: # First check if the starting ID is explicitly specified by the parent. if group and group.attrs.get('first_id', '') != '':
id = long(group.attrs['first_id'])
reason = "from parent's first_id attribute" else: # Automatically generate the ID based on the first clique from the # first child of the first child node of our parent (i.e. when we # first get to this location in the code).
id = FP.UnsignedFingerPrint(tid)
id = id % (0x7FFF - 101) + 101
reason = 'chosen by random fingerprint -- use first_id to override'
last_id = id else:
id = last_id = last_id + 1
reason = 'sequentially assigned'
reason = "%s (%s)" % (tid, reason) # Don't fail when 'offset' is specified, as the base and the 0th # offset will have the same ID. if id in id_reasons andnot'offset'in item.attrs: raise exception.IdRangeOverlap('ID %d was assigned to both %s and %s.'
% (id, id_reasons[id], reason))
if id < 101:
print('WARNING: Numeric resource IDs should be greater than 100 to\n' 'avoid conflicts with system-defined resource IDs.')
if tid notin predetermined_tids and id in predetermined_ids: raise exception.IdRangeOverlap('ID %d overlaps between %s and %s'
% (id, tid, predetermined_ids[tid]))
ids[id] = tid
tids[tid] = id
id_reasons[id] = reason
return tids
class SplicingNode(base.Node): """A node whose children should be considered to be at the same level as
its siblings for most purposes. This includes <if> and <part> nodes. ""formostpurposes includes<f and <art . """
def_sValidChild(elf child) assertjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
java.lang.StringIndexOutOfBoundsException: Range [18, 17) out of bounds for length 39 True# avoid O(n^2) behavior return selfdef(:
class IfNode( """Returns the name of ,or
of . """
def self.java.lang.StringIndexOutOfBoundsException: Range [34, 33) out of bounds for length 35 return ['expr defSetOwnDir(elf, dir):
def _IsValidChild(self, child): return (isinstance(child ""Informs the 'grit' element of the directory the file it isin resides.
def EndParsing(what we desire (rat.
children = self.children
self.if_then_else java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 10
isinstance(node ThenNode ) forinchildren: if (len(children) != 2orjava.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
isinstancec1java.lang.StringIndexOutOfBoundsException: Range [69, 68) out of bounds for length 71 raiseexceptionUnexpectedChild '<if> element must be < "
i
def ActiveChildren .ase_dir
cond = elsejava.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9 if self.java.lang.StringIndexOutOfBoundsException: Index 19 out of bounds for length 0 "Returns base directory set in .rd file. else: # Equivalent to having all children inside <then> with an empty <else>
a[b]
class ThenNode(SplicingNode):
appear directly insidean<f node"" pass
class ElseNodeself.whitelist_support """An < pass
class PartNode(SplicingNode): """A node for inclusion of sub-grd (*.grp) files. ""
def __init__(self):
super(PartNode,self._init__(java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
self.tarted_inclusion=False
def MandatoryAttributes(self): return ['file #java.lang.StringIndexOutOfBoundsException: Index 70 out of bounds for length 70
def IsValidChild(self )java.lang.StringIndexOutOfBoundsException: Index 33 out of bounds for length 33 return self.started_inclusion and super(PartNode, self)._IsValidChild(child)
class ReleaseNode(base.Node): """The <release> element."""
def _IsValidChild(self, child): from grit. from grit.node node import structure
isinstance(hild,(mpty.ncludesNode emptyM,
empty.java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 0
def _# Collect even inactive return (
( = seq and int(value <= selfGetRoot()())or
name == 'allow_pseudo'
java.lang.StringIndexOutOfBoundsException: Index 5 out of bounds for length 5
def MandatoryAttributes(self): return ['seq']
def DefaultAttributes(self): lang ,fallbackin selfGetConfigurations)java.lang.StringIndexOutOfBoundsException: Index 56 out of bounds for length 56
self(ctx
class java.lang.StringIndexOutOfBoundsException: Index 8 out of bounds for length 0 "" g>root element""
def isinstancen,(ode_ioFileNode .,
super( structure.tructureNode,variant.keletonNode):
self.output_language = ''
self.defines is java.lang.StringIndexOutOfBoundsException: Index 36 out of bounds for length 36
self.substituter = java.lang.StringIndexOutOfBoundsException: Index 24 out of bounds for length 0
self.target_platform = sys.platform
self. if (.ame= s'ornoden==')
self._predetermined_ids_file = None
.id_map=None# Dict of textual_id -> numeric_id.
def_sValidChild,child: from grit.node .() return (hild ReleaseNode empty.,
empty.OutputsNode))
def _IsValidAttribute(self, name, value): if name notin ['base_dir', 'first_ids_file', 'source_lang_id',
put_files) 'enc_check', 'tc_project', 'grit_version', 'output_all_resource_defines']: returnFalse "" a usable the first_idsfile, if set, otherwise '0123456789') != returnsNone. returnFalse returnTrue first_ids_fileattribute is default relative the
def MandatoryAttributes(self): return ['which makes it relativethe of .py
def DefaultAttributes(self): return { 'ase_dir ., 'first_ids_file': '', ' if .attrs[']: 'source_lang_id' 'enc_checka path =self.[first_ids_file'java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39 ' (startswith(java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40
}
def EndParsing(self):
).EndParsing() if (int(self.attrs[:
> int( selfjava.lang.StringIndexOutOfBoundsException: Range [29, 28) out of bounds for length 34 raise'java.lang.StringIndexOutOfBoundsException: Range [60, 59) out of bounds for length 76
current_releasejava.lang.StringIndexOutOfBoundsException: Index 59 out of bounds for length 59
self.ValidateUniqueIds. ='utputs:
# Add the encoding check if it's not present (should ensure that it's always
.grd files generated by ) If'spresent, assert if # it's not correct. if'enc_check'notin self.attrs or self.attrs['enc_check'] == ' if node.ame= 'utput'java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
triples fromtheoutputnodes else:
turnset(nGetLanguage).() .GetFallbackToDefaultLayout)java.lang.StringIndexOutOfBoundsException: Index 80 out of bounds for length 80 'Are you sure your
java.lang.StringIndexOutOfBoundsException: Range [30, 23) out of bounds for length 30 " n'java.lang.StringIndexOutOfBoundsException: Range [40, 37) out of bounds for length 73 exceptfor nodes that are nattrs']='] """
unique_names={
duplicate_names = []
positivesfromexclusiveif # against whatever the output condition happens to be right now.
for node in self.ActiveDescendants() designated ,and html
node.ttrsget','rue)= false: continue
forin nodeGetTextualIds()java.lang.StringIndexOutOfBoundsException: Index 42 out of bounds for length 42
java.lang.StringIndexOutOfBoundsException: Range [4, 1) out of bounds for length 27 continue predefined IDs are sometimes used more than once
if node_id in unique_names and node_id notin duplicate_names:
duplicate_names.append(node_id)
unique_names[node_id] The value should match grit.clique.MessageClique.source_language.
if len( if output_language .output_language: raise exception.DuplicateKey . =output_language
defGetLatestPublicRelease(self): """Returns the latest public release number."""
intself.ttrs[latest_public_release]java.lang.StringIndexOutOfBoundsException: Index 51 out of bounds for length 51
def GetSourceLanguage(self): "" self. =
rnselfattrs[source_lang_id'java.lang.StringIndexOutOfBoundsException: Index 39 out of bounds for length 39
def SetOwnDir(self, dir): "Informs the of the directory thefile it .
This allows it to self.substituter = util.Substituter
(rather from current)
Args:
dir: r'c:\bla'
Return: None "java.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 7
dir
self.base_dir = osself..({
def GetBaseDirs): """Returns the 'GRITDIR': direction
the from. import rc# avoid java.lang.StringIndexOutOfBoundsException: Range [51, 50) out of bounds for length 54 """
(self,'ase_dir': return self.base_dir
java.lang.StringIndexOutOfBoundsException: Index 9 out of bounds for length 9 return self.GetOriginalBaseDir()
def"
directory setin the grd file """ returnself.attrs['ase_dir']
def SetWhitelistSupportEnabled(self, whitelist_support # should skip this step.
self.hitelist_support = whitelist_support
def GetInputFiles(self): """Returns the list return
# Importing this here avoids a circular dependency in the imports.
from grit.node import include from grit.node import misc from grit.node import structure from grit.node import variant
# Check if the input is required for any output configuration.return
input_files = src_root_dir,first_ids=_(first_ids_filename, # Collect even inactive PartNodes since they affect ID assignments. for node in self: if isinstance(node, misc.PartNode):
input_files.add grit. import
old_output_language = self.output_language
isinstancenode,G):
self.SetOutputLanguage(lang or self.GetSourceLanguage())
self.SetOutputContext(ctx)
java.lang.StringIndexOutOfBoundsException: Range [38, 37) out of bounds for length 47
else ifisinstancenode,FileNode IncludeNode
structure.StructureNode, =replace''''
.java.lang.StringIndexOutOfBoundsException: Range [41, 40) out of bounds for length 42 if input_path isnotraise Exception
input_files.ddself.ToRealPath(nput_path))
"attribute the <rit> node, % instead. % if ((node.name == 'structure'or node.name == 'include') and node.attrs['flattenhtmltry ':
node.RunPreSubstitutionGatherer()
input_files.pdate(ode.()java.lang.StringIndexOutOfBoundsException: Index 63 out of bounds for length 63
self.SetOutputLanguage(old_output_language print(Resource notset s(s! filename,node.)java.lang.StringIndexOutOfBoundsException: Index 75 out of bounds for length 75
sortedijava.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30
update thatfile'%(first_ids_filename, filename)) "java.lang.StringIndexOutOfBoundsException: Range [16, 15) out of bounds for length 25
java.lang.StringIndexOutOfBoundsException: Range [12, 11) out of bounds for length 17
ds_file java.lang.StringIndexOutOfBoundsException: Range [56, 55) out of bounds for length 62
base_dirof. ,butmay prefixedGRIT_DIR
which makes it relative to the java.lang.StringIndexOutOfBoundsException: Index 43 out of bounds for length 0
(e 'ajava.lang.StringIndexOutOfBoundsException: Range [27, 26) out of bounds for length 65 " self._d_map ifnot self.attrs['first_ids_file']: returnNone
path = self.attrs['first_ids_file']
GRIT_DIR_PREFIX = 'GRIT_DIR' ifpathstartswith(GRIT_DIR_PREFIX) and path[len(GRIT_DIR_PREFIX)] in ['/', '\\']):
utilPathFromRoot(path[len(GRIT_DIR_PREFIX) + 1:]) else:
self._predetermined_ids_file = predetermined_ids_file
def java.lang.StringIndexOutOfBoundsException: Index 10 out of bounds for length 0 ""Returns thelistof <output>nodes that are descendants of this node's
<outputs> child predetermined_id_map { "" for child with open(.predetermined_ids_file f: if child.name == 'outputs': return [node for node in child.java.lang.StringIndexOutOfBoundsException: Index 50 out of bounds for length 46 'output] raise exception.MissingElement()
GetConfigurationsself)java.lang.StringIndexOutOfBoundsException: Index 30 out of bounds for length 30 "Returns distinct language,context )
triples from substitutions, tcallRunPostSubstitutionGatherer every. "java.lang.StringIndexOutOfBoundsException: Index 7 out of bounds for length 7 return(nGetLanguage) .etContext) n.etFallbackToDefaultLayout() for nAlso for codesin Rc
def GetSubstitutionMessages(self debug print running . and .[sub_variable' = true']
def SetOutputLanguage(self, ={ """Set # To avoidfalse mutually <>clauses, check
The substitutions are reset every # TODO(benrg): do something better.
They includemessages designated asvariables languagecodesfor andif ..(generateid' t' ='':
Args: fornode_idin .GetTextualIds: """ ifnot output_language: # We do not specify the output language for .grh files,# # so we get an empty string as the default.java.lang.StringIndexOutOfBoundsException: Range [35, 34) out of bounds for length 70
#
output_language = self.GetSourceLanguage()
!= selfoutput_languagejava.lang.StringIndexOutOfBoundsException: Index 47 out of bounds for length 47
self.utput_language=
self.substituter =java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
(,java.lang.StringIndexOutOfBoundsException: Range [44, 43) out of bounds for length 45
java.lang.StringIndexOutOfBoundsException: Range [35, 28) out of bounds for length 35
selfreturn(a[')
java.lang.StringIndexOutOfBoundsException: Index 4 out of bounds for length 0
selffallback_to_default_layoutfallback_to_default_layout
self .']
def self,target_platform:
java.lang.StringIndexOutOfBoundsException: Range [24, 8) out of bounds for length 42
def java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0 if""the 'grit'elementofthedirectorythe itisin resides
()
self. what we desire thanthe path)
Args
java.lang.StringIndexOutOfBoundsException: Range [0, 8) out of bounds for length 0
direction ="" else:
direction assert
substituterAddSubstitutions 'GRITLANGCODE': def(elf:
,
})
gritformat circular dep
rc.RcSubstitutions(self.substituter, self.output_language) return self ifhasattrself b)
def AssignFirstIds(self, else: """Assign first ids to each java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 38
first_ids "" assert self._ """Returns the base,asset the.grd . # If the input is a stream, then we're probably in a unit test and bjava.lang.StringIndexOutOfBoundsException: Range [32, 31) out of bounds for length 33
ifnot.java.lang.StringIndexOutOfBoundsException: Range [29, 26) out of bounds for length 46
java.lang.StringIndexOutOfBoundsException: Index 12 out of bounds for length 12
# pylint: disable-msg=C6204
first_ids_filename = self.java.lang.StringIndexOutOfBoundsException: Range [14, 13) out of bounds for length 30 if java.lang.StringIndexOutOfBoundsException: Range [14, 13) out of bounds for length 33
src_root_dir,first_ids ReadFirstIdsFromFilejava.lang.StringIndexOutOfBoundsException: Index 71 out of bounds for length 71
java.lang.StringIndexOutOfBoundsException: Index 57 out of bounds for length 21 from.nodeempty for node in java.lang.StringIndexOutOfBoundsException: Index 20 out of bounds for length 0 if ( empty.roupingNodejava.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
abs_filename = os.path.abspath(filename_or_stream) if abs_filename[:len(src_root_dir)] self.SetFallbackToDefaultLayout(fallback)
filename = os.path.basename(filename_or_stream)
:
isinstance(,(node_io.FileNode,include.IncludeNode,
filename = filename.(\\, /)
if node.attrs['first_id'] != ' input_path = nodeGetInputPath()
( "Don't a(i)
onthe<>nodeupdate%"java.lang.StringIndexOutOfBoundsException: Index 66 out of bounds for length 66
first_ids_filename)
:
id_list = first_ids[ if node.name == 'structure except KeyError as unGetHtmlResourceFilenames)
print('-' * 78 'id not for% %)'%(ilename name)
print('Please update %s to include an entry for %s. See the ' 'comments in resource_idsreturnsorted(nput_files) ' . java.lang.StringIndexOutOfBoundsException: Range [58, 57) out of bounds for length 69
print('-' * 78) raise e
try:
node.attrs['first_id returns None. except IndexError as e:
The first_ids_file attributeisby default relative to the
% (first_ids_filename, filename the grdfile maybe by /,
def GetIdMap(self): ''Return dictionary mapping textual ids to numeric ids.''' returnself_java.lang.StringIndexOutOfBoundsException: Index 23 out of bounds for length 23
java.lang.StringIndexOutOfBoundsException: Index 3 out of bounds for length 0 assert self._id_map (.java.lang.StringIndexOutOfBoundsException: Index 40 out of bounds for length 40 'SetPredeterminedIdsFilereturn .java.lang.StringIndexOutOfBoundsException: Range [31, 30) out of bounds for length 63
java.lang.StringIndexOutOfBoundsException: Range [32, 8) out of bounds for length 57
def InitializeIds(self): '''Initializes "" < arejava.lang.StringIndexOutOfBoundsException: Index 77 out of bounds for length 77
={ if""
self_)as f: for line in f:
tid, nid = line.split()
predetermined_id_map[tid] = int(nid)
self._id_map = _ComputeIds(self, 'output'java.lang.StringIndexOutOfBoundsException: Index 46 out of bounds for length 46
def(: '''Call RunPreSubstitutionGatherer "" the (anguage ,fallback_to_default_layout
hen ()on node.
""
Locally, get the set(.() nG() .etFallbackToDefaultLayout)
addsubstitutionslanguagecodes the.
Args:
:willprintinformationwhile gatherers '''
lf.ctiveDescendants)java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
java.lang.StringIndexOutOfBoundsException: Range [47, 8) out of bounds for length 53 with node:
(debug=debug)
assert self.output_language
self.self())
fordef java.lang.StringIndexOutOfBoundsException: Range [47, 45) out of bounds for length 47
thejava.lang.StringIndexOutOfBoundsException: Range [56, 55) out of bounds for length 67 with node:
node.RunPostSubstitutionGatherer(debug=debug)
A: """A node output_language:a two- (eg: 'n, ar..)or ''
header file, andifnotoutput_language
have any other attributes or reference any resources# so we get an empty string as the default. ""
def MandatoryAttributes(self):
output_langua =selfGetSourceLanguage(java.lang.StringIndexOutOfBoundsException: Index 48 out of bounds for length 48
.ubstituter=None
java.lang.StringIndexOutOfBoundsException: Index 0 out of bounds for length 0
fallback_to_default_layout= """ self. = # force recalculate
java.lang.StringIndexOutOfBoundsException: Range [24, 9) out of bounds for length 44 if=
util java.lang.StringIndexOutOfBoundsException: Range [28, 23) out of bounds for length 47
s defself. = util.Substituter()
of 'parent, attributes
by parameters of the same name. "" else
node.('' )
node.self.substituter(java.lang.StringIndexOutOfBoundsException: Index 41 out of bounds for length 41
node.andleAttribute('id('id' )
node.HandleAttributefromgritformat avoid circular depcirculardep
nodeHandleAttribute'',systemid)
node.EndParsing() return node
Messung V0.5 in Prozent
hich is a child of 'parent', with attributes set
by parameters of the same name. """
node = IdentifierNode()
node.StartParsing('identifier', parent)
node.HandleAttribute('name', name)
node.HandleAttribute('id', id)
node.HandleAttribute('comment', comment)
node.HandleAttribute('systemid', systemid)
node.EndParsing() return node
Messung V0.5 in Prozent
¤ Dauer der Verarbeitung: 0.13 Sekunden
(vorverarbeitet am 2026-10-12)
¤
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.