public override Size2D MeasureString(String text, StyleFont font) { GdiFont gdiFont = ViewConverter.Convert(font); SizeF gdiSize = _internalGraphics.MeasureString( text, gdiFont, Int32.MaxValue, StringFormat.GenericTypographic); return(ViewConverter.Convert(gdiSize)); }
public override IEnumerable <GdiRenderObject> RenderText(String text, StyleFont font, Rectangle2D layoutRectangle, Path2D flowPath, StyleBrush fontBrush, Matrix2D transform) { GdiRenderObject renderedText = new GdiRenderObject( text, ViewConverter.Convert(font), ViewConverter.Convert(layoutRectangle), ViewConverter.Convert(fontBrush), null, null, null, null, null); yield return(renderedText); }
public LabelStyle(StyleFont font, StyleBrush foreground, StyleBrush background, Point2D offset, Size2D collisionBuffer, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) : base(font, foreground, background, offset, collisionBuffer, horizontalAlignment, verticalAlignment) { }
private void ApplyUnsetStyleValue(StylePropertyReader reader, InheritedStylesData inheritedStylesData) { if (inheritedStylesData == null) { ApplyInitialStyleValue(reader); } var specificity = reader.specificity; switch (reader.propertyID) { case StylePropertyID.Color: color = inheritedStylesData.color; color.specificity = specificity; break; case StylePropertyID.Font: unityFont = inheritedStylesData.font; unityFont.specificity = specificity; break; case StylePropertyID.FontSize: fontSize = inheritedStylesData.fontSize; fontSize.specificity = specificity; break; case StylePropertyID.FontStyleAndWeight: unityFontStyleAndWeight = inheritedStylesData.unityFontStyle; unityFontStyleAndWeight.specificity = specificity; break; case StylePropertyID.UnityTextAlign: unityTextAlign = inheritedStylesData.unityTextAlign; unityTextAlign.specificity = specificity; break; case StylePropertyID.Visibility: visibility = inheritedStylesData.visibility; visibility.specificity = specificity; break; case StylePropertyID.WhiteSpace: whiteSpace = inheritedStylesData.whiteSpace; whiteSpace.specificity = specificity; break; case StylePropertyID.Custom: RemoveCustomStyleProperty(reader.property.name); break; default: ApplyInitialStyleValue(reader.propertyID, specificity); break; } }
public void CopyFrom(InheritedStylesData other) { if (other != null) { color = other.color; font = other.font; fontSize = other.fontSize; visibility = other.visibility; whiteSpace = other.whiteSpace; unityFontStyle = other.unityFontStyle; unityTextAlign = other.unityTextAlign; } }
private void SetPropertyValue(object newValue) { object val = StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id); Type type = m_PropertyInfo.type; if (newValue == null) { if (type == typeof(StyleBackground)) { val = new StyleBackground(); } if (type == typeof(StyleFont)) { val = new StyleFont(); } } else if (type == newValue.GetType()) { val = newValue; } else { if (type == typeof(StyleBackground)) { val = new StyleBackground(newValue as Texture2D); } else if (type == typeof(StyleEnum <Overflow>) && newValue is OverflowInternal) { OverflowInternal newV = (OverflowInternal)newValue; Overflow v = newV == OverflowInternal.Hidden ? Overflow.Hidden : Overflow.Visible; val = new StyleEnum <Overflow>(v); } else { var valueInfo = type.GetProperty("value"); try { valueInfo.SetValue(val, newValue, null); } catch (Exception) { Debug.LogError($"Invalid value for property '{m_PropertyName}'"); return; } } } StyleDebug.SetInlineStyleValue(m_SelectedElement.style, m_PropertyInfo.id, val); SetSpecificity(StyleDebug.InlineSpecificity); }
private static Font getFont(StyleFont styleFont) { if (styleFont == null) { return(null); } FontLookupKey key = new FontLookupKey(styleFont.GetHashCode()); Font font; _fontCache.TryGetValue(key, out font); return(font); }
/// <summary> /// Initializes a new Label instance. /// </summary> /// <param name="text">Text to write</param> /// <param name="location">Position of label</param> /// <param name="rotation">Rotation</param> /// <param name="priority">Label priority used for collision detection.</param> /// <param name="collisionBuffer">Area around label for collision detection.</param> /// <param name="style">The style to use in rendering the label.</param> public Label2D(String text, Point2D location, Single rotation, Int32 priority, Size2D collisionBuffer, LabelStyle style) { _text = text; _location = location; _rotation = rotation; _priority = priority; _collisionBuffer = collisionBuffer; _style = style ?? new LabelStyle(); _collisionBuffer = _style.CollisionBuffer; _font = _style.Font; _offset = _style.Offset; }
public static GdiFont Convert(StyleFont styleFont) { GdiFont font = getFont(styleFont); if (font == null) { font = new Font(styleFont.FontFamily.Name, (Single)styleFont.Size.Width, Convert(styleFont.Style)); saveFont(styleFont, font); } return(font); }
public void ApplyFont(StyleSheet sheet, StyleValueHandle[] handles, int specificity, ref StyleFont property) { StyleValueHandle handle = handles[0]; Font font = null; switch (handle.valueType) { case StyleValueType.ResourcePath: { string path = sheet.ReadResourcePath(handle); if (!string.IsNullOrEmpty(path)) { font = Panel.LoadResource(path, typeof(Font)) as Font; } if (font == null) { Debug.LogWarning(string.Format("Font not found for path: {0}", path)); } } break; case StyleValueType.AssetReference: { font = sheet.ReadAssetReference(handle) as Font; if (font == null) { Debug.LogWarning("Invalid font reference"); } } break; default: Debug.LogWarning("Invalid value for font " + handle.valueType); break; } if (font != null) { var value = new StyleFont(font) { specificity = specificity }; property.Apply(value, StylePropertyApplyMode.CopyIfEqualOrGreaterSpecificity); } }
IEnumerable ITextRenderer <Point2D, Size2D, Rectangle2D> .RenderText( String text, StyleFont font, Rectangle2D layoutRectangle, Path <Point2D, Rectangle2D> flowPath, StyleBrush fontBrush, IMatrix <DoubleComponent> transform) { if (!(flowPath is Path2D)) { throw new ArgumentException("Parameter must be a Path2D instance.", "flowPath"); } if (!(transform is Matrix2D)) { throw new ArgumentException("Parameter must be a Matrix2D instance.", "transform"); } return(RenderText(text, font, layoutRectangle, flowPath as Path2D, fontBrush, transform as Matrix2D)); }
private void SetPropertyValue(object newValue) { object val = StyleDebug.GetComputedStyleValue(m_SelectedElement.computedStyle, m_PropertyInfo.id); Type type = m_PropertyInfo.type; if (newValue == null) { if (type == typeof(StyleBackground)) { val = new StyleBackground(); } if (type == typeof(StyleFont)) { val = new StyleFont(); } if (type == typeof(StyleFontDefinition)) { val = new StyleFontDefinition(); } } else if (type == newValue.GetType()) { // For StyleLengthField val = newValue; } else { if (type == typeof(StyleBackground)) { val = new StyleBackground(newValue as Texture2D); } else if (type == typeof(StyleFontDefinition)) { val = new StyleFontDefinition(newValue); } else if (val is TextShadow textShadow) { if (newValue is Color newColor) { textShadow.color = newColor; } if (newValue is Vector2 newOffset) { textShadow.offset = newOffset; } if (newValue is float newBlur) { textShadow.blurRadius = newBlur; } val = new StyleTextShadow(textShadow); } else if (type == typeof(StyleEnum <Overflow>) && newValue is OverflowInternal) { OverflowInternal newV = (OverflowInternal)newValue; Overflow v = newV == OverflowInternal.Hidden ? Overflow.Hidden : Overflow.Visible; val = new StyleEnum <Overflow>(v); } else if (val is Scale scale && newValue is Vector3 newScale) { val = new StyleScale(new Scale(newScale)); }
public override Size2D MeasureString(String text, StyleFont font) { throw new Exception("The method or operation is not implemented."); }
public override IEnumerable <Object> RenderText(String text, StyleFont font, Rectangle2D layoutRectangle, Path2D flowPath, StyleBrush fontBrush, Matrix2D transform) { throw new Exception("The method or operation is not implemented."); }
public void ApplyFont(StyleSheet sheet, StyleValueHandle[] handles, int specificity, ref StyleFont property) { Font font = null; if (currentStyleValue.resource.IsAllocated) { font = currentStyleValue.resource.Target as Font; } property.Apply(new StyleFont(font, currentStyleValue.keyword) { specificity = specificity }, StylePropertyApplyMode.Copy); }
public LabelStyle(StyleFont font, StyleBrush foreground) : base(font, foreground) { }
public static List <VisualElement> AddRichText(string text, IButtonRegistry buttonRegistry, VisualElement root, bool isInsideCodeBlock) { List <VisualElement> results = new List <VisualElement>(); IEnumerable <RichText> richTexts = ParseRichText(text, isInsideCodeBlock); //Parse rich texts to create paragraphs. List <List <RichText> > paragraphs = new List <List <RichText> > { new List <RichText>() }; foreach (RichText richText in richTexts) { if (richText.richTextTag.tag == RichTextTag.Tag.button || richText.richTextTag.tag == RichTextTag.Tag.code) { paragraphs[paragraphs.Count - 1].Add(richText); continue; } string[] strings = richText.associatedText.Split('\n'); for (int i = 0; i < strings.Length; i++) { if (i != 0) { paragraphs.Add(new List <RichText>()); } //Split paragraph content (already split by tag) into individual words string[] wordSplit = Regex.Split(strings[i], @"(?<=[ -])"); //Split but keep delimiters attached. foreach (var word in wordSplit) { if (!string.IsNullOrEmpty(word)) { paragraphs[paragraphs.Count - 1].Add(new RichText(richText.richTextTag, word)); } } } } foreach (List <RichText> paragraph in paragraphs) { //Add all the paragraphs VisualElement rootTemp = root; root = AddParagraphContainer(root); for (int i = 0; i < paragraph.Count; i++) { RichText word = paragraph[i]; if (i < paragraph.Count - 1) { //If there are more words RichText nextWord = paragraph[i + 1]; string nextText = nextWord.associatedText; if (Regex.IsMatch(nextText, "^[^a-zA-Z] ?")) { VisualElement inlineGroup = new VisualElement(); root.Add(inlineGroup); inlineGroup.AddToClassList("inline-text-group"); AddRichTextInternal(word, inlineGroup); AddRichTextInternal(nextWord, inlineGroup); ++i; continue; } } AddRichTextInternal(word, root); //Add all the words and style them. void AddRichTextInternal(RichText richText, VisualElement rootToAddTo) { RichTextTag tag = richText.richTextTag; TextElement inlineText = null; switch (tag.tag) { case RichTextTag.Tag.none: inlineText = AddInlineText(richText.associatedText, rootToAddTo); break; case RichTextTag.Tag.button: if (buttonRegistry == null) { Debug.LogWarning("There was no ButtonRegistry provided to AddRichText. Button tags will not function."); inlineText = AddInlineButton(() => Debug.LogWarning("There was no ButtonRegistry provided to AddRichText. Button tags will not function."), richText.associatedText, rootToAddTo); break; } if (!buttonRegistry.GetRegisteredButtonAction(tag.stringVariables, out Action action)) { return; } inlineText = AddInlineButton(action, richText.associatedText, rootToAddTo); break; case RichTextTag.Tag.code: //Scroll ScrollView codeScroll = new ScrollView(ScrollViewMode.Horizontal); VisualElement contentContainer = codeScroll.contentContainer; codeScroll.contentViewport.style.flexDirection = FlexDirection.Column; codeScroll.contentViewport.style.alignItems = Align.Stretch; codeScroll.AddToClassList("code-scroll"); root.Add(codeScroll); contentContainer.ClearClassList(); contentContainer.AddToClassList("code-container"); VisualElement codeContainer = contentContainer; CSharpHighlighter highlighter = new CSharpHighlighter { AddStyleDefinition = false }; // To add code, we first use the CSharpHighlighter to construct rich text for us. string highlit = highlighter.Highlight(richText.associatedText); // After constructing new rich text we pass the text back recursively through this function with the new parent. AddRichText(highlit, buttonRegistry, codeContainer, true); // only parse spans because this is all the CSharpHighlighter parses. //Finalise content container foreach (VisualElement child in codeContainer.Children()) { if (child.ClassListContains(paragraphContainerClass)) { child.AddToClassList("code"); if (child.childCount == 1) { AddInlineText("", child); //This seems to be required to get layout to function properly. } } } //Begin Hack FieldInfo m_inheritedStyle = typeof(VisualElement).GetField("inheritedStyle", BindingFlags.NonPublic | BindingFlags.Instance); if (m_inheritedStyle == null) { m_inheritedStyle = typeof(VisualElement).GetField("m_InheritedStylesData", BindingFlags.NonPublic | BindingFlags.Instance); } Type inheritedStylesData = Type.GetType("UnityEngine.UIElements.StyleSheets.InheritedStylesData,UnityEngine"); FieldInfo font = inheritedStylesData.GetField("font", BindingFlags.Public | BindingFlags.Instance); FieldInfo fontSize = inheritedStylesData.GetField("fontSize", BindingFlags.Public | BindingFlags.Instance); Font consola = (Font)EditorGUIUtility.Load("consola"); contentContainer.Query <Label>().ForEach(l => { l.AddToClassList("code"); //Hack to regenerate the font size as Rich Text tags are removed from the original calculation. object value = m_inheritedStyle.GetValue(l); StyleFont fontVar = (StyleFont)font.GetValue(value); fontVar.value = consola; font.SetValue(value, fontVar); StyleLength fontSizeVar = 12; // = (StyleLength) fontSize.GetValue(value); //This doesn't seem to work properly, hard coded for now. fontSize.SetValue(value, fontSizeVar); m_inheritedStyle.SetValue(l, value); Vector2 measuredTextSize = l.MeasureTextSize(l.text.Replace('>', ' '), 0, VisualElement.MeasureMode.Undefined, 0, VisualElement.MeasureMode.Undefined); l.style.width = measuredTextSize.x; l.style.height = measuredTextSize.y; }); //Button Button codeCopyButtonButtonContainer = new Button(() => { EditorGUIUtility.systemCopyBuffer = richText.associatedText; Debug.Log("Copied Code to Clipboard"); }); codeCopyButtonButtonContainer.ClearClassList(); codeCopyButtonButtonContainer.AddToClassList("code-button"); codeCopyButtonButtonContainer.StretchToParentSize(); codeContainer.Add(codeCopyButtonButtonContainer); break; case RichTextTag.Tag.span: Label spanLabel = new Label { text = richText.associatedText }; spanLabel.AddToClassList(tag.stringVariables); rootToAddTo.Add(spanLabel); break; case RichTextTag.Tag.image: throw new NotImplementedException(); default: throw new ArgumentOutOfRangeException(); } if (inlineText != null) { inlineText.style.unityFontStyleAndWeight = tag.fontStyle; if (tag.size > 0) { inlineText.style.fontSize = tag.size; } if (tag.color != Color.clear) { inlineText.style.color = tag.color; } results.Add(inlineText); } } } root = rootTemp; } return(results); /*void RichTextDebug(string richText) => Debug.Log(GetRichTextCapableText(richText)); * string GetRichTextCapableText(string richText) => text.Replace("<", "<<b></b>");*/ }
public abstract IEnumerable <TRenderObject> RenderText(String text, StyleFont font, Rectangle2D layoutRectangle, Path2D flowPath, StyleBrush fontBrush, Matrix2D transform);
public abstract Size2D MeasureString(String text, StyleFont font);
public IEnumerable <TRenderObject> RenderText(String text, StyleFont font, Point2D location, StyleBrush fontBrush) { Rectangle2D layoutRectangle = new Rectangle2D(location, MeasureString(text, font)); return(RenderText(text, font, layoutRectangle, null, fontBrush, null)); }
private void SetPropertyValue(object newValue) { object val = StyleDebug.GetComputedStyleActualValue(m_SelectedElement.computedStyle, m_PropertyInfo.id); Type type = m_PropertyInfo.type; if (newValue == null) { if (type == typeof(StyleBackground)) { val = new StyleBackground(); } if (type == typeof(StyleFont)) { val = new StyleFont(); } } else if (type == newValue.GetType()) { // For StyleLengthField val = newValue; } else { if (type == typeof(StyleBackground)) { val = new StyleBackground(newValue as Texture2D); } else if (type == typeof(StyleFontDefinition)) { val = new StyleFontDefinition(newValue); } else if (val is TextShadow textShadow) { if (newValue is Color newColor) { textShadow.color = newColor; } if (newValue is Vector2 newOffset) { textShadow.offset = newOffset; } if (newValue is float newBlur) { textShadow.blurRadius = newBlur; } val = new StyleTextShadow(textShadow); } else if (type == typeof(StyleEnum <Overflow>) && newValue is OverflowInternal) { OverflowInternal newV = (OverflowInternal)newValue; Overflow v = newV == OverflowInternal.Hidden ? Overflow.Hidden : Overflow.Visible; val = new StyleEnum <Overflow>(v); } else { var underlyingType = type.GetProperty("value").PropertyType; var ctor = type.GetConstructor(new[] { underlyingType }); try { val = ctor.Invoke(new[] { newValue }); } catch (Exception) { Debug.LogError($"Invalid value for property '{m_PropertyName}'"); return; } } } StyleDebug.SetInlineStyleValue(m_SelectedElement.style, m_PropertyInfo.id, val); SetSpecificity(StyleDebug.InlineSpecificity); }
internal void ApplyStyleProperty(IStylePropertyReader reader) { switch (reader.propertyID) { case StylePropertyID.AlignContent: StyleSheetApplicator.ApplyAlign(reader, ref alignContent); break; case StylePropertyID.AlignItems: StyleSheetApplicator.ApplyAlign(reader, ref alignItems); break; case StylePropertyID.AlignSelf: StyleSheetApplicator.ApplyAlign(reader, ref alignSelf); break; case StylePropertyID.BackgroundImage: backgroundImage = reader.ReadStyleBackground(0); break; case StylePropertyID.FlexBasis: flexBasis = reader.ReadStyleLength(0); break; case StylePropertyID.FlexGrow: flexGrow = reader.ReadStyleFloat(0); break; case StylePropertyID.FlexShrink: flexShrink = reader.ReadStyleFloat(0); break; case StylePropertyID.Font: unityFont = reader.ReadStyleFont(0); break; case StylePropertyID.FontSize: fontSize = reader.ReadStyleLength(0); break; case StylePropertyID.FontStyleAndWeight: unityFontStyleAndWeight = reader.ReadStyleEnum <FontStyle>(0); break; case StylePropertyID.FlexDirection: flexDirection = reader.ReadStyleEnum <FlexDirection>(0); break; case StylePropertyID.FlexWrap: flexWrap = reader.ReadStyleEnum <Wrap>(0); break; case StylePropertyID.Height: height = reader.ReadStyleLength(0); break; case StylePropertyID.JustifyContent: justifyContent = reader.ReadStyleEnum <Justify>(0); break; case StylePropertyID.MarginLeft: marginLeft = reader.ReadStyleLength(0); break; case StylePropertyID.MarginTop: marginTop = reader.ReadStyleLength(0); break; case StylePropertyID.MarginRight: marginRight = reader.ReadStyleLength(0); break; case StylePropertyID.MarginBottom: marginBottom = reader.ReadStyleLength(0); break; case StylePropertyID.MaxHeight: maxHeight = reader.ReadStyleLength(0); break; case StylePropertyID.MaxWidth: maxWidth = reader.ReadStyleLength(0); break; case StylePropertyID.MinHeight: minHeight = reader.ReadStyleLength(0); break; case StylePropertyID.MinWidth: minWidth = reader.ReadStyleLength(0); break; case StylePropertyID.Overflow: overflow = reader.ReadStyleEnum <OverflowInternal>(0); break; case StylePropertyID.OverflowClipBox: unityOverflowClipBox = reader.ReadStyleEnum <OverflowClipBox>(0); break; case StylePropertyID.PaddingLeft: paddingLeft = reader.ReadStyleLength(0); break; case StylePropertyID.PaddingTop: paddingTop = reader.ReadStyleLength(0); break; case StylePropertyID.PaddingRight: paddingRight = reader.ReadStyleLength(0); break; case StylePropertyID.PaddingBottom: paddingBottom = reader.ReadStyleLength(0); break; case StylePropertyID.Position: position = reader.ReadStyleEnum <Position>(0); break; case StylePropertyID.PositionTop: top = reader.ReadStyleLength(0); break; case StylePropertyID.PositionBottom: bottom = reader.ReadStyleLength(0); break; case StylePropertyID.PositionLeft: left = reader.ReadStyleLength(0); break; case StylePropertyID.PositionRight: right = reader.ReadStyleLength(0); break; case StylePropertyID.UnityTextAlign: unityTextAlign = reader.ReadStyleEnum <TextAnchor>(0); break; case StylePropertyID.Color: color = reader.ReadStyleColor(0); break; case StylePropertyID.Width: width = reader.ReadStyleLength(0); break; case StylePropertyID.WhiteSpace: whiteSpace = reader.ReadStyleEnum <WhiteSpace>(0); break; case StylePropertyID.BackgroundColor: backgroundColor = reader.ReadStyleColor(0); break; case StylePropertyID.BackgroundScaleMode: unityBackgroundScaleMode = reader.ReadStyleEnum <ScaleMode>(0); break; case StylePropertyID.BackgroundImageTintColor: unityBackgroundImageTintColor = reader.ReadStyleColor(0); break; case StylePropertyID.BorderLeftColor: borderLeftColor = reader.ReadStyleColor(0); break; case StylePropertyID.BorderTopColor: borderTopColor = reader.ReadStyleColor(0); break; case StylePropertyID.BorderRightColor: borderRightColor = reader.ReadStyleColor(0); break; case StylePropertyID.BorderBottomColor: borderBottomColor = reader.ReadStyleColor(0); break; case StylePropertyID.BorderLeftWidth: borderLeftWidth = reader.ReadStyleFloat(0); break; case StylePropertyID.BorderTopWidth: borderTopWidth = reader.ReadStyleFloat(0); break; case StylePropertyID.BorderRightWidth: borderRightWidth = reader.ReadStyleFloat(0); break; case StylePropertyID.BorderBottomWidth: borderBottomWidth = reader.ReadStyleFloat(0); break; case StylePropertyID.BorderTopLeftRadius: borderTopLeftRadius = reader.ReadStyleLength(0); break; case StylePropertyID.BorderTopRightRadius: borderTopRightRadius = reader.ReadStyleLength(0); break; case StylePropertyID.BorderBottomRightRadius: borderBottomRightRadius = reader.ReadStyleLength(0); break; case StylePropertyID.BorderBottomLeftRadius: borderBottomLeftRadius = reader.ReadStyleLength(0); break; case StylePropertyID.Cursor: cursor = reader.ReadStyleCursor(0); break; case StylePropertyID.SliceLeft: unitySliceLeft = reader.ReadStyleInt(0); break; case StylePropertyID.SliceTop: unitySliceTop = reader.ReadStyleInt(0); break; case StylePropertyID.SliceRight: unitySliceRight = reader.ReadStyleInt(0); break; case StylePropertyID.SliceBottom: unitySliceBottom = reader.ReadStyleInt(0); break; case StylePropertyID.Opacity: opacity = reader.ReadStyleFloat(0); break; case StylePropertyID.Visibility: visibility = reader.ReadStyleEnum <Visibility>(0); break; case StylePropertyID.Display: StyleSheetApplicator.ApplyDisplay(reader, ref display); break; default: throw new ArgumentException(string.Format("Non exhaustive switch statement (value={0})", reader.propertyID)); } }
IEnumerable ITextRenderer <Point2D, Size2D, Rectangle2D> .RenderText(String text, StyleFont font, Point2D location, StyleBrush fontBrush) { throw new Exception("The method or operation is not implemented."); }
public override IEnumerable <DependencyObject> RenderText(string text, StyleFont font, Rectangle2D layoutRectangle, Path2D flowPath, StyleBrush fontBrush, Matrix2D transform) { throw new NotImplementedException(); }
public override Size2D MeasureString(string text, StyleFont font) { throw new NotImplementedException(); }
private static void saveFont(StyleFont styleFont, Font font) { _fontCache[new FontLookupKey(styleFont.GetHashCode())] = font; }
public override Size2D MeasureString(string text, StyleFont font) { return(Size2D.Empty); //we will leave it up to the client to measure the string. }