// This is the ReSharper 8.1 version public RichTextBlock GetElementDescription(IDeclaredElement element, DeclaredElementDescriptionStyle style, PsiLanguageType language, IPsiModule module) { var attribute = element as IHtmlAttributeDeclaredElement; if (attribute == null) return null; var attributeDescription = GetAttributeDescription(attribute.ShortName); var block = new RichTextBlock(); var typeDescription = new RichText(htmlDescriptionsCache.GetDescriptionForHtmlValueType(attribute.ValueType)); if (style.IntendedDescriptionPlacement == DescriptionPlacement.AFTER_NAME && (style.ShowSummary || style.ShowFullDescription)) block.SplitAndAdd(typeDescription); string description = null; if (style.ShowSummary && attributeDescription != null) description = attributeDescription.Summary; else if (style.ShowFullDescription && attributeDescription != null) description = attributeDescription.Description; if (!string.IsNullOrEmpty(description)) block.SplitAndAdd(description); if (style.IntendedDescriptionPlacement == DescriptionPlacement.ON_THE_NEW_LINE && (style.ShowSummary || style.ShowFullDescription)) { // TODO: Perhaps we should show Value: Expression for attributes that take an Angular expression, etc typeDescription.Prepend("Value: "); block.SplitAndAdd(typeDescription); } return block; }
public RichText TryPresent([NotNull] DeclaredElementInstance declaredElementInstance, [NotNull] PresenterOptions options, [NotNull] PsiLanguageType languageType, bool useReSharperColors, [NotNull] out PresentedInfo presentedInfo) { var richText = new RichText(); IColorizer colorizer = TryCreateColorizer(richText, languageType, useReSharperColors); if (colorizer == null) { presentedInfo = new PresentedInfo(); return null; } presentedInfo = colorizer.AppendDeclaredElement(declaredElementInstance.Element, declaredElementInstance.Substitution, options); return richText; }
/// <summary> /// Presents the specified descriptor. /// </summary> /// <param name="descriptor">The descriptor.</param> /// <param name="occurence">The occurence.</param> /// <param name="occurencePresentationOptions">The occurence presentation options.</param> /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns> public bool Present(IMenuItemDescriptor descriptor, IOccurence occurence, OccurencePresentationOptions occurencePresentationOptions) { var itemOccurence = occurence as ItemOccurence; if (itemOccurence == null) { return false; } var greyTextStyle = TextStyle.FromForeColor(SystemColors.GrayText); var richText = new RichText(itemOccurence.ItemName, TextStyle.FromForeColor(Color.Tomato)); if (!string.IsNullOrEmpty(itemOccurence.ParentPath)) { richText.Append(string.Format(" (in {0})", itemOccurence.ParentPath), greyTextStyle); } descriptor.Text = richText; descriptor.Style = MenuItemStyle.Enabled; descriptor.ShortcutText = new RichText(itemOccurence.ItemUri.Site.Name + "/" + itemOccurence.ItemUri.DatabaseName, greyTextStyle); return true; }
public void RichText_Decode_2() { Assert.AreEqual("Привет", RichText.Decode("\\u1055?\\u1088?\\u1080?\\u1074?\\u1077?\\u1090?")); }
public string GetHtml(Range r) { this.tb = r.tb; Dictionary <StyleIndex, object> styles = new Dictionary <StyleIndex, object>(); StringBuilder sb = new StringBuilder(); StringBuilder tempSB = new StringBuilder(); StyleIndex currentStyleId = StyleIndex.None; r.Normalize(); int currentLine = r.Start.iLine; styles[currentStyleId] = null; // if (UseOriginalFont) { sb.AppendFormat("<font style=\"font-family: {0}, monospace; font-size: {1}px; line-height: {2}px;\">", r.tb.Font.Name, r.tb.CharHeight - r.tb.LineInterval, r.tb.CharHeight); } // if (IncludeLineNumbers) { tempSB.AppendFormat("<span class=lineNumber>{0}</span> ", currentLine + 1); } // bool hasNonSpace = false; foreach (Place p in r) { Char c = r.tb[p.iLine][p.iChar]; if (c.style != currentStyleId) { Flush(sb, tempSB, currentStyleId); currentStyleId = c.style; styles[currentStyleId] = null; } if (p.iLine != currentLine) { for (int i = currentLine; i < p.iLine; i++) { tempSB.AppendLine(UseBr ? "<br>" : ""); if (IncludeLineNumbers) { tempSB.AppendFormat("<span class=lineNumber>{0}</span> ", i + 2); } } currentLine = p.iLine; hasNonSpace = false; } switch (c.c) { case ' ': if ((hasNonSpace || !UseForwardNbsp) && !UseNbsp) { goto default; } tempSB.Append(" "); break; case '<': tempSB.Append("<"); break; case '>': tempSB.Append(">"); break; case '&': tempSB.Append("&"); break; default: hasNonSpace = true; tempSB.Append(c.c); break; } } Flush(sb, tempSB, currentStyleId); if (UseOriginalFont) { sb.AppendLine("</font>"); } //build styles if (UseStyleTag) { tempSB.Length = 0; tempSB.AppendLine("<style type=\"text/css\">"); foreach (var styleId in styles.Keys) { tempSB.AppendFormat(".fctb{0}{{ {1} }}\r\n", GetStyleName(styleId), GetCss(styleId)); } tempSB.AppendLine("</style>"); sb.Insert(0, tempSB.ToString()); } if (IncludeLineNumbers) { sb.Insert(0, LineNumbersCSS); } return(sb.ToString()); }
/// <summary> /// Shows VisualMarker /// Call this method in Draw method, when you need to show VisualMarker for your style /// </summary> protected virtual void AddVisualMarker(RichText tb, StyleVisualMarker marker) { tb.AddVisualMarker(marker); }
protected TooltipContent([CanBeNull] RichText text, TextRange trackingRange) { _text = text; _trackingRange = trackingRange; }
public static void Run() { // ExStart:InsertChineseNumberList // ExFor:NumberList // ExFor:ParagraphStyle // ExFor:ParagraphStyle.FontColor // ExFor:ParagraphStyle.FontName // ExFor:ParagraphStyle.FontSize // ExFor:Page // ExFor:Outline // ExFor:OutlineElement // ExFor:OutlineElement.NumberList // ExFor:RichText // ExFor:RichText.ParagraphStyle // ExFor:RichText.Text // ExSummary:Shows how to insert new list with chinese numbering. string dataDir = RunExamples.GetDataDir_Text(); // Initialize OneNote document Aspose.Note.Document doc = new Aspose.Note.Document(); // Initialize OneNote page Aspose.Note.Page page = new Aspose.Note.Page(doc); Outline outline = new Outline(doc); // Apply text style settings ParagraphStyle defaultStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; // Numbers in the same outline are automatically incremented. OutlineElement outlineElem1 = new OutlineElement(doc) { NumberList = new NumberList("{0})", NumberFormat.ChineseCounting, "Arial", 10) }; RichText text1 = new RichText(doc) { Text = "First", ParagraphStyle = defaultStyle }; outlineElem1.AppendChildLast(text1); //------------------------ OutlineElement outlineElem2 = new OutlineElement(doc) { NumberList = new NumberList("{0})", NumberFormat.ChineseCounting, "Arial", 10) }; RichText text2 = new RichText(doc) { Text = "Second", ParagraphStyle = defaultStyle }; outlineElem2.AppendChildLast(text2); //------------------------ OutlineElement outlineElem3 = new OutlineElement(doc) { NumberList = new NumberList("{0})", NumberFormat.ChineseCounting, "Arial", 10) }; RichText text3 = new RichText(doc) { Text = "Third", ParagraphStyle = defaultStyle }; outlineElem3.AppendChildLast(text3); //------------------------ outline.AppendChildLast(outlineElem1); outline.AppendChildLast(outlineElem2); outline.AppendChildLast(outlineElem3); page.AppendChildLast(outline); doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "InsertChineseNumberList_out.one"; doc.Save(dataDir); // ExEnd:InsertChineseNumberList Console.WriteLine("\nChinese number list inserted successfully.\nFile saved at " + dataDir); }
void RPC_ChangeGameMode(int mode) { settings.mode = (GameMode)mode; gameModeText.text = RichText.Paint("Game mode: ", Color.red, true, false) + RichText.Paint(settings.mode.ToString(), Color.white, false, true); }
public static void Run() { // ExStart:ApplyBulletsOnText // ExFor:ParagraphStyle // ExFor:ParagraphStyle.FontColor // ExFor:ParagraphStyle.FontName // ExFor:ParagraphStyle.FontSize // ExFor:Page // ExFor:Outline // ExFor:OutlineElement // ExFor:OutlineElement.NumberList // ExFor:RichText // ExFor:RichText.ParagraphStyle // ExFor:RichText.Text // ExSummary:Shows how to insert new bulleted lis. string dataDir = RunExamples.GetDataDir_Text(); // Create an object of the Document class Aspose.Note.Document doc = new Aspose.Note.Document(); // Initialize Page class object Aspose.Note.Page page = new Aspose.Note.Page(doc); // Initialize Outline class object Outline outline = new Outline(doc); // Initialize TextStyle class object and set formatting properties ParagraphStyle defaultStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; // Initialize OutlineElement class objects and apply bullets OutlineElement outlineElem1 = new OutlineElement(doc) { NumberList = new NumberList("*", "Arial", 10) }; // Initialize RichText class object and apply text style RichText text1 = new RichText(doc) { Text = "First", ParagraphStyle = defaultStyle }; outlineElem1.AppendChildLast(text1); OutlineElement outlineElem2 = new OutlineElement(doc) { NumberList = new NumberList("*", "Arial", 10) }; RichText text2 = new RichText(doc) { Text = "Second", ParagraphStyle = defaultStyle }; outlineElem2.AppendChildLast(text2); OutlineElement outlineElem3 = new OutlineElement(doc) { NumberList = new NumberList("*", "Arial", 10) }; RichText text3 = new RichText(doc) { Text = "Third", ParagraphStyle = defaultStyle }; outlineElem3.AppendChildLast(text3); // Add outline elements outline.AppendChildLast(outlineElem1); outline.AppendChildLast(outlineElem2); outline.AppendChildLast(outlineElem3); // Add Outline node page.AppendChildLast(outline); // Add Page node doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "ApplyBulletsOnText_out.one"; doc.Save(dataDir); // ExEnd:ApplyBulletsOnText Console.WriteLine("\nBullets applied successfully on a text.\nFile saved at " + dataDir); }
public IntListItem(RichText text, int i) { Text = text; Int = i; }
public static void Run() { // ExStart:CreateDocWithFormattedRichText // ExFor:SaveOptions.PageIndex // ExFor:RichText.Append(System.String,TextStyle) // ExSummary:Shows how to create a document with formatted rich text. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_LoadingAndSaving(); // Create an object of the Document class Document doc = new Document(); // Initialize Page class object Page page = new Page(); // Initialize Title class object Title title = new Title(); // Initialize TextStyle class object and set formatting properties ParagraphStyle defaultTextStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; RichText titleText = new RichText() { ParagraphStyle = defaultTextStyle }.Append("Title!"); Outline outline = new Outline() { VerticalOffset = 100, HorizontalOffset = 100 }; OutlineElement outlineElem = new OutlineElement(); TextStyle textStyleForHelloWord = new TextStyle { FontColor = Color.Red, FontName = "Arial", FontSize = 10, }; TextStyle textStyleForOneNoteWord = new TextStyle { FontColor = Color.Green, FontName = "Calibri", FontSize = 10, IsItalic = true, }; TextStyle textStyleForTextWord = new TextStyle { FontColor = Color.Blue, FontName = "Arial", FontSize = 15, IsBold = true, IsItalic = true, }; RichText text = new RichText() { ParagraphStyle = defaultTextStyle } .Append("Hello", textStyleForHelloWord) .Append(" OneNote", textStyleForOneNoteWord) .Append(" text", textStyleForTextWord) .Append("!", TextStyle.Default); title.TitleText = titleText; // Set page title page.Title = title; // Add RichText node outlineElem.AppendChildLast(text); // Add OutlineElement node outline.AppendChildLast(outlineElem); // Add Outline node page.AppendChildLast(outline); // Add Page node doc.AppendChildLast(page); // Save OneNote document dataDir = dataDir + "CreateDocWithFormattedRichText_out.one"; doc.Save(dataDir); // ExEnd:CreateDocWithFormattedRichText Console.WriteLine("\nOneNote document created successfully with formatted rich text.\nFile saved at " + dataDir); }
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 override Widget build(BuildContext context) { D.assert(this.textDirection != null || WidgetsD.debugCheckHasDirectionality(context)); TextDirection textDirection = this.textDirection ?? Directionality.of(context); IconThemeData iconTheme = IconTheme.of(context); float iconSize = size ?? iconTheme.size.Value; if (icon == null) { return(new SizedBox(width: iconSize, height: iconSize)); } float iconOpacity = iconTheme.opacity.Value; Color iconColor = color ?? iconTheme.color; if (iconOpacity != 1.0) { iconColor = iconColor.withOpacity(iconColor.opacity * iconOpacity); } Widget iconWidget = new RichText( overflow: TextOverflow.visible, // Never clip. textDirection: textDirection, // Since we already fetched it for the assert... text: new TextSpan( text: new string(new[] { (char)icon.codePoint }), style: new TextStyle( inherit: false, color: iconColor, fontSize: iconSize, fontFamily: icon.fontFamily ) ) ); var matrix = Matrix4.identity(); matrix.scale(-1.0f, 1.0f, 1.0f); if (icon.matchTextDirection) { switch (textDirection) { case TextDirection.rtl: iconWidget = new Transform( transform: matrix, alignment: Alignment.center, transformHitTests: false, child: iconWidget ); break; case TextDirection.ltr: break; } } return(new SizedBox( width: iconSize, height: iconSize, child: new Center( child: iconWidget ) )); }
/// <summary> /// Provides access to HudMain properties via RHF API /// </summary> private object GetOrSetMember(object data, int memberEnum) { switch ((HudMainAccessors)memberEnum) { case HudMainAccessors.ScreenWidth: return(ScreenWidth); case HudMainAccessors.ScreenHeight: return(ScreenHeight); case HudMainAccessors.AspectRatio: return(AspectRatio); case HudMainAccessors.ResScale: return(ResScale); case HudMainAccessors.Fov: return(Fov); case HudMainAccessors.FovScale: return(FovScale); case HudMainAccessors.PixelToWorldTransform: return(PixelToWorld); case HudMainAccessors.UiBkOpacity: return(UiBkOpacity); case HudMainAccessors.ClipBoard: { if (data == null) { return(ClipBoard.apiData); } else { ClipBoard = new RichText(data as List <RichStringMembers>); } break; } case HudMainAccessors.EnableCursor: { if (data == null) { return(_enableCursor); } else { _enableCursor = (bool)data; } break; } case HudMainAccessors.RefreshDrawList: { if (data == null) { return(RefreshDrawList); } else { _refreshDrawList = (bool)data; } break; } case HudMainAccessors.GetUpdateAccessors: { if (data == null) { return(GetUpdateAccessors); } else { GetUpdateAccessors = data as Action <List <HudUpdateAccessors>, byte>; _refreshDrawList = true; } break; } case HudMainAccessors.GetFocusOffset: return(GetFocusOffset(data as Action <byte>)); case HudMainAccessors.GetPixelSpaceFunc: return(instance._root.GetHudSpaceFunc); case HudMainAccessors.GetPixelSpaceOriginFunc: return(instance._root.GetNodeOriginFunc); case HudMainAccessors.GetInputFocus: GetInputFocus(data as Action); break; case HudMainAccessors.InputMode: return(InputMode); } return(null); }
public ProductionListItem(Production prod, int turnsLeft, ProductionListItem_Mode mode, DataManager dataManager) { DisplayMode = mode; Production = prod; switch (mode) { case ProductionListItem_Mode.ProductionList: ProductionProgress = $"$(production) {turnsLeft} turns".ToRichText(); foreach (RichTextSection section in ProductionProgress.Sections) { section.Scale = 0.75f; } break; case ProductionListItem_Mode.ProductionQueue: ProductionProgress = $"$(production) {Production.Progress}/{Production.Cost} ({(Production.Progress / (float)Production.Cost * 100).ToString("0")}%) - {turnsLeft} turns left".ToRichText(); foreach (RichTextSection section in ProductionProgress.Sections) { section.Scale = 0.75f; } break; } float prodToGold = 5f; // TODOD replace this with a game wide (config?) var // format the items text to show construction information //string suffix = ""; //if (turnsLeft != -1) // suffix = $" - {turnsLeft} turns"; switch (prod.ProductionType) { case ProductionType.UNIT: //Text = $"{Unit.FormatName(Production.Name)}{suffix}".ToRichText(); ProductionName = Unit.FormatName(Production.Name).ToRichText(); Unit unit = dataManager.Unit.GetUnit(prod.Name); SpriteAtlas unitAtlas = Engine.Instance.Content.GetAsset <SpriteAtlas>(unit.IconAtlas); Icon = new Sprite(unitAtlas, unit.IconKey); RichText unitToolTipText; if (unit.Range > 1) { unitToolTipText = $"Cost: {unit.Cost} $(production) / {unit.Cost * prodToGold} $(gold)\n$(movement) Movement: {unit.Movement}\n$(sight) Sight: {unit.Sight}\n$(strength) Ranged Strenght: {unit.RangedStrength}\n$(range) Range: {unit.Range}".ToRichText(); } else { unitToolTipText = $"Cost: {unit.Cost} $(production) / {unit.Cost * prodToGold} $(gold)\n$(movement) Movement: {unit.Movement}\n$(sight) Sight: {unit.Sight}\n$(strength) Combat Strenght: {unit.CombatStrength}".ToRichText(); } ToolTip = new ToolTip(unitToolTipText, 400); break; case ProductionType.BUILDING: //Text = $"{Building.FormatName(Production.Name)}{suffix}".ToRichText(); ProductionName = Building.FormatName(Production.Name).ToRichText(); Building building = dataManager.Building.GetBuilding(prod.Name); SpriteAtlas buildingAtlas = Engine.Instance.Content.GetAsset <SpriteAtlas>(building.IconAtlas); Icon = new Sprite(buildingAtlas, building.IconKey); RichText buildingToolTipText = $"Cost: {building.Cost} $(production) / {building.Cost * prodToGold} $(gold)\n{building.Description}".ToRichText(); ToolTip = new ToolTip(buildingToolTipText, 400); break; } }
public StringListItem(RichText text, string s) { Text = text; String = s; }
public string GetText() { KeyCode c = InputManager.GetInput(InputName); return(RichText.InBold(GetDisplayName()) + " : " + c); }
public void RichText_Encode_2() { Assert.AreEqual("Hello,\\'0aWorld!", RichText.Encode("Hello,\nWorld!", null)); Assert.AreEqual("Copyright \\'a9 2017", RichText.Encode("Copyright © 2017", null)); }
private ILookupItem CreateMethodItem(CSharpCodeCompletionContext context, UnityEventFunction eventFunction, IClassLikeDeclaration declaration, bool hasReturnType, AccessRights accessRights) { if (CSharpLanguage.Instance == null) { return(null); } // Only show the modifier in the list text if it's not already specified and there isn't a return type, in // which case we default to `private`. E.g. if someone types `OnAnim`, then show `private void OnAnimate...` // but if they type `void OnAnim`, they don't want a modifier, and if they type `public void OnAnim` then // they want to use `public` var showModifier = false; if (!hasReturnType && accessRights == AccessRights.NONE) { showModifier = true; accessRights = AccessRights.PRIVATE; } var factory = CSharpElementFactory.GetInstance(declaration, false); var methodDeclaration = eventFunction.CreateDeclaration(factory, declaration, accessRights); if (methodDeclaration.DeclaredElement == null) { return(null); } var instance = new DeclaredElementInstance(methodDeclaration.DeclaredElement); var declaredElementInfo = new DeclaredElementInfoWithoutParameterInfo(methodDeclaration.DeclaredName, instance, CSharpLanguage.Instance, context.BasicContext.LookupItemsOwner, context) { Ranges = context.CompletionRanges }; // This is effectively the same as GenerateMemberPresentation, but without the overhead that comes // with the flexibility of formatting any time of declared element. We just hard code the format var predefinedType = context.PsiModule.GetPredefinedType(); var parameters = string.Empty; if (eventFunction.Parameters.Length > 0) { var sb = new StringBuilder(); for (var i = 0; i < eventFunction.Parameters.Length; i++) { if (i > 0) { sb.Append(", "); } var parameter = eventFunction.Parameters[i]; var type = predefinedType.TryGetType(parameter.ClrTypeName, NullableAnnotation.Unknown); var typeName = type?.GetPresentableName(CSharpLanguage.Instance) ?? parameter.ClrTypeName.ShortName; sb.AppendFormat("{0}{1}{2}", parameter.IsByRef ? "out" : string.Empty, typeName, parameter.IsArray ? "[]" : string.Empty); } parameters = sb.ToString(); } var text = $"{eventFunction.Name}({parameters})"; var parameterOffset = eventFunction.Name.Length; var modifier = showModifier ? CSharpDeclaredElementPresenter.Instance.Format(accessRights) + " " : string.Empty; var psiIconManager = context.BasicContext.LookupItemsOwner.Services.PsiIconManager; return(LookupItemFactory.CreateLookupItem(declaredElementInfo) .WithPresentation(item => { var displayName = new RichText($"{modifier}{text} {{ ... }}"); // GenerateMemberPresentation marks everything as bold, and the parameters + block syntax as not important var parameterStartOffset = modifier.Length + parameterOffset; LookupUtil.MarkAsNotImportant(displayName, TextRange.FromLength(parameterStartOffset, displayName.Length - parameterStartOffset)); LookupUtil.AddEmphasize(displayName, new TextRange(modifier.Length, displayName.Length)); var image = psiIconManager.GetImage(methodDeclaration.DeclaredElement, methodDeclaration.DeclaredElement.PresentationLanguage, true); var marker = item.Info.Ranges.CreateVisualReplaceRangeMarker(); return new SimplePresentation(displayName, image, marker); }) .WithBehavior(_ => new UnityEventFunctionBehavior(myShellLocks, declaredElementInfo, eventFunction, accessRights)) .WithMatcher(_ => new ShiftedDeclaredElementMatcher(eventFunction.Name, modifier.Length, declaredElementInfo, context.BasicContext.IdentifierMatchingStyle))); }
public override Widget build(BuildContext context) { string text; if (this.channel.lastMessage != null) { if (this.channel.lastMessage.deleted) { text = "[此消息已被删除]"; } else if (this.channel.lastMessage.type == ChannelMessageType.image) { text = "[图片]"; } else if (this.channel.lastMessage.type == ChannelMessageType.file) { text = "[文件]"; } else { text = this.channel.lastMessage.content ?? ""; } } else { text = ""; } var contentTextSpans = new List <TextSpan>(); if (this.channel.lastMessage.author?.fullName.isNotEmpty() ?? text.isNotEmpty() && this.channel.lastMessage.author.id != this.myUserId) { contentTextSpans.Add(new TextSpan( $"{this.channel.lastMessage.author?.fullName}: ", style: CTextStyle.PRegularBody4 )); } contentTextSpans.AddRange(MessageUtils.messageWithMarkdownToTextSpans( content: text, mentions: this.channel.lastMessage?.mentions, this.channel.lastMessage?.mentionEveryone ?? false, null, bodyStyle: CTextStyle.PRegularBody4, linkStyle: CTextStyle.PRegularBody4 )); Widget message = new RichText( text: new TextSpan( (this.channel.atMe || this.channel.atAll) && this.channel.unread > 0 ? "[有人@我] " : "", style: CTextStyle.PRegularError, children: contentTextSpans ), overflow: TextOverflow.ellipsis, maxLines: 1 ); // Don't show the time if nonce is 0, i.e. the time is not loaded yet. // Otherwise, the time would be like 0001/01/01 8:00 string timeString = this.channel.lastMessage?.nonce != 0 ? this.channel.lastMessage?.time.DateTimeString() ?? "" : ""; Widget titleLine = new Container( padding: EdgeInsets.only(16), child: new Row( crossAxisAlignment: CrossAxisAlignment.start, children: new List <Widget> { new Expanded( child: new Text( data: this.channel.name, style: CTextStyle.PLargeMedium, maxLines: 1, overflow: TextOverflow.ellipsis ) ), new Container(width: 16), new Text( data: timeString, style: CTextStyle.PSmallBody4 ) } ) ); return(new GestureDetector( onTap: this.onTap, child: new Container( color: this.channel.isTop ? CColors.PrimaryBlue.withOpacity(0.04f) : CColors.White, height: 72, padding: EdgeInsets.symmetric(12, 16), child: new Row( children: new List <Widget> { new PlaceholderImage( this.channel?.thumbnail ?? "", 48, 48, 4, fit: BoxFit.cover, true, CColorUtils.GetSpecificDarkColorFromId(id: this.channel?.id) ), new Expanded( child: new Column( children: new List <Widget> { titleLine, new Row( children: new List <Widget> { new Container(width: 16), new Expanded( child: message ), new NotificationDot( this.channel.unread > 0 ? this.channel.mentioned > 0 ? $"{this.channel.mentioned}" : "" : null, margin: EdgeInsets.only(16) ) } ) } ) ) } ) ) )); }
public PostfixTemplatePresentation([NotNull] RichText displayName) { myDisplayName = displayName; }
public PostfixTemplatePresentation([NotNull] PostfixTemplateInfo info) { myDisplayName = info.Text.ToLowerInvariant(); }
/// <summary> /// Writes the RichText instance. /// </summary> public void Write(RichText richText) { Write(richText, 0, richText.Length); }
private void OnRichTextChanged([CanBeNull] RichText newValue) { _richTextSpan = newValue?.ToSpan(); SetInlines(); }
public static void Run() { // ExStart:CreateDocWithRootAndSubPages // ExFor:Page // ExFor:Page.Level // ExSummary:Shows how to add a page with a subpage. // The path to the documents directory. string dataDir = RunExamples.GetDataDir_Pages(); // Create an object of the Document class Document doc = new Document(); // Initialize Page class object and set its level Aspose.Note.Page page1 = new Aspose.Note.Page(doc) { Level = 1 }; // Initialize Page class object and set its level Aspose.Note.Page page2 = new Aspose.Note.Page(doc) { Level = 2 }; // Initialize Page class object and set its level Aspose.Note.Page page3 = new Aspose.Note.Page(doc) { Level = 1 }; /*---------- Adding nodes to first Page ----------*/ Outline outline = new Outline(doc); OutlineElement outlineElem = new OutlineElement(doc); ParagraphStyle textStyle = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; RichText text = new RichText(doc) { Text = "First page.", ParagraphStyle = textStyle }; outlineElem.AppendChildLast(text); outline.AppendChildLast(outlineElem); page1.AppendChildLast(outline); /*---------- Adding nodes to second Page ----------*/ var outline2 = new Outline(doc); var outlineElem2 = new OutlineElement(doc); var textStyle2 = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; var text2 = new RichText(doc) { Text = "Second page.", ParagraphStyle = textStyle2 }; outlineElem2.AppendChildLast(text2); outline2.AppendChildLast(outlineElem2); page2.AppendChildLast(outline2); /*---------- Adding nodes to third Page ----------*/ var outline3 = new Outline(doc); var outlineElem3 = new OutlineElement(doc); var textStyle3 = new ParagraphStyle { FontColor = Color.Black, FontName = "Arial", FontSize = 10 }; var text3 = new RichText(doc) { Text = "Third page.", ParagraphStyle = textStyle3 }; outlineElem3.AppendChildLast(text3); outline3.AppendChildLast(outlineElem3); page3.AppendChildLast(outline3); /*---------- Add pages to the OneNote Document ----------*/ doc.AppendChildLast(page1); doc.AppendChildLast(page2); doc.AppendChildLast(page3); // Save OneNote document dataDir = dataDir + "CreateDocWithRootAndSubPages_out.one"; doc.Save(dataDir); // ExEnd:CreateDocWithRootAndSubPages Console.WriteLine("\nOneNote document created successfully with root and sub level pages.\nFile saved at " + dataDir); }
// Added To Scene: Initialise individual elements public override void Added() { base.Added(); // Panel image Image_Background = new Entity_Image(X, Y, "", false); { Image_Background.NineSlice(Program.PATH_PA + "media/ui/main/shared/img/panel/img_menu_panel.png", 24, 24, 256, 364); //Image_Background.SetTarget( center ); Image_Background.Layer = Helper.Layer_UI; } Scene.Instance.Add(Image_Background); // Icon image Image_Icon = new Entity_Image(X, Y - 96, IconFile); { //Image_Icon.SetTarget( center ); } Scene.Instance.Add(Image_Icon); // Card name Text_Label = new Text(Label, Program.Font, 20); { Text_Label.CenterOrigin(); Text_Label.SetPosition(new Vector2(0, 64)); Text_Label.Color = Color.Green; } Image_Icon.AddGraphic(Text_Label); // Description Text_Description = new RichText(Description, Program.Font, 12); { Text_Description.SetPosition(new Vector2(-128 + 16, 96)); Text_Description.TextWidth = 256 - 32; Text_Description.WordWrap = true; } Image_Icon.AddGraphic(Text_Description); // Panel image Image_Button_Background = new Entity_Image(X, Y + 140, "", false); { Image_Button_Background.NineSlice(Program.PATH_PA + "media/ui/main/shared/img/panel/img_panel_std_black.png", 120, 86, 326, 156); //Image_Button_Background.SetTarget( center ); } Scene.Instance.Add(Image_Button_Background); // Button Choose Button_Choose = new Entity_UI_Button(); { Button_Choose.Label = "DOWNLOAD"; Vector2 pos = new Vector2(X, Y + 134); Button_Choose.Center = Vector2.Zero; Button_Choose.Offset.Y = -1; Button_Choose.ButtonBounds = new Vector4(pos.X, pos.Y, 196, 48); Button_Choose.Scroll = new Vector2(1, 1); Button_Choose.OnPressed = delegate(Entity_UI_Button self) { self.Image.image.Color = self.Colour_Hover * Color.Gray; AudioManager.Instance.PlaySound("resources/audio/ui_click.wav"); }; Button_Choose.OnReleased = delegate(Entity_UI_Button self) { NetworkManager.SendPickCard(Label); Helper.GetGameScene().HideCards(); AudioManager.Instance.PlaySound("resources/audio/ui_click.wav"); }; Button_Choose.Layer = Helper.Layer_UI; } Scene.Instance.Add(Button_Choose); Layer = Helper.Layer_UI; }
public static Button CreateFoldButton(string text) { #if WIN const int FontSize = 36; const int SpaceAfter = -16; const float Height = 40.0f; #else const int FontSize = 64; const int SpaceAfter = -32; const float Height = 75.0f; #endif var b = new Button { Text = text, Height = Height, MinHeight = Height }; var textPresenter = new RichText { Id = "TextPresenter", Nodes = { new TextStyle { Font = new SerializableFont("Text"), Size = FontSize, Tag = "1", SpaceAfter = SpaceAfter } }, Height = Height, HAlignment = HAlignment.Left, VAlignment = VAlignment.Center }; var bg = new Image { Id = "bg", Shader = ShaderId.Silhuette, Height = Height, Anchors = Anchors.LeftRightTopBottom, Color = Color4.White }; var arrow = new RichText { Id = "arrow", Nodes = { new TextStyle { Font = new SerializableFont("Text"), Tag = "1", Size = FontSize, } }, Height = Height, VAlignment = VAlignment.Center, HAlignment = HAlignment.Right, MinWidth = Height, MaxWidth = Height }; var padding = new Image { Id = "padding", MinWidth = 0, MaxWidth = 0, Shader = ShaderId.Silhuette, Color = Color4.DarkGray }; var w = new Widget { Height = Height, Anchors = Anchors.LeftRightTopBottom, Layout = new HBoxLayout() }; w.AddNode(padding); w.AddNode(arrow); w.AddNode(textPresenter); b.AddNode(w); b.AddNode(bg); return(b); }
protected void Header([NotNull] RichText text) { SetIndent(AddHeader(text), myCurrentIndent); }
private void DrawWorldRecord() { DrawEntryHeader("PLMWINF_WorldRecords".Translate(), backgroundColor: Color.yellow); if (_gameData.WorldData.WorldCharacteristics == null || _gameData.WorldData.WorldCharacteristics.Count == 0) { //Log.Error("[PrepareLanding] TabInfo.BuildWorldRecords: No Info"); return; } // default line height const float gapLineHeight = 4f; // add a gap before the scroll view ListingStandard.Gap(gapLineHeight); /* * Calculate heights */ // height of the scrollable outer Rect (visible portion of the scroll view, not the 'virtual' one) var maxScrollViewOuterHeight = InRect.height - ListingStandard.CurHeight - DefaultElementHeight; // height of the 'virtual' portion of the scroll view var numElements = _gameData.WorldData.WorldCharacteristics.Count * 3; // 1 label + 2 elements (highest + lowest) = 3 var scrollableViewHeight = (numElements * DefaultElementHeight) + (_gameData.WorldData.WorldCharacteristics.Count * gapLineHeight); /* * Scroll view */ var innerLs = ListingStandard.BeginScrollView(maxScrollViewOuterHeight, scrollableViewHeight, ref _scrollPosWorldRecords, 16f); var selectedTileIndex = 0; foreach (var characteristicData in _gameData.WorldData.WorldCharacteristics) { var characteristicName = characteristicData.CharacteristicName; innerLs.Label(RichText.Bold(RichText.Color($"{characteristicName}:", Color.cyan))); // there might be no characteristics if (characteristicData.WorldTilesCharacteristics.Count == 0) { innerLs.Label("No Info [DisableWorldData enabled]"); continue; } /* * lowest */ var lowestCharacteristicKvp = characteristicData.WorldTilesCharacteristics.First(); // we need to follow user preference for temperature. var value = characteristicData.Characteristic == MostLeastCharacteristic.Temperature ? GenTemperature.CelsiusTo(lowestCharacteristicKvp.Value, Prefs.TemperatureMode) : lowestCharacteristicKvp.Value; var vectorLongLat = Find.WorldGrid.LongLatOf(lowestCharacteristicKvp.Key); var textLowest = $"{"PLMWINF_WorldLowest".Translate()} {characteristicName}: {value:F1} {characteristicData.CharacteristicMeasureUnit} [{lowestCharacteristicKvp.Key}; {vectorLongLat.y.ToStringLatitude()} - {vectorLongLat.x.ToStringLongitude()}]"; var labelRect = innerLs.GetRect(DefaultElementHeight); var selected = selectedTileIndex == _worldRecordSelectedTileIndex; if (Core.Gui.Widgets.LabelSelectable(labelRect, textLowest, ref selected, TextAnchor.MiddleLeft)) { // go to the location of the selected tile _worldRecordSelectedTileIndex = selectedTileIndex; Find.WorldInterface.SelectedTile = lowestCharacteristicKvp.Key; Find.WorldCameraDriver.JumpTo(Find.WorldGrid.GetTileCenter(Find.WorldInterface.SelectedTile)); } selectedTileIndex++; /* * highest */ var highestCharacteristicKvp = characteristicData.WorldTilesCharacteristics.Last(); // we need to follow user preference for temperature. value = characteristicData.Characteristic == MostLeastCharacteristic.Temperature ? GenTemperature.CelsiusTo(highestCharacteristicKvp.Value, Prefs.TemperatureMode) : highestCharacteristicKvp.Value; vectorLongLat = Find.WorldGrid.LongLatOf(highestCharacteristicKvp.Key); var textHighest = $"{"PLMWINF_WorldHighest".Translate()} {characteristicName}: {value:F1} {characteristicData.CharacteristicMeasureUnit} [{highestCharacteristicKvp.Key}; {vectorLongLat.y.ToStringLatitude()} - {vectorLongLat.x.ToStringLongitude()}]"; labelRect = innerLs.GetRect(DefaultElementHeight); selected = selectedTileIndex == _worldRecordSelectedTileIndex; if (Core.Gui.Widgets.LabelSelectable(labelRect, textHighest, ref selected, TextAnchor.MiddleLeft)) { // go to the location of the selected tile _worldRecordSelectedTileIndex = selectedTileIndex; Find.WorldInterface.SelectedTile = highestCharacteristicKvp.Key; Find.WorldCameraDriver.JumpTo(Find.WorldGrid.GetTileCenter(Find.WorldInterface.SelectedTile)); } selectedTileIndex++; // add a thin line between each label innerLs.GapLine(gapLineHeight); } ListingStandard.EndScrollView(innerLs); }
private void UpdateLines(RichText tas, Range range) { if (updating) { return; } updating = true; int start = range.Start.iLine; int end = range.End.iLine; if (start > end) { int temp = start; start = end; end = temp; } int originalStart = start; bool modified = false; StringBuilder sb = new StringBuilder(); Place place = new Place(0, end); while (start <= end) { InputRecord old = Lines.Count > start ? Lines[start] : null; string text = tas[start++].Text; InputRecord input = new InputRecord(text); if (old != null) { totalFrames -= old.Frames; string line = input.ToString(); if (text != line) { if (old.Frames == 0 && input.Frames == 0 && old.ZeroPadding == input.ZeroPadding && old.Equals(input) && line.Length >= text.Length) { line = string.Empty; } Range oldRange = tas.Selection; if (!string.IsNullOrEmpty(line)) { int index = oldRange.Start.iChar + line.Length - text.Length; if (index < 0) { index = 0; } if (index > 4) { index = 4; } if (old.Frames == input.Frames && old.ZeroPadding == input.ZeroPadding) { index = 4; } place = new Place(index, start - 1); } modified = true; } else { place = new Place(4, start - 1); } text = line; Lines[start - 1] = input; } else { place = new Place(text.Length, start - 1); } if (start <= end) { sb.AppendLine(text); } else { sb.Append(text); } totalFrames += input.Frames; } if (modified) { tas.Selection = new Range(tas, 0, originalStart, tas[end].Count, end); tas.SelectedText = sb.ToString(); tas.Selection = new Range(tas, place.iChar, end, place.iChar, end); Text = titleBarText + " ***"; } UpdateStatusBar(); updating = false; }
/// <summary> /// Builds content for internal fields /// </summary> /// <param name="subitem"></param> /// <param name="resultText"></param> private void InternalFieldContentBuilder(Item subitem, StringBuilder resultText) { //Get all the fields for an item var fields = subitem.Fields; fields.ReadAll(); fields.Sort(); foreach (Field field in fields) { if (!field.Name.StartsWith("__")) { string fieldSource = DetermineFieldSource(field); switch (field.Type) { case "Droptree": var treeCtrl = new Tree(); treeCtrl.ItemID = subitem.ID.ToString(); treeCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); treeCtrl.Source = field.Source; treeCtrl.Disabled = Disabled; var sources = GetSources(subitem, field); var sourceId = Guid.Empty; if (sources.Any()) { sourceId = sources[0].ID.Guid; } Sitecore.Context.ClientPage.AddControl(this, treeCtrl); treeCtrl.Value = field.Value; resultText.AppendFormat(Prototypes.Tree, field.DisplayName, treeCtrl.RenderAsText(), treeCtrl.ID, field.ID, sourceId, fieldSource); break; case "File": var fileCtrl = new File(); fileCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); Sitecore.Context.ClientPage.AddControl(this, fileCtrl); fileCtrl.SetValue(field.Value); fileCtrl.Disabled = Disabled; resultText.AppendFormat(Prototypes.StandardWrapper, field.DisplayName, fileCtrl.RenderAsText(), fileCtrl.ID, field.ID, RenderMenuButtons(fileCtrl.ID, field, ReadOnly), "file", fieldSource); break; case "Image": var imageCtrl = new Sitecore.Shell.Applications.ContentEditor.Image(); imageCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); Sitecore.Context.ClientPage.AddControl(this, imageCtrl); imageCtrl.ItemLanguage = ItemLanguage; imageCtrl.ItemVersion = ItemVersion; imageCtrl.SetValue(field.Value); imageCtrl.Disabled = Disabled; resultText.AppendFormat(Prototypes.StandardWrapper, field.DisplayName, imageCtrl.RenderAsText(), imageCtrl.ID, field.ID, RenderMenuButtons(imageCtrl.ID, field, ReadOnly), "image", fieldSource); break; case "Multilist": var multiListCtrl = new MultilistEx(); multiListCtrl.ItemID = subitem.ID.ToString(); multiListCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); multiListCtrl.SetValue(field.Value); multiListCtrl.Source = field.Source; Sitecore.Context.ClientPage.AddControl(this, multiListCtrl); multiListCtrl.Disabled = Disabled; multiListCtrl.ItemLanguage = subitem.Language.Name; resultText.AppendFormat(Prototypes.StandardWrapper, field.DisplayName, multiListCtrl.RenderAsText(), multiListCtrl.ID, field.ID, RenderMenuButtons(multiListCtrl.ID, field, ReadOnly), "multilist", fieldSource); break; case "Treelist": var treelistCtrl = new TreeList(); treelistCtrl.ItemID = subitem.ID.ToString(); treelistCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); treelistCtrl.ItemLanguage = ItemLanguage; treelistCtrl.SetValue(field.Value); treelistCtrl.Source = field.Source; treelistCtrl.Disabled = Disabled; Sitecore.Context.ClientPage.AddControl(this, treelistCtrl); resultText.AppendFormat(Prototypes.StandardWrapper, field.DisplayName, treelistCtrl.RenderAsText(), treelistCtrl.ID, field.ID, RenderMenuButtons(treelistCtrl.ID, field, ReadOnly), "treelist", fieldSource); break; case "Datetime": case "Date": var dateCtrl = field.Type == "Date" ? new Date() : new Sitecore.Shell.Applications.ContentEditor.DateTime(); dateCtrl.ItemID = subitem.ID.ToString(); dateCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); dateCtrl.Disabled = Disabled; Sitecore.Context.ClientPage.AddControl(this, dateCtrl); dateCtrl.SetValue(field.Value); resultText.AppendFormat(Prototypes.Date, field.DisplayName, dateCtrl.RenderAsText(), dateCtrl.ID, field.ID, RenderMenuButtons(dateCtrl.ID, field, ReadOnly), fieldSource); break; case "Rich Text": var richTextCtrl = new RichText(); richTextCtrl.ItemID = subitem.ID.ToString(); richTextCtrl.ItemLanguage = ItemLanguage; richTextCtrl.ItemVersion = subitem.Version.ToString(); richTextCtrl.FieldID = field.ID.ToString(); richTextCtrl.ID = string.Format("ExpressSubitem_{0:N}{1:N}", field.ID.Guid, subitem.ID.Guid); richTextCtrl.Disabled = Disabled; Sitecore.Context.ClientPage.AddControl(this, richTextCtrl); // Fixing Sitecore bug for no value field if (field.Value == "__#!$No value$!#__") { using (new SecurityDisabler()) { using (new EditContext(subitem)) { field.Value = ""; } } } richTextCtrl.Value = field.Value; resultText.AppendFormat(Prototypes.RichText, field.DisplayName, richTextCtrl.RenderAsText(), richTextCtrl.ID, field.ID, RenderMenuButtons(richTextCtrl.ID, field, ReadOnly), fieldSource); break; case "Single-Line Text": case "Integer": resultText.AppendFormat(Prototypes.TextBox, field.DisplayName, field.ID, field.Value, Disabled ? "disabled='disabled'" : "", fieldSource); break; case "Droplink": bool selectionInList; string options = BuildDropdownOptions(subitem, field, out selectionInList); string errorMessage = ""; if (!selectionInList) { errorMessage = @"<DIV style=""PADDING-BOTTOM: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; COLOR: #999999; PADDING-TOP: 2px"">The field contains a value that is not in the selection list.</DIV>"; } resultText.AppendFormat(Prototypes.Dropdown, field.DisplayName, field.ID, options, Disabled ? "disabled='disabled'" : "", errorMessage, fieldSource); break; case "Checkbox": var @checked = ((CheckboxField)field).Checked; resultText.AppendFormat(Prototypes.Checkbox, field.DisplayName, field.ID, @checked ? "checked" : "", Disabled ? "disabled='disabled'" : "", fieldSource); break; default: resultText.AppendFormat("<div class=\"unknown-field\">Unknown field type of \"{0}\" for field \"{1}\"</div>", field.Type, field.Name); break; } } } }
protected virtual object GetPropertyValue(Type modelPropertyType, IEnumerable <XmlElement> htmlElements) { bool isListProperty = modelPropertyType.IsGenericList(); Type targetType = modelPropertyType.GetUnderlyingGenericListType() ?? modelPropertyType; object result; if (targetType == typeof(string)) { if (isListProperty) { result = htmlElements.Select(e => e.InnerText).ToList(); } else { result = htmlElements.First().InnerText; } } else if (targetType == typeof(RichText)) { if (isListProperty) { result = htmlElements.Select(e => new RichText(e.InnerXml)).ToList(); } else { result = new RichText(htmlElements.First().InnerXml); } } else if (targetType == typeof(Link)) { if (isListProperty) { result = htmlElements.Select(e => BuildLink(e)).ToList(); } else { result = BuildLink(htmlElements.First()); } } else if (typeof(EntityModel).IsAssignableFrom(targetType)) { if (isListProperty) { IList stronglyTypedModels = targetType.CreateGenericList(); foreach (XmlElement htmlElement in htmlElements) { stronglyTypedModels.Add(BuildStronglyTypedTopic(targetType, htmlElement)); } result = stronglyTypedModels; } else { result = BuildStronglyTypedTopic(targetType, htmlElements.First()); } } else { throw new DxaException($"Unexpected property type '{targetType.FullName}'"); } return(result); }
public CSharpColorizer([NotNull] RichText richText, [NotNull] TextStyleHighlighterManager textStyleHighlighterManager, [NotNull] CodeAnnotationsCache codeAnnotationsCache, bool useReSharperColors) { _richText = richText; _textStyleHighlighterManager = textStyleHighlighterManager; _codeAnnotationsCache = codeAnnotationsCache; _useReSharperColors = useReSharperColors; }
public void ReportMessage(RichText message) { engine.ReportMessage(this, message); }
public bool? IsElementObsolete(IDeclaredElement element, out RichTextBlock obsoleteDescription, DeclaredElementDescriptionStyle style) { obsoleteDescription = null; var obsoletable = element as IObsoletable; if (obsoletable == null) return null; if (!obsoletable.Obsolete && !obsoletable.NonStandard) return false; obsoleteDescription = new RichTextBlock(); var richText = new RichText(); if (obsoletable.Obsolete) richText.Append("Obsolete!", new TextStyle(FontStyle.Bold)); else if (obsoletable.NonStandard) richText.Append("Non-standard!", new TextStyle(FontStyle.Bold)); obsoleteDescription.Add(richText); return true; }
private static void ShowTooltip(IDataContext context, ISolution solution, RichText tooltip) { var shellLocks = solution.GetComponent<IShellLocks>(); var tooltipManager = solution.GetComponent<ITooltipManager>(); tooltipManager.Show(tooltip, lifetime => { var windowContextSource = context.GetData(UI.DataConstants.PopupWindowContextSource); if (windowContextSource != null) { var windowContext = windowContextSource.Create(lifetime); var ctxTextControl = windowContext as TextControlPopupWindowContext; return ctxTextControl == null ? windowContext : ctxTextControl.OverrideLayouter(lifetime, lifetimeLayouter => new DockingLayouter(lifetimeLayouter, new TextControlAnchoringRect(lifetimeLayouter, ctxTextControl.TextControl, ctxTextControl.TextControl. Caret.Offset(), shellLocks), Anchoring2D.AnchorTopOrBottom)); } return solution.GetComponent<MainWindowPopupWindowContext>().Create(lifetime); }); }