/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context"></param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var scaler = (CanvasScaler)component; scaler.uiScaleMode = (CanvasScaler.ScaleMode)reader.GetIntAttribute(AttributeUIScaleMode); switch (scaler.uiScaleMode) { case CanvasScaler.ScaleMode.ConstantPixelSize: scaler.scaleFactor = reader.GetFloatAttribute(AttibuteScaleFactor); scaler.referencePixelsPerUnit = reader.GetFloatAttribute(AttributeReferencePixelsPerUnit); break; case CanvasScaler.ScaleMode.ScaleWithScreenSize: scaler.referenceResolution = reader.GetVector2Attribute(AttributeReferenceResolution); scaler.matchWidthOrHeight = reader.GetFloatAttribute(AttributeMatchWidthOrHeight); scaler.referencePixelsPerUnit = reader.GetFloatAttribute(AttributeReferencePixelsPerUnit); break; case CanvasScaler.ScaleMode.ConstantPhysicalSize: scaler.physicalUnit = (CanvasScaler.Unit)reader.GetIntAttribute(AttributeReferenceResolution); scaler.fallbackScreenDPI = reader.GetFloatAttribute(AttributeFallbackScreenDPI); scaler.defaultSpriteDPI = reader.GetFloatAttribute(AttributeDefaultSpriteDPI); break; default: Debug.LogWarning("Unsupport scale mode " + scaler.uiScaleMode); break; } }
private const string GROUP_NAME_TRANSITION = "transition"; // Not L10N public override void ReadXml(XmlReader reader) { base.ReadXml(reader); reader.ReadStartElement(); // Consume tag List <Color> groupColors = new List <Color>(); List <Color> libraryColors = new List <Color>(); while (reader.IsStartElement(EL.color)) { string groupName = reader.GetAttribute(ATTR.type); Color color = Color.FromArgb(reader.GetIntAttribute(ATTR.red), reader.GetIntAttribute(ATTR.green), reader.GetIntAttribute(ATTR.blue)); if (groupName == GROUP_NAME_PRECURSOR) { groupColors.Add(color); } else if (groupName == GROUP_NAME_TRANSITION) { libraryColors.Add(color); } reader.Read(); // Consume tag } PrecursorColors = ImmutableList.ValueOf(groupColors); TransitionColors = ImmutableList.ValueOf(libraryColors); reader.ReadEndElement(); // Consume end tag }
/// <summary> /// 从<see cref="XmlReader"/>中读取游戏对象。 /// </summary> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> /// <param name="forceInactive">是否强制将游戏对象设为非激活状态,通常反序列化根游戏对象时需要设置此值,以防其上面的组件的Awake方法自动执行</param> /// <returns>游戏对象</returns> public static GameObject GetGameObject(this XmlReader reader, DeserializationContext context, bool forceInactive = false) { var gameObject = new GameObject { name = reader.GetAttribute("Name"), layer = reader.GetIntAttribute("Layer"), }; if (forceInactive) { gameObject.SetActive(false); } var instanceId = reader.GetIntAttribute("InstanceId"); context.RegisterReference(instanceId, gameObject); var subReader = reader.ReadSubtree(); subReader.Read(); subReader.Read(); //Components if (subReader.IsStartElement("Components")) { var innerReader = reader.ReadSubtree(); innerReader.Read(); if (innerReader.Read()) { while (innerReader.NodeType != XmlNodeType.EndElement) { readComponent(innerReader, gameObject, context); } } subReader.Skip(); } //Children if (subReader.IsStartElement("Children")) { var innerReader = reader.ReadSubtree(); innerReader.Read(); if (innerReader.Read()) { while (innerReader.NodeType != XmlNodeType.EndElement) { var childObject = reader.GetGameObject(context); childObject.transform.SetParent(gameObject.transform, false); } } subReader.Skip(); } reader.Skip(); return(gameObject); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context"></param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var rayCaster = (GraphicRaycaster)component; rayCaster.ignoreReversedGraphics = reader.GetBoolAttribute(AttributeIgnoreReversedGraphics); rayCaster.blockingObjects = (GraphicRaycaster.BlockingObjects)reader.GetIntAttribute(AttributeBlockingObjects); //被保护的字段,只能通过反射设置 var mask = (LayerMask)reader.GetIntAttribute(AttributeBlockingMask); getBlockMaskFieldInfo().SetValue(rayCaster, mask); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var selectable = (Selectable)component; selectable.interactable = reader.GetBoolAttribute(AttributeInteractable); selectable.transition = (Selectable.Transition)reader.GetIntAttribute(AttributeTransition); switch (selectable.transition) { case Selectable.Transition.None: break; case Selectable.Transition.ColorTint: var graphicInstanceId = reader.GetIntAttribute(AttributeTargetGraphic); context.AddReference <Graphic>(graphicInstanceId, graphic => { selectable.targetGraphic = graphic; }); var subReader = reader.ReadSubtree(); subReader.Read(); if (subReader.Read()) { selectable.colors = subReader.GetColorBlockElement(ElementColors); } break; case Selectable.Transition.SpriteSwap: var graphicInstanceId2 = reader.GetIntAttribute(AttributeTargetGraphic); context.AddReference <Graphic>(graphicInstanceId2, graphic => { selectable.targetGraphic = graphic; }); var subReader2 = reader.ReadSubtree(); subReader2.Read(); if (subReader2.Read()) { reader.GetSpriteStateElement(ElementSpriteState, spriteState => { selectable.spriteState = spriteState; }, context); reader.Skip(); } break; case Selectable.Transition.Animation: var subReader3 = reader.ReadSubtree(); subReader3.Read(); if (subReader3.Read()) { selectable.animationTriggers = reader.GetAnimationTriggers(ElementAnimationTriggers); reader.Skip(); } break; default: Debug.LogWarning("Unsupported transition mode " + selectable.transition); break; } reader.GetNavigationElement(ElementNavigation, navigation => { selectable.navigation = navigation; }, context); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { base.Deserialize(component, reader.ReadSubtree(), context); var inputField = (InputField)component; var textComponentId = reader.GetIntAttribute(AttributeTextComponent); if (textComponentId != 0) { context.AddReference <Text>(textComponentId, text => { inputField.textComponent = text; }); } inputField.characterLimit = reader.GetIntAttribute(AttributeCharacterLimit); inputField.contentType = (InputField.ContentType)reader.GetIntAttribute(AttributeContentType); inputField.lineType = (InputField.LineType)reader.GetIntAttribute(AttributeLineType); inputField.inputType = (InputField.InputType)reader.GetIntAttribute(AttributeInputType); inputField.keyboardType = (TouchScreenKeyboardType)reader.GetIntAttribute(AttributeKeyboardType); inputField.characterValidation = (InputField.CharacterValidation)reader.GetIntAttribute(AttributeCharacterValidation); var placeholderId = reader.GetIntAttribute(AttributePlaceholder); if (placeholderId != 0) { context.AddReference <Text>(textComponentId, placeholder => { inputField.placeholder = placeholder; }); } inputField.caretBlinkRate = reader.GetFloatAttribute(AttributeCaretBlinkRate); inputField.selectionColor = reader.GetColor32Attribute(AttributeSelectionColor); inputField.shouldHideMobileInput = reader.GetBoolAttribute(AttributeHideMobileInput); if (reader.ReadToDescendant(ElementText)) { inputField.text = reader.ReadElementString(); } }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { base.Deserialize(component, reader, context); var scrollbar = (Scrollbar)component; var handleRectId = reader.GetIntAttribute(AttributeHandleRect); if (handleRectId != 0) { context.AddReference <RectTransform>(handleRectId, rect => { scrollbar.handleRect = rect; }); } scrollbar.direction = (Scrollbar.Direction)reader.GetIntAttribute(AttributeDirection); scrollbar.value = reader.GetFloatAttribute(AttributeValue); scrollbar.size = reader.GetFloatAttribute(AttrbuteSize); scrollbar.numberOfSteps = reader.GetIntAttribute(AttributeNumberOfSteps); }
private static void readComponent(XmlReader reader, GameObject gameObject, DeserializationContext context) { var element = reader.Name; ComponentResolver resolver; if (!mResolverNameBindings.TryGetValue(element, out resolver)) { Debug.LogWarning("Unresolved component type name -> " + element); return; } Component component; if (resolver.TargetType == typeof(Transform)) { component = gameObject.transform; } else { component = gameObject.AddComponent(resolver.TargetType); } var instanceId = reader.GetIntAttribute("InstanceId"); context.RegisterReference(instanceId, component); resolver.Deserialize(component, reader, context); //Debug.Log(component.GetType() + " loaded."); reader.Skip(); }
public override void ReadXml(XmlReader reader) { // Read tag attributes base.ReadXml(reader); SpectrumCount = reader.GetIntAttribute(ATTR.count_measured); // Consume tag reader.Read(); }
public override void ReadXml(XmlReader reader) { // Read tag attributes base.ReadXml(reader); PanoramaServer = reader.GetAttribute(ATTR.panorama_server); LibraryRevision = reader.GetIntAttribute(ATTR.revision); // Consume tag reader.Read(); }
public void ReadXml(XmlReader reader) { SkylineFilePath = reader.GetAttribute(ATTR.skyline_file_path); FolderToWatch = reader.GetAttribute(ATTR.folder_to_watch); IncludeSubfolders = reader.GetBoolAttribute(ATTR.include_subfolders); var pattern = reader.GetAttribute(ATTR.qc_file_pattern); var filterType = reader.GetAttribute(ATTR.file_filter_type); if (string.IsNullOrEmpty(filterType) && !string.IsNullOrEmpty(pattern)) { // Support for older version where filter type was not written to XML; only regex filters were allowed filterType = RegexFilter.NAME; } QcFileFilter = FileFilter.GetFileFilter(filterType, pattern); ResultsWindow = reader.GetIntAttribute(ATTR.results_window); InstrumentType = reader.GetAttribute(ATTR.instrument_type); AcquisitionTime = reader.GetIntAttribute(ATTR.acquisition_time); }
public void ReadXml(XmlReader reader) { // Read tag attributes MaxMissedCleavages = reader.GetIntAttribute(ATTR.max_missed_cleavages); ExcludeRaggedEnds = reader.GetBoolAttribute(ATTR.exclude_ragged_ends); // Consume tag reader.Read(); Validate(); }
public override void ReadXml(XmlReader reader) { // Read tag attributes base.ReadXml(reader); SpectrumCount = reader.GetIntAttribute(ATTR.count_measured); Score = reader.GetNullableDoubleAttribute(ATTR.score); ScoreType = reader.GetAttribute(ATTR.score_type); // Consume tag reader.Read(); }
public void ReadXml(XmlReader reader) { bool isEmpty = reader.IsEmptyElement; // Read past the property element reader.Read(); // For empty lists in Settings.Default if (isEmpty) { return; } if (reader.IsStartElement(EL.revision)) { RevisionIndex = reader.GetIntAttribute(ATTR.index); reader.Read(); // Consume tag } var helpers = GetXmlElementHelpers(); var helper = reader.FindHelper(helpers); // Read list items List <TValue> list = new List <TValue>(); if (helper != null) { reader.ReadElements(list, helpers); } else { // Support for v0.1 format if (reader.IsEmptyElement) { reader.Read(); } else { // Try to get through the elements with whatever // names they were given, based on class names. helper = new XmlElementHelper <TValue>(); reader.ReadStartElement(); // <ArrayOfType while (reader.IsStartElement()) { list.Add(helper.Deserialize(reader)); // <Type } reader.ReadEndElement(); } } Clear(); AddRange(list); // Perform final list specific updates ValidateLoad(); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { base.Deserialize(component, reader, context); var toggle = (Toggle)component; toggle.isOn = reader.GetBoolAttribute(AttributeIsOn); toggle.toggleTransition = (Toggle.ToggleTransition)reader.GetIntAttribute(AttributeToggleTransition); var graphicId = reader.GetIntAttribute(AttributeGraphic); var toggleGroupId = reader.GetIntAttribute(AttributeToggleGroup); if (graphicId != 0) { context.AddReference <Graphic>(graphicId, graphic => { toggle.graphic = graphic; }); } if (toggleGroupId != 0) { context.AddReference <ToggleGroup>(toggleGroupId, toggleGroup => { toggle.group = toggleGroup; }); } }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context">反序列化上下文</param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { base.Deserialize(component, reader, context); var slider = (Slider)component; var fillRectId = reader.GetIntAttribute(AttributeFillRect); var handleRectId = reader.GetIntAttribute(AttributeHandleRect); if (fillRectId != 0) { context.AddReference <RectTransform>(fillRectId, rect => { slider.fillRect = rect; }); } if (handleRectId != 0) { context.AddReference <RectTransform>(handleRectId, rect => { slider.handleRect = rect; }); } slider.direction = (Slider.Direction)reader.GetIntAttribute(AttributeDirection); slider.minValue = reader.GetFloatAttribute(AttributeMinValue); slider.maxValue = reader.GetFloatAttribute(AttributeMaxValue); slider.wholeNumbers = reader.GetBoolAttribute(AttributeWholeNumbers); slider.value = reader.GetFloatAttribute(AttributeValue); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context"></param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var image = (Image)component; var spriteId = reader.GetAttribute(AttributeSourceImage); context.AddDependency <Sprite>(spriteId, sprite => { image.sprite = sprite; }); image.color = reader.GetColor32Attribute(AttributeColor); image.material = reader.GetMaterialElement(ElementMaterial); image.type = (Image.Type)reader.GetIntAttribute(AttributeImageType); switch (image.type) { case Image.Type.Simple: reader.GetBoolAttribute(AttributePreserveAspect, image.preserveAspect); break; case Image.Type.Sliced: reader.GetBoolAttribute(AttributeFillCenter, image.fillCenter); break; case Image.Type.Tiled: reader.GetBoolAttribute(AttributeFillCenter, image.fillCenter); break; case Image.Type.Filled: image.fillMethod = (Image.FillMethod)reader.GetIntAttribute(AttributeFillCenter); image.fillOrigin = reader.GetIntAttribute(AttributeFillOrigin); image.fillAmount = reader.GetFloatAttribute(AttributeFillAmount); image.fillClockwise = reader.GetBoolAttribute(AttributeClockwise); image.preserveAspect = reader.GetBoolAttribute(AttributePreserveAspect); break; default: Debug.LogWarning("Unsupported image type -> " + image.type); break; } image.preserveAspect = reader.GetBoolAttribute(AttributePreserveAspect); }
unsafe void IXmlSerializable.ReadXml(XmlReader reader) { if (reader.AttributeCount >= 2 && GetIntAttribute("width", out var w) && GetIntAttribute("height", out var h)) { fixed(int *width = &Width) * width = w; fixed(int *height = &Height) * height = h; } bool GetIntAttribute(string name, out int value) => reader.GetIntAttribute(name, out value); }
public void ReadXml(XmlReader reader) { // Read tag attributes MonoisotopicMass = reader.GetNullableDoubleAttribute(ATTR.massdiff_monoisotopic) ?? 0; AverageMass = reader.GetNullableDoubleAttribute(ATTR.massdiff_average) ?? 0; Formula = reader.GetAttribute(ATTR.formula); Inclusion = reader.GetEnumAttribute(ATTR.inclusion, LossInclusion.Library); Charge = reader.GetIntAttribute(ATTR.charge, 0); // Consume tag reader.Read(); Validate(); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context"></param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var text = (Text)component; text.color = reader.GetColor32Attribute(AttributeColor); text.material = reader.GetMaterialElement(ElementMaterial); if (reader.ReadToDescendant(ElementText)) { text.text = reader.ReadElementString(); } //Character reader.ReadToDescendant(ElementCharacter); var font = reader.GetAttribute(AttributeFont); if (font != null) { text.font = Resources.GetBuiltinResource <Font>(font + ".ttf"); } text.fontStyle = (FontStyle)reader.GetIntAttribute(AttributeFontStyle); text.fontSize = reader.GetIntAttribute(AttributeFontSize); text.lineSpacing = reader.GetFloatAttribute(AttributeLineSpacing); text.supportRichText = reader.GetBoolAttribute(AttributeRichText); reader.Skip(); //Paragraph reader.ReadToDescendant(ElementParagraph); text.alignment = (TextAnchor)reader.GetIntAttribute(AttributeAlignment); #if UNITY_4_6_1 text.horizontalOverflow = (HorizontalWrapMode)reader.GetIntAttribute(AttributeHorizontalOverflow); text.verticalOverflow = (VerticalWrapMode)reader.GetIntAttribute(AttributeVerticalOverflow); #endif text.resizeTextForBestFit = reader.GetBoolAttribute(AttributeBestFit); reader.Skip(); }
public override void ReadXml(XmlReader reader) { base.ReadXml(reader); reader.ReadStartElement(); var columns = new List <GridColumn>(); while (reader.IsStartElement(El.grid_column)) { var name = reader.GetAttribute(Attr.name); var visible = reader.GetBoolAttribute(Attr.visible); var width = reader.GetIntAttribute(Attr.width); columns.Add(new GridColumn(name, visible, width)); reader.Read(); } _columns = ImmutableList.ValueOf(columns); reader.ReadEndElement(); }
public override void ReadXml(XmlReader reader) { // Read tag attributes base.ReadXml(reader); Fragment = reader.GetAttribute(ATTR.cut); if (IsFragment) { Restrict = reader.GetAttribute(ATTR.no_cut); Terminus = reader.GetAttribute(ATTR.sense, ToSeqTerminus); MinFragmentLength = reader.GetNullableIntAttribute(ATTR.min_length) ?? DEFAULT_MIN_FRAGMENT_LENGTH; } else { var charges = TextUtil.ParseInts(reader.GetAttribute(ATTR.charges)); // Old version? if (charges.Count() > 1) { throw new InvalidDataException(Resources.MeasuredIon_ReadXml_Multiple_charge_states_for_custom_ions_are_no_longer_supported_); } SettingsCustomIon = SettingsCustomIon.Deserialize(reader); if (charges.Any()) // Old style - fix it up a little for our revised ideas about custom ion ionization { Charge = charges[0]; if (string.IsNullOrEmpty(SettingsCustomIon.Formula)) // Adjust the user-supplied masses { SettingsCustomIon = new SettingsCustomIon(SettingsCustomIon.Formula, Math.Round(SettingsCustomIon.MonoisotopicMass + BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.H), SequenceMassCalc.MassPrecision), // Assume user provided neutral mass. Round new value easiest XML roundtripping. Math.Round(SettingsCustomIon.AverageMass + BioMassCalc.AVERAGE.GetMass(BioMassCalc.H), SequenceMassCalc.MassPrecision), // Assume user provided neutral mass. Round new value easiest XML roundtripping. SettingsCustomIon.Name); } } else { Charge = reader.GetIntAttribute(ATTR.charge); } IsOptional = reader.GetBoolAttribute(ATTR.optional); } // Consume tag reader.Read(); Validate(); }
/// <summary> /// 从指定的XML中读取并填充<see cref="Component"/>属性。 /// </summary> /// <param name="component">目标组件</param> /// <param name="reader">读取器</param> /// <param name="context"></param> public override void Deserialize(Component component, XmlReader reader, DeserializationContext context) { var canvas = (Canvas)component; canvas.renderMode = (RenderMode)reader.GetIntAttribute(AttributeRenderMode); switch (canvas.renderMode) { case RenderMode.ScreenSpaceOverlay: canvas.pixelPerfect = reader.GetBoolAttribute(AttributePixelPerfect); canvas.sortingOrder = reader.GetIntAttribute(AttributeSortOrder); break; case RenderMode.ScreenSpaceCamera: canvas.pixelPerfect = reader.GetBoolAttribute(AttributePixelPerfect); if (!string.IsNullOrEmpty(reader.GetAttribute(AttributeRenderCamera))) { Debug.LogWarning("Resolving render camera not implement yet."); } canvas.planeDistance = reader.GetFloatAttribute(AttributePlaneDistance); canvas.sortingLayerID = reader.GetIntAttribute(AttributeSortLayer); canvas.sortingOrder = reader.GetIntAttribute(AttributeOrderInLayer); break; case RenderMode.WorldSpace: if (!string.IsNullOrEmpty(reader.GetAttribute(AttributeEventCamera))) { Debug.LogWarning("Resolving event camera not implement yet."); } canvas.sortingLayerID = reader.GetIntAttribute(AttributeSortLayer); canvas.sortingOrder = reader.GetIntAttribute(AttributeOrderInLayer); break; default: Debug.LogWarning("Resolving " + canvas.renderMode + " not implement yet."); break; } }
/// <summary> /// 从<see cref="XmlReader"/>中读取指定名称的<see cref="Navigation"/>属性。 /// </summary> /// <param name="reader">读取器</param> /// <param name="name">属性名称</param> /// <param name="callback">成功后的回调</param> /// <param name="context">反序列化上下文</param> /// <returns>属性的值</returns> public static void GetNavigationElement(this XmlReader reader, string name, Action <Navigation> callback, DeserializationContext context) { if (!reader.IsStartElement(name)) { callback(Navigation.defaultNavigation); return; } var references = new Selectable[4]; var mode = (Navigation.Mode)reader.GetIntAttribute(AttributeNavigationMode); var up = reader.GetIntAttribute(AttributeNavigationUp); var down = reader.GetIntAttribute(AttributeNavigationDown); var left = reader.GetIntAttribute(AttributeNavigationLeft); var right = reader.GetIntAttribute(AttributeNavigationRight); switch (mode) { case Navigation.Mode.None: case Navigation.Mode.Horizontal: case Navigation.Mode.Vertical: case Navigation.Mode.Automatic: break; case Navigation.Mode.Explicit: if (up != 0) { context.AddReference <Selectable>(up, selectable => { references[0] = selectable; }); } if (down != 0) { context.AddReference <Selectable>(down, selectable => { references[1] = selectable; }); } if (left != 0) { context.AddReference <Selectable>(left, selectable => { references[2] = selectable; }); } if (right != 0) { context.AddReference <Selectable>(right, selectable => { references[3] = selectable; }); } context.AddCallback(() => { var navigation = new Navigation { mode = mode, selectOnUp = references[0], selectOnDown = references[1], selectOnLeft = references[2], selectOnRight = references[3], }; callback(navigation); }); break; default: Debug.LogWarning("Unsupported navigation mode -> " + mode); break; } reader.Skip(); }
public static int GetIntAttribute(this XmlReader reader, string name) { return(reader.GetIntAttribute(name, 0)); }
public void ReadXml(XmlReader reader) { // Read start tag attributes ExcludeNTermAAs = reader.GetIntAttribute(ATTR.start); MinPeptideLength = reader.GetIntAttribute(ATTR.min_length); MaxPeptideLength = reader.GetIntAttribute(ATTR.max_length); AutoSelect = reader.GetBoolAttribute(ATTR.auto_select); var list = new List<PeptideExcludeRegex>(); // Consume tag if (reader.IsEmptyElement) reader.Read(); else { reader.ReadStartElement(); // Read child elements reader.ReadElementList(EL.peptide_exclusions, list); reader.ReadEndElement(); } Exclusions = list; DoValidate(); }
public override void ReadXml(XmlReader reader) { RevisionIndex = reader.GetIntAttribute(Attr.revision); base.ReadXml(reader); AddDefaults(); }
public override void ReadXml(XmlReader reader) { // Read tag attributes base.ReadXml(reader); Fragment = reader.GetAttribute(ATTR.cut); if (IsFragment) { Restrict = reader.GetAttribute(ATTR.no_cut); Terminus = reader.GetAttribute(ATTR.sense, ToSeqTerminus); MinFragmentLength = reader.GetNullableIntAttribute(ATTR.min_length) ?? DEFAULT_MIN_FRAGMENT_LENGTH; } else { var charges = TextUtil.ParseInts(reader.GetAttribute(ATTR.charges)); // Old version? if (charges.Count() > 1) throw new InvalidDataException(Resources.MeasuredIon_ReadXml_Multiple_charge_states_for_custom_ions_are_no_longer_supported_); SettingsCustomIon = SettingsCustomIon.Deserialize(reader); if (charges.Any()) // Old style - fix it up a little for our revised ideas about custom ion ionization { Charge = charges[0]; if (string.IsNullOrEmpty(SettingsCustomIon.Formula)) // Adjust the user-supplied masses { SettingsCustomIon = new SettingsCustomIon(SettingsCustomIon.Formula, Math.Round(SettingsCustomIon.MonoisotopicMass + BioMassCalc.MONOISOTOPIC.GetMass(BioMassCalc.H), SequenceMassCalc.MassPrecision), // Assume user provided neutral mass. Round new value easiest XML roundtripping. Math.Round(SettingsCustomIon.AverageMass + BioMassCalc.AVERAGE.GetMass(BioMassCalc.H), SequenceMassCalc.MassPrecision), // Assume user provided neutral mass. Round new value easiest XML roundtripping. SettingsCustomIon.Name); } } else { Charge = reader.GetIntAttribute(ATTR.charge); } IsOptional = reader.GetBoolAttribute(ATTR.optional); } // Consume tag reader.Read(); Validate(); }
void ReadBlocks(XmlReader reader) { (int x, int y, Size size)prevBlock = default; if (reader.NodeType is XmlNodeType.None) { reader.Read(); } while (reader.Read()) { if (reader.NodeType is XmlNodeType.Element) { if (!reader.GetIntAttribute("x", out var x)) { throw new Exception("'x' attribute must be defined"); } if (!reader.GetIntAttribute("y", out var y)) { throw new Exception("'y' attribute must be defined"); } if (reader.GetStringAttribute("id", out var id) && blocks.ContainsKey(id !)) { throw new Exception($"id: '{id}' must be unique"); } var w = reader.GetIntAttribute("width", out var value) ? (int?)value : null; var h = reader.GetIntAttribute("height", out value) ? (int?)value : null; if (w.HasValue ^ h.HasValue) { throw new Exception("Neither or Both 'width' and 'height' must be set"); } else if (!w.HasValue && !h.HasValue && reader.GetIntAttribute("size", out var size)) { w = h = size; } (var prev, string?relativeTo) = (false, null); if (reader.GetStringAttribute(nameof(relativeTo), out relativeTo) && !(prev = relativeTo == nameof(prev)) && !blocks.ContainsKey(relativeTo !)) { throw new Exception($"id: '{relativeTo}' must be set before usage"); } else if (prev) { relativeTo = null; } SetBlocks((BlockType)Enum.Parse(typeof(BlockType), reader.Name), x, y); void SetBlocks(BlockType block, int x, int y) { if (prev || relativeTo is { }) { var relativeToBlock = prev ? prevBlock : blocks[relativeTo]; (x, y) = (x + relativeToBlock.x, y + relativeToBlock.y); } if (!w.HasValue && !h.HasValue) { Blocks[x, y] = block; prevBlock = (x, y, new Size(1, 1)); } else { foreach (var i in Enumerable.Range(x, w.Value)) { foreach (var j in Enumerable.Range(y, h.Value)) { Blocks[i, j] = block; } } prevBlock = (x, y, new Size(w.Value, h.Value)); } if (id is { })
/// <summary> /// Reads in an engine.xml file and turns it into a CaptionList, SpeakerSet and engine /// Settings. /// </summary> /// <param name="path">The Path to the engine.xml file.</param> /// <returns>A 3-Tuple containing a CaptionList, a SpeakerSet, and a Settings /// object in that specific order.</returns> public static Tuple <List <Caption>, Dictionary <string, Speaker>, SettingsXml> ParseEngineXml(string path) { var captionList = new List <Caption>(); var speakerSet = new Dictionary <string, Speaker>(); var settings = new SettingsXml(); XmlReaderSettings readerSettings = new XmlReaderSettings { IgnoreWhitespace = true, IgnoreComments = true }; using (XmlReader r = XmlReader.Create(path, readerSettings)) { while (r.Read()) { //Look for start elements only. if (!r.IsStartElement()) { continue; } // Get element name and switch on it. switch (r.Name) { case XmlElements.Enact: break; case XmlElements.Settings: r.Read(); r.AssertNode(XmlElements.Meta); settings.Base = r.GetNonNullAttribute(XmlAttributes.Base); settings.Spacing = r.GetNonNullAttribute(XmlAttributes.WordSpacing); settings.SeparateEmotionWords = r.GetNonNullAttribute(XmlAttributes.SeparateEmotionWords); r.Read(); r.AssertNode(XmlElements.Playback); settings.Playback.AutoPlay = r.GetBoolAttribute(XmlAttributes.AutoPlay); settings.Playback.AutoRewind = r.GetBoolAttribute(XmlAttributes.AutoRewind); settings.Playback.Seek = r.GetNonNullAttribute(XmlAttributes.Seek); settings.Playback.AutoSize = r.GetBoolAttribute(XmlAttributes.AutoSize); settings.Playback.Scale = r.GetIntAttribute(XmlAttributes.Scale); settings.Playback.Volume = r.GetIntAttribute(XmlAttributes.Volume); settings.Playback.ShowCaptions = r.GetBoolAttribute(XmlAttributes.ShowCaptions); r.Read(); r.AssertNode(XmlElements.Skin); settings.Skin.Source = r.GetNonNullAttribute(XmlAttributes.Source); settings.Skin.AutoHide = r.GetBoolAttribute(XmlAttributes.AutoHide); settings.Skin.FadeTime = r.GetIntAttribute(XmlAttributes.FadeTime); settings.Skin.BackGroundAlpha = r.GetIntAttribute(XmlAttributes.BackgroundAlpha); settings.Skin.BackgroundColour = r.GetNonNullAttribute(XmlAttributes.BackgroundColour); r.Read(); r.AssertNode(XmlElements.Video); settings.VideoSource = r.GetNonNullAttribute(XmlAttributes.Source); r.Read(); r.AssertNode(XmlElements.Emotions); r.Read(); r.AssertNode(XmlElements.Happy); settings.Happy.Fps = r.GetNonNullAttribute(XmlAttributes.FPS); settings.Happy.Duration = r.GetNonNullAttribute(XmlAttributes.Duration); settings.Happy.AlphaBegin = r.GetNonNullAttribute(XmlAttributes.AlphaBegin); settings.Happy.AlphaFinish = r.GetNonNullAttribute(XmlAttributes.AlphaFinish); settings.Happy.ScaleBegin = r.GetNonNullAttribute(XmlAttributes.ScaleBegin); settings.Happy.ScaleFinish = r.GetNonNullAttribute(XmlAttributes.ScaleFinish); settings.Happy.YFinish = r.GetNonNullAttribute(XmlAttributes.YFinish); r.Read(); r.AssertNode(XmlElements.Sad); settings.Sad.Fps = r.GetNonNullAttribute(XmlAttributes.FPS); settings.Sad.Duration = r.GetNonNullAttribute(XmlAttributes.Duration); settings.Sad.AlphaBegin = r.GetNonNullAttribute(XmlAttributes.AlphaBegin); settings.Sad.AlphaFinish = r.GetNonNullAttribute(XmlAttributes.AlphaFinish); settings.Sad.ScaleBegin = r.GetNonNullAttribute(XmlAttributes.ScaleBegin); settings.Sad.ScaleFinish = r.GetNonNullAttribute(XmlAttributes.ScaleFinish); settings.Sad.YFinish = r.GetNonNullAttribute(XmlAttributes.YFinish); r.Read(); r.AssertNode(XmlElements.Fear); settings.Fear.Fps = r.GetNonNullAttribute(XmlAttributes.FPS); settings.Fear.Duration = r.GetNonNullAttribute(XmlAttributes.Duration); settings.Fear.ScaleBegin = r.GetNonNullAttribute(XmlAttributes.ScaleBegin); settings.Fear.ScaleFinish = r.GetNonNullAttribute(XmlAttributes.ScaleFinish); settings.Fear.VibrateX = r.GetNonNullAttribute(XmlAttributes.VibrateX); settings.Fear.VibrateY = r.GetNonNullAttribute(XmlAttributes.VibrateY); r.Read(); r.AssertNode(XmlElements.Anger); settings.Anger.Fps = r.GetNonNullAttribute(XmlAttributes.FPS); settings.Anger.Duration = r.GetNonNullAttribute(XmlAttributes.Duration); settings.Anger.ScaleBegin = r.GetNonNullAttribute(XmlAttributes.ScaleBegin); settings.Anger.ScaleFinish = r.GetNonNullAttribute(XmlAttributes.ScaleFinish); settings.Anger.VibrateX = r.GetNonNullAttribute(XmlAttributes.VibrateX); settings.Anger.VibrateY = r.GetNonNullAttribute(XmlAttributes.VibrateY); break; case XmlElements.Speakers: break; //Do Nothing case XmlElements.Speaker: r.AssertNode(XmlElements.Speaker); string name = r.GetNonNullAttribute(XmlAttributes.Name); Speaker s = new Speaker(name); r.Read(); r.AssertNode(XmlElements.Background); //Create background colour based on xml paramaters bool visible = r.GetBoolAttribute(XmlAttributes.Visible); double alphaD = r.GetDoubleAttribute(XmlAttributes.Alpha); int colourCode = r.GetHexAttribute(XmlAttributes.Colour); int alpha = (int)((visible) ? alphaD * 0xFF : 0x00); // Bitshift alpha to the most significant byte of the integer s.Font.BackgroundColour = Color.FromArgb(alpha << 24 | colourCode); r.Read(); r.AssertNode(XmlElements.Font); s.Font.Family = r.GetNonNullAttribute(XmlAttributes.Name); s.Font.Size = r.GetIntAttribute(XmlAttributes.Size); s.Font.ForegroundColour = Color.FromArgb(SpeakerFont.ForegroundAlphaValue << 24 | r.GetHexAttribute(XmlAttributes.Colour)); s.Font.Bold = r.GetIntAttribute(XmlAttributes.Bold); r.ReadStartElement(XmlElements.Font); //Add to speakerSet speakerSet[s.Name] = s; break; case XmlElements.Captions: break; //Do Nothing case XmlElements.Caption: r.AssertNode(XmlElements.Caption); Caption c = new Caption { Begin = r.GetNonNullAttribute(XmlAttributes.Begin), End = r.GetNonNullAttribute(XmlAttributes.End), Speaker = speakerSet[r.GetNonNullAttribute(XmlAttributes.Speaker)], Location = (ScreenLocation)r.GetIntAttribute(XmlAttributes.Location), Alignment = (Alignment)r.GetIntAttribute(XmlAttributes.Align) }; List <CaptionWord> wordList = new List <CaptionWord>(); while (r.Read()) { //If the Node is an end element, then the reader has parsed //through all of this caption's words. if (r.NodeType == XmlNodeType.EndElement && r.Name.Equals(XmlElements.Caption)) { break; } if (r.NodeType == XmlNodeType.Element && r.Name.Equals(XmlElements.Word)) { r.AssertNode(XmlElements.Word); //Doublecheck, it's the only way to be sure. Emotion e = (Emotion)r.GetIntAttribute(XmlAttributes.Emotion); Intensity i = (Intensity)r.GetIntAttribute(XmlAttributes.Intensity); //Get word from node and add it to the list CaptionWord word = new CaptionWord(e, i, r.ReadString(), 0); wordList.Add(word); } } c.Words.SetWordList(wordList); captionList.Add(c); break; default: throw new ArgumentException("Value '" + r.Name + "' is not a valid node", r.Name); } }//Enact } return(Tuple.Create(captionList, speakerSet, settings)); }
public void ReadXml(XmlReader reader) { var list = new List<TypedModifications>(); var internalStandardTypes = new[] {IsotopeLabelType.heavy}; MaxVariableMods = reader.GetIntAttribute(ATTR.max_variable_mods, DEFAULT_MAX_VARIABLE_MODS); MaxNeutralLosses = reader.GetIntAttribute(ATTR.max_neutral_losses, DEFAULT_MAX_NEUTRAL_LOSSES); // Consume tag if (reader.IsEmptyElement) { list.Add(new TypedModifications(IsotopeLabelType.light, new StaticMod[0])); reader.Read(); } else { var internalStandardNames = new List<string>(); string internalStandardName = reader.GetAttribute(ATTR.internal_standard); reader.ReadStartElement(); if (internalStandardName != null) { if (internalStandardName == IsotopeLabelType.NONE_NAME) internalStandardTypes = new IsotopeLabelType[0]; else internalStandardNames.Add(internalStandardName); } else { while (reader.IsStartElement(EL.internal_standard)) { internalStandardNames.Add(reader.GetAttribute(ATTR.name)); reader.Read(); } } if (internalStandardNames.Count > 0) internalStandardTypes = new IsotopeLabelType[internalStandardNames.Count]; SetInternalStandardType(IsotopeLabelType.light, internalStandardNames, internalStandardTypes); // Read child elements var listMods = new List<StaticMod>(); reader.ReadElementList(EL.static_modifications, listMods); list.Add(new TypedModifications(IsotopeLabelType.light, listMods)); int typeOrder = IsotopeLabelType.FirstHeavy; while (reader.IsStartElement(EL.heavy_modifications)) { // If first heavy tag has no isotope_label attribute, use the default heavy type var labelType = IsotopeLabelType.heavy; string typeName = reader.GetAttribute(ATTR.isotope_label); if (!string.IsNullOrEmpty(typeName)) { labelType = new IsotopeLabelType(typeName, typeOrder); if (Equals(labelType, IsotopeLabelType.heavy)) labelType = IsotopeLabelType.heavy; // If the created label type is going to be used and there are serialization // context modifications, try to use the label types from the context. else if (_serializationContext != null) { var modsContext = _serializationContext.GetModificationsByName(typeName); if (modsContext != null) { // CONSIDER: Should this require full equality, including order? labelType = modsContext.LabelType; } } } else if (typeOrder > IsotopeLabelType.FirstHeavy) { throw new InvalidDataException( string.Format(Resources.PeptideModifications_ReadXml_Heavy_modifications_found_without__0__attribute, ATTR.isotope_label)); } typeOrder++; SetInternalStandardType(labelType, internalStandardNames, internalStandardTypes); // If no internal standard type was given, use the first heavy type. if (internalStandardNames.Count == 0 && internalStandardTypes.Length != 0) { internalStandardNames.Add(labelType.Name); internalStandardTypes = new[] {labelType}; } listMods = new List<StaticMod>(); reader.ReadElementList(EL.heavy_modifications, listMods); list.Add(new TypedModifications(labelType, listMods)); } int iMissingType = internalStandardTypes.IndexOf(labelType => labelType == null); if (iMissingType != -1) { throw new InvalidDataException(string.Format(Resources.PeptideModifications_ReadXml_Internal_standard_type__0__not_found, internalStandardNames[iMissingType])); } reader.ReadEndElement(); } if (list.Count < 2) list.Add(new TypedModifications(IsotopeLabelType.heavy, new StaticMod[0])); _modifications = MakeReadOnly(list.ToArray()); InternalStandardTypes = internalStandardTypes; DoValidate(); }