private static void PutDate(InlineCollection inline, DateTime time) { Run text = new Run(time.ToString("M/d")); inline.Add(text); inline.Add(new LineBreak()); }
private static bool AddLineBreakIfNeeded(InlineCollection inlines) { if (inlines.Count <= 0) { return(false); } Inline lastInline = inlines[inlines.Count - 1]; while ((lastInline is Span)) { var span = (Span)lastInline; if (span.Inlines.Count > 0) { lastInline = span.Inlines[span.Inlines.Count - 1]; } } if (lastInline is LineBreak) { return(false); } inlines.Add(new LineBreak()); return(true); }
public static void Format(string message, InlineCollection collection) { UrlMatch urlMatch; int cur = 0; while (UrlMatcher.TryGetMatch(message, cur, out urlMatch)) { string before = message.Substring(cur, urlMatch.Offset - cur); if (before.Length > 0) collection.Add(new Run(before)); var matchRun = new Run(urlMatch.Text); try { Hyperlink link = new Hyperlink(matchRun); link.NavigateUri = new Uri(urlMatch.Text); link.RequestNavigate += hlink_RequestNavigate; collection.Add(link); } catch { collection.Add(matchRun); } cur = urlMatch.Offset + urlMatch.Text.Length; } string ending = message.Substring(cur); if (ending.Length > 0) collection.Add(new Run(ending)); }
/// <summary> /// Renders all of the children for the given element. /// </summary> /// <param name="rootElemnet">The root element to render children of</param> /// <param name="currentInlines">The inlines where they should go</param> /// <param name="trimTextStart">If true the first text box start will be trimed so there is no leading space</param> private void RenderInlineChildren(MarkdownElement rootElemnet, InlineCollection currentInlines, ref bool trimTextStart) { foreach (MarkdownInline element in rootElemnet.Children) { RendnerInline(element, currentInlines, ref trimTextStart); } }
static bool AddLineBreakIfNeeded(InlineCollection inlines) { if (inlines.Count <= 0) { return(false); } var lastInline = inlines[inlines.Count - 1]; while ((lastInline is Windows.UI.Xaml.Documents.Span)) { var span = (Windows.UI.Xaml.Documents.Span)lastInline; if (span.Inlines.Count > 0) { lastInline = span.Inlines[span.Inlines.Count - 1]; } } if (lastInline is LineBreak) { return(false); } inlines.Add(new LineBreak()); return(true); }
/// <summary> /// Retrieves all the runs and line breaks inside an inline collection recursively. This is very useful for white-space character handling. /// </summary> /// <param name="inlineCollection">The inline collection from which the runs and line breaks are to be retrieved.</param> /// <returns>Returns a list of runs and line breaks from the specified inline collection in the order that they appear within the inline collection.</returns> private static List<Inline> GetRunsAndLineBreaks(InlineCollection inlineCollection) { // Creates a new list, which will contain the result List<Inline> runsAndLineBreaks = new List<Inline>(); // Cycles over all the inlines in the inline collection foreach (Inline inline in inlineCollection) { // Checks if the current inline element is a run, if so then it is added to the result set Run run = inline as Run; if (run != null) runsAndLineBreaks.Add(run); // Checks if the current inline element is a line break, if so then it is added to the result set LineBreak lineBreak = inline as LineBreak; if (lineBreak != null) runsAndLineBreaks.Add(lineBreak); // Checks if the current inline element is a span, a span is the only inline element, which can itself contain inline elements, if the current // inline element is a span, then the runs and line breaks that it contains are recursively retrieved and added to the result set Span span = inline as Span; if (span != null) runsAndLineBreaks.AddRange(HtmlConverter.GetRunsAndLineBreaks(span.Inlines)); } // Returns the created list of runs and line breaks return runsAndLineBreaks; }
private void InnerWrite(FlowDocumentScrollViewer rtb, Paragraph p, string text, ConsoleColor foreground) { InlineCollection list = p.Inlines; // 满1000行删除500行 if (list.Count > 1000) { int delLines = 500; while (delLines-- > 0) { ((IList)list).RemoveAt(0); } } Run run = new Run(text) { Foreground = new SolidColorBrush(foreground.ToMediaColor()) }; list.Add(run); if (ChkbIsConsoleAutoScrollToEnd.IsChecked.HasValue && ChkbIsConsoleAutoScrollToEnd.IsChecked.Value) { ScrollViewer(rtb)?.ScrollToEnd(); } }
static void AddParameterModifier(SymbolFormatter formatter, InlineCollection inlines, IParameterSymbol p) { switch (p.RefKind) { case RefKind.Ref: inlines.Add(new Run("ref ") { Foreground = formatter.Keyword }); return; case RefKind.Out: inlines.Add(new Run("out ") { Foreground = formatter.Keyword }); return; case RefKind.In: inlines.Add(new Run("in ") { Foreground = formatter.Keyword }); return; } if (p.IsParams) { inlines.Add(new Run("params ") { Foreground = formatter.Keyword }); } }
public void LoadFormattedText() { if (formattedText == null || formattedText.Count == 0) { formattedText = FormatLine(GrepLine); } }
private static void InlinesSourcePropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e) { InlineCollection inlines = null; if (obj is TextBlock) { inlines = ((TextBlock)obj).Inlines; } else if (obj is Paragraph) { inlines = ((Paragraph)obj).Inlines; } #if NETFX_CORE || SILVERLIGHT else if (obj is RichTextBlock) { var paragraph = new Paragraph(); inlines = paragraph.Inlines; var richTextBlock = (RichTextBlock)obj; richTextBlock.Blocks.Clear(); richTextBlock.Blocks.Add(paragraph); } #endif if (inlines != null) { inlines.Clear(); foreach (var inline in TextToInlines((string)e.NewValue)) { inlines.Add(inline); } } }
/// <summary> /// Fill stop tip /// </summary> /// <param name="inlines">Inlines to fill</param> /// <param name="location">Source stop</param> private static void _FillStop(InlineCollection inlines, Stop stop) { if (stop.StopType == StopType.Lunch) { Inline inline = new Run((string)App.Current.FindResource("LunchString")); inlines.Add(inline); return; } _AddName(inlines, stop); if (stop.AssociatedObject is Order) { _AddPriorityIfNeeded(stop.AssociatedObject as Order, inlines); } _AddArriveTime(stop.ArriveTime, inlines); // Add stop's time window(s). _AddStopTimeWindows(inlines, stop); foreach (TipProperty tipProperty in App.Current.MapDisplay.StopTitlesSelected) { _AddBindableProperty(inlines, tipProperty, stop); } }
/// <summary> /// Add bindable property value /// </summary> /// <param name="inlines">Inlines to fill</param> /// <param name="tipProperty">Property</param> /// <param name="source">Source object</param> private static void _AddBindableProperty(InlineCollection inlines, TipProperty tipProperty, object source) { try { PropertyPath propertyPath = new PropertyPath(tipProperty.PrefixPath + tipProperty.Name); Binding binding = new Binding(); binding.Path = propertyPath; binding.Source = source; FrameworkElement fe = new FrameworkElement(); BindingOperations.SetBinding(fe, FrameworkElement.DataContextProperty, binding); object value = fe.DataContext; if (value != null) { string valueStr; if (value is double && tipProperty.ValueUnits.HasValue && tipProperty.DisplayUnits.HasValue) { Unit valueUnits = tipProperty.ValueUnits.Value; Unit displayUnits = tipProperty.DisplayUnits.Value; if (valueUnits != displayUnits) { value = UnitConvertor.Convert((double)value, valueUnits, displayUnits); } valueStr = UnitFormatter.Format((double)value, displayUnits); } else { // Special case for planned date if (tipProperty.Name.Equals(Order.PropertyNamePlannedDate)) { DateTime dateTime = (DateTime)value; valueStr = dateTime.ToShortDateString(); } else if (tipProperty.Name.Equals(Stop.PropertyNameStopType)) { valueStr = _GetStopTypeStr((StopType)value, (Stop)source); } else { valueStr = value.ToString(); } } if (valueStr.Length > 0) { _AddLine(tipProperty.Title, valueStr, inlines, false); } } BindingOperations.ClearBinding(fe, FrameworkElement.DataContextProperty); } catch (Exception ex) { Logger.Info(ex); } }
/// <summary> /// Fill zone tip /// </summary> /// <param name="inlines">Inlines to fill</param> /// <param name="location">Source zone</param> private static void _FillZone(InlineCollection inlines, Zone zone) { string name = zone.Name; _AddLine(_nameCaption, name, inlines, false); if (App.Current.MainWindow.CurrentPage == _optimizeAndEditPage) { string zoneAssignment = ""; foreach (Route route in _optimizeAndEditPage.CurrentSchedule.Routes) { if (route.Zones.Contains(zone)) { if (zoneAssignment.Length != 0) { zoneAssignment += ROUTE_SEPARATOR; } zoneAssignment += route.Name; } } if (zoneAssignment.Length > 0) { _AddLine(_zoneAssignmentCaption, zoneAssignment, inlines, false); } } }
private static void Fill(InlineCollection inlines, ElementToken token, Hint hint) { foreach (var t in token.Tokens) { inlines.Add(GetInline(t, hint)); } }
public TextMediaBindableRun CloseSelf(bool saveContent) { InlineCollection inlines = null; InlineUIContainer container = Parent as InlineUIContainer; if (container.Parent is Span) { Span o = container.Parent as Span; inlines = o.Inlines; } else if (container.Parent is Paragraph) { Paragraph o = container.Parent as Paragraph; inlines = o.Inlines; } else if (container.Parent is TextBlock) { TextBlock o = container.Parent as TextBlock; inlines = o.Inlines; } else { Debug.Print("Should never happen"); return(null); } return(DoCloseSelf(saveContent, container, inlines)); }
public void WriteLine(string text, ConsoleColor foreground) { Dispatcher.Invoke((Action)(() => { InlineCollection list = this.ConsoleParagraph.Inlines; string line = text; if (list.Count != 0 || _buffer.Count != 0) { line = "\n" + text; } if (IsBuffer) { _buffer.Add(line); _colors.Add(foreground); if (list.Count + _buffer.Count > MAXLINE) { if (list.Count != 0) { ((IList)list).RemoveAt(0); } else { _buffer.RemoveAt(0); _colors.RemoveAt(0); } } } else { InnerWrite(line, foreground); } })); }
private void WalkDocumentTree(Action <TextElement> action, InlineCollection ic) { foreach (Inline inline in ic) { if (inline is Figure) { WalkDocumentTree(action, (Figure)inline); } else if (inline is Floater) { WalkDocumentTree(action, (Floater)inline); } else if (inline is Run) { WalkDocumentTree(action, (Run)inline); } else if (inline is LineBreak) { WalkDocumentTree(action, (LineBreak)inline); } else if (inline is InlineUIContainer) { WalkDocumentTree(action, (InlineUIContainer)inline); } else if (inline is Span) { WalkDocumentTree(action, (Span)inline); } else { System.Diagnostics.Debug.Fail("TextElement type not matched ??"); } } }
/// <summary> /// Renders a strikethrough element. /// </summary> /// <param name="inlineCollection"> The list to add to. </param> /// <param name="element"> The parsed inline element to render. </param> /// <param name="context"> Persistent state. </param> private void RenderStrikethroughRun(InlineCollection inlineCollection, StrikethroughTextInline element, RenderContext context) { Span span = new Span { FontFamily = new FontFamily("Consolas") }; // Render the children into the inline. RenderInlineChildren(span.Inlines, element.Inlines, span, context); AlterChildRuns(span, (parentSpan, run) => { var text = run.Text; var builder = new StringBuilder(text.Length * 2); foreach (var c in text) { builder.Append((char)0x0336); builder.Append(c); } run.Text = builder.ToString(); }); // Add it to the current inlines inlineCollection.Add(span); }
protected override void Render() { InlineCollection inlines = Inlines; inlines.Clear(); TwitterStatusViewer v = Owner; if (v == null) { return; } Status s = v.DataContext as Status; if (s == null) { return; } Status s1 = s; if (s.RetweetedStatus != null) { s = s.RetweetedStatus; } v.CreateTweetBody(s.Text, inlines); }
public void FormatInlines(FlowDocument doc, InlineCollection inlines, StringBuilder buf, int indent) { foreach (Inline block in inlines) { FormatInline(doc, block, buf, indent); } }
private void InnerWrite(string text, ConsoleColor foreground) { Run run = new Run(text) { Foreground = new SolidColorBrush(foreground.ToMediaColor()) }; this.ConsoleParagraph.Inlines.Add(run); InlineCollection list = this.ConsoleParagraph.Inlines; // 满1000行删除500行 if (list.Count > 1000) { int delLines = 500; while (delLines-- > 0) { list.Remove(list.FirstInline); } } if (ChkbIsConsoleAutoScrollToEnd.IsChecked.HasValue && ChkbIsConsoleAutoScrollToEnd.IsChecked.Value) { this.RichTextBox.ScrollToEnd(); } }
public static FrameworkContentElement LoadDataTemplate(DataTemplate dataTemplate) { object content = dataTemplate.LoadContent(); if (content is Fragment) { return((FrameworkContentElement)((Fragment)content).Content); } else if (content is TextBlock) { InlineCollection inlines = ((TextBlock)content).Inlines; if (inlines.Count == 1) { return(inlines.FirstInline); } else { Paragraph paragraph = new Paragraph(); // we can't use an enumerator, since adding an inline removes it from its collection while (inlines.FirstInline != null) { paragraph.Inlines.Add(inlines.FirstInline); } return(paragraph); } } else { throw new Exception("Data template needs to contain a <Fragment> or <TextBlock>"); } }
public void AddInlines(InlineCollection inlines) { if (this.Parts == null) { this.CreateParts(); } foreach (EmojiStringPart part in this.Parts) { switch (part) { case EmojiPart emoji: Image image = new Image { Source = new BitmapImage(new Uri(emoji.FileName)), Height = 16, Width = 16, Margin = new Thickness(0) }; RenderOptions.SetBitmapScalingMode(image, BitmapScalingMode.HighQuality); inlines.Add(image); break; case TextPart text: inlines.Add(new Run(text.Content)); break; } } }
private static void OnXamlStringChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { TextBlock tb = d as TextBlock; if (tb == null) { return; } string xamlString = e.NewValue as string; if (string.IsNullOrEmpty(xamlString)) { return; } InlineCollection inlineCollection = CreateInlineCollection(xamlString); if (inlineCollection == null || inlineCollection.Count == 0) { return; } Inline[] inlines = new Inline[inlineCollection.Count]; inlineCollection.CopyTo(inlines, 0); PopulateTextBlockInlines(tb, inlines); }
/// <summary> /// Renders an image element. /// </summary> /// <param name="inlineCollection"> The list to add to. </param> /// <param name="element"> The parsed inline element to render. </param> /// <param name="context"> Persistent state. </param> private void RenderImage(InlineCollection inlineCollection, ImageInline element, RenderContext context) { var image = new Image(); var imageContainer = new InlineUIContainer() { Child = image }; // if url is not absolute we have to return as local images are not supported if (!element.Url.StartsWith("http") && !element.Url.StartsWith("ms-app")) { RenderTextRun(inlineCollection, new TextRunInline { Text = element.Text, Type = MarkdownInlineType.TextRun }, context); return; } image.Source = new BitmapImage(new Uri(element.Url)); image.HorizontalAlignment = HorizontalAlignment.Left; image.VerticalAlignment = VerticalAlignment.Top; image.Stretch = ImageStretch; ToolTipService.SetToolTip(image, element.Tooltip); // Try to add it to the current inlines // Could fail because some containers like Hyperlink cannot have inlined images try { inlineCollection.Add(imageContainer); } catch { // Ignore error } }
static public string TextUpTo(this InlineCollection inlines, TextPointer pointer) { StringBuilder textUpTo = new StringBuilder(); foreach (Inline inline in inlines) { if (inline.ElementStart.Offset > pointer.Offset) { break; } if (inline is Run run) { // Need some more work here to take account of run.FlowDirection and pointer.LogicalDirection. textUpTo.Append(run.Text.Substring(0, Math.Max(0, Math.Min(run.Text.Length, pointer.Offset - run.ContentStart.Offset)))); } else if (inline is Span span) { string spanTextUpTo = span.Inlines.TextUpTo(pointer); textUpTo.Append(spanTextUpTo); } else if (inline is LineBreak lineBreak) { textUpTo.Append((pointer.Offset >= lineBreak.ContentEnd.Offset) ? Environment.NewLine : ""); } else if (inline is InlineUIContainer uiContainer) { textUpTo.Append(" "); // empty string replacing the UI content. } else { throw new InvalidOperationException($"Unrecognized inline type {inline.GetType().Name}"); } } return(textUpTo.ToString()); }
/// <summary> /// Called to render an inline element /// </summary> /// <param name="element"></param> /// <param name="currentInlines"></param> private void RendnerInline(MarkdownInline element, InlineCollection currentInlines, ref bool trimTextStart) { switch (element.Type) { case MarkdownInlineType.TextRun: RenderTextRun((TextRunInline)element, currentInlines, ref trimTextStart); break; case MarkdownInlineType.Bold: RenderBoldRun((BoldTextElement)element, currentInlines, ref trimTextStart); break; case MarkdownInlineType.MarkdownLink: RenderMarkdownLink((MarkdownLinkInline)element, currentInlines, ref trimTextStart); break; case MarkdownInlineType.Italic: RenderItalicRun((ItalicTextElement)element, currentInlines, ref trimTextStart); break; case MarkdownInlineType.RawHyperlink: RenderRawHyperlink((RawHyperlinkInline)element, currentInlines, ref trimTextStart); break; case MarkdownInlineType.RawSubreddit: RenderRawSubreddit((RawSubredditInline)element, currentInlines, ref trimTextStart); break; } }
/// <summary> /// Renders a link element /// </summary> /// <param name="inlineCollection"> The list to add to. </param> /// <param name="element"> The parsed inline element to render. </param> /// <param name="parent"> The container element. </param> /// <param name="context"> Persistent state. </param> private void RenderMarkdownLink(InlineCollection inlineCollection, MarkdownLinkInline element, TextElement parent, RenderContext context) { // Avoid crash when link text is empty. if (element.Inlines.Count == 0) { return; } // Attempt to resolve references. element.ResolveReference(_document); if (element.Url == null) { // The element couldn't be resolved, just render it as text. RenderInlineChildren(inlineCollection, element.Inlines, parent, context); return; } // HACK: Superscript is not allowed within a hyperlink. But if we switch it around, so // that the superscript is outside the hyperlink, then it will render correctly. // This assumes that the entire hyperlink is to be rendered as superscript. if (AllTextIsSuperscript(element) == false) { // Regular ol' hyperlink. var link = new Hyperlink(); // Register the link _linkRegister.RegisterNewHyperLink(link, element.Url); // Remove superscripts. RemoveSuperscriptRuns(element, insertCaret: true); // Render the children into the link inline. var childContext = context.Clone(); childContext.WithinHyperlink = true; RenderInlineChildren(link.Inlines, element.Inlines, link, childContext); context.TrimLeadingWhitespace = childContext.TrimLeadingWhitespace; // Add it to the current inlines inlineCollection.Add(link); } else { // THE HACK IS ON! // Create a fake superscript element. var fakeSuperscript = new SuperscriptTextInline { Inlines = new List <MarkdownInline> { element } }; // Remove superscripts. RemoveSuperscriptRuns(element, insertCaret: false); // Now render it. RenderSuperscriptRun(inlineCollection, fakeSuperscript, parent, context); } }
static void AddPadding(InlineCollection inlines, int padding) { if (padding != 0) { inlines.Add(CreatePadding(padding)); } }
private static TI GetFirstChild <TI>(InlineCollection inlines) where TI : Inline { var inline = inlines.FirstInline as TI; Assert.NotNull(inline); return(inline); }
/// <summary> /// Renders a superscript element. /// </summary> /// <param name="inlineCollection"> The list to add to. </param> /// <param name="element"> The parsed inline element to render. </param> /// <param name="parent"> The container element. </param> /// <param name="context"> Persistent state. </param> private void RenderSuperscriptRun(InlineCollection inlineCollection, SuperscriptTextInline element, TextElement parent, RenderContext context) { // Le <sigh>, InlineUIContainers are not allowed within hyperlinks. if (context.WithinHyperlink) { RenderInlineChildren(inlineCollection, element.Inlines, parent, context); return; } var paragraph = new Paragraph(); paragraph.FontSize = parent.FontSize * 0.8; paragraph.FontFamily = parent.FontFamily; paragraph.FontStyle = parent.FontStyle; paragraph.FontWeight = parent.FontWeight; RenderInlineChildren(paragraph.Inlines, element.Inlines, paragraph, context); var richTextBlock = CreateOrReuseRichTextBlock(null, context); richTextBlock.Blocks.Add(paragraph); var border = new Border(); border.Padding = new Thickness(0, 0, 0, paragraph.FontSize * 0.2); border.Child = richTextBlock; var inlineUIContainer = new InlineUIContainer(); inlineUIContainer.Child = border; // Add it to the current inlines inlineCollection.Add(inlineUIContainer); }
/// <summary> /// Renders all of the children for the given element. /// </summary> /// <param name="inlineCollection"> The list to add to. </param> /// <param name="inlineElements"> The parsed inline elements to render. </param> /// <param name="parent"> The container element. </param> /// <param name="context"> Persistent state. </param> private void RenderInlineChildren(InlineCollection inlineCollection, IList <MarkdownInline> inlineElements, TextElement parent, RenderContext context) { foreach (MarkdownInline element in inlineElements) { RenderInline(inlineCollection, element, parent, context); } }
// Methods public static void AddLinkText(InlineCollection inlines, string text, HyperLinkObj obj) { Hyperlink item = new Hyperlink(new Run(text)) { Tag = obj }; inlines.Add(item); }
public static void LoadRichText(InlineCollection container, string content) { container.Clear(); if (content == null) return; HtmlDocument d = new HtmlDocument(); d.LoadHtml(content); Analyse(d.DocumentNode, container, ParsingStyle.Normal); }
internal static void Analyse(HtmlNode node, InlineCollection container, ParsingStyle style) { if (node == null) return; foreach (var item in node.ChildNodes) { switch (item.Name) { //文本 case "#text": container.Add(new Run() { Text = item.InnerText }); continue; case "strong": style = style | ParsingStyle.Bold; break; //链接 case "a": var link = new Hyperlink(); ParseRelativeUrl(item.GetAttributeValue("href", ""), link, App.Current.NavigationService); Analyse(item, link.Inlines, style); container.Add(link); continue; //图片 case "img": var image = new Image() { Source = new BitmapImage(new Uri(item.GetAttributeValue("src", ""))) }; var cont = new InlineUIContainer(); cont.Child = image; container.Add(cont); continue; //换行 case "br": container.Add(new LineBreak()); continue; //容器 case "span": case "div": case "p": break; case "b": //TODO: 设置属性,是否要加红搜索显示结果 if(node.GetAttributeValue("class","") == "key_red") { Span p = new Span(); p.Foreground = new SolidColorBrush(Colors.Red); Analyse(item, container, style); continue; } else break; //非文本 case "button": continue; default: continue; } Analyse(item, container, style); } }
public void FillInlines(string text, InlineCollection collection) { text = text.Replace("\r", ""); var codeLexem = new CodeLexem(text); var list = codeLexem.Parse(CodeLanguage); foreach (CodeLexem current in list) { collection.Add(current.ToInline(CodeLanguage)); } }
private static int GetCharOffsetToPosition(InlineCollection inlineCollection, TextPointer position, out TextPointer result) { int offset = 0; foreach (var inline in inlineCollection) { offset += GetCharOffsetToPosition(inline, position, out result); if (result == null || result.CompareTo(position) >= 0) return offset; } result = null; return offset; }
private static void GetText(StringBuilder builder, InlineCollection inlines) { foreach (var inline in inlines) { Run run = inline as Run; if (run != null) { builder.Append(run.Text); } Span span = inline as Span; if (span != null) { GetText(builder, span.Inlines); } } }
private void AddComparisonToOptimal(InlineCollection inlines, double current, double optimal, bool smallIsGood) { double difference = current - optimal; Color color = new Color(); if (difference < 0) { color = smallIsGood ? Colors.Green : Colors.Red; } else { color = smallIsGood ? Colors.Red : Colors.Green; } if (Math.Abs(difference) > 0.004) { inlines.Add(new Run() { Text = " (" }); inlines.Add(new Run() { Text = difference.ToString("+0.##;-0.##"), Foreground = new SolidColorBrush(color) }); inlines.Add(new Run() { Text = ")" }); } }
/// <summary> /// Convert an flow document inlines into their (combined!) html representation. /// </summary> /// <param name="inlines">Flow document inlines collection.</param> /// <param name="htmlWriter">XmlTextWriter producing resulting html.</param> /// <param name="conversionResult">Conversion result to store error and warning messages. Can be null.</param> /// <param name="inheritedStyle">Inherited inline styles.</param> /// <remarks> /// Supported: Hyperlink, Bold, Underline, Italic as well as Run and InlineUIContainer for Image. /// </remarks> private static void AddInlines(InlineCollection inlines, XmlTextWriter htmlWriter, ValidationResult conversionResult, List<InlineStyles> inheritedStyle) { for (int i = 0; i < inlines.Count; ++i) { Inline inline = inlines.ElementAt(i); #region InheritedStyle + B,I,U processing bool bAddBold = false; bool bAddItalic = false; bool bAddUnderlined = false; // Bold if (inline.FontWeight != System.Windows.FontWeights.Bold && inheritedStyle.Contains(InlineStyles.Bold)) { // close last element tag htmlWriter.WriteEndElement(); inheritedStyle.Remove(InlineStyles.Bold); } else if (!inheritedStyle.Contains(InlineStyles.Bold) && inline.FontWeight == System.Windows.FontWeights.Bold) bAddBold = true; // Italic if (inline.FontStyle != System.Windows.FontStyles.Italic && inheritedStyle.Contains(InlineStyles.Italic)) { // close last element tag htmlWriter.WriteEndElement(); inheritedStyle.Remove(InlineStyles.Italic); } else if (!inheritedStyle.Contains(InlineStyles.Italic) && inline.FontStyle == System.Windows.FontStyles.Italic) bAddItalic = true; // Underline bool bHasUnderline = false; if (inline is Run && inline.Parent is Span) { if ((inline.Parent as Span).TextDecorations.Contains(System.Windows.TextDecorations.Underline[0])) bHasUnderline = true; } if (!inline.TextDecorations.Contains(System.Windows.TextDecorations.Underline[0]) && inheritedStyle.Contains(InlineStyles.Underlined)) { if (!bHasUnderline) { // close last element tag htmlWriter.WriteEndElement(); inheritedStyle.Remove(InlineStyles.Underlined); } } else if (!inheritedStyle.Contains(InlineStyles.Underlined) && inline.TextDecorations.Contains(System.Windows.TextDecorations.Underline[0])) if (!bHasUnderline) bAddUnderlined = true; if (inline is HtmlHyperlink) bAddUnderlined = false; // see what needs to be added.. if multiple elements need to be added, than we have to iterate through // siblings to see what tag to set first (depending on what to close first). if (bAddUnderlined || bAddBold || bAddItalic) { if (bAddBold && bAddItalic || bAddBold && bAddUnderlined || bAddItalic && bAddUnderlined) { InlineStylesCount stylesCount = InlineStylesCounter.Count(inlines, i + 1); // see what has to be added first // add tags for (int z = 0; z < 3; ++z) { if (stylesCount.Order[z] == InlineStyles.Bold && bAddBold) { htmlWriter.WriteStartElement("b"); inheritedStyle.Add(InlineStyles.Bold); } else if (stylesCount.Order[z] == InlineStyles.Italic && bAddItalic) { htmlWriter.WriteStartElement("i"); inheritedStyle.Add(InlineStyles.Italic); } else if (stylesCount.Order[z] == InlineStyles.Underlined && bAddUnderlined) { htmlWriter.WriteStartElement("u"); inheritedStyle.Add(InlineStyles.Underlined); } } } else { // just add the tag of the needed style if (bAddBold) { htmlWriter.WriteStartElement("b"); inheritedStyle.Add(InlineStyles.Bold); } else if (bAddItalic) { htmlWriter.WriteStartElement("i"); inheritedStyle.Add(InlineStyles.Italic); } else if (bAddUnderlined) { htmlWriter.WriteStartElement("u"); inheritedStyle.Add(InlineStyles.Underlined); } } } #endregion // continue with text or inlines if (inline is InlineUIContainer) { InlineUIContainer container = inline as InlineUIContainer; if (container.Child is HtmlImage) { // Add image AddImage(container.Child as HtmlImage, htmlWriter, conversionResult); } else if (container.Child is System.Windows.Controls.TextBlock) { // Comment, just add text as is string text = ExtendedHtmlUtility.HtmlEntityEncode((container.Child as System.Windows.Controls.TextBlock).Text); htmlWriter.WriteRaw(text); } else { // not supported if (conversionResult != null) { if (container.Child != null) conversionResult.AddMessage(new ConversionMessage(ModelValidationViolationType.Warning, "AddInline: Unknown inline ui container child: " + container.Child.ToString())); //else // conversionResult.AddMessage(new ConversionMessage(ModelValidationViolationType.Warning, // "AddInline: Inline ui container child is null: " + container.ToString())); } } } else if (inline is HtmlHyperlink) { // Add hyperlink AddHyperlink(inline as HtmlHyperlink, htmlWriter, conversionResult, inheritedStyle); } else if (inline is Span) { Span span = inline as Span; AddInlines(span.Inlines, htmlWriter, conversionResult, inheritedStyle); } else if (inline is Run) { string text = ExtendedHtmlUtility.HtmlEntityEncode((inline as Run).Text); //string text = HtmlEncode((inline as Run).Text); ; htmlWriter.WriteRaw(text); } else { // not supported if (conversionResult != null) { conversionResult.AddMessage(new ConversionMessage(ModelValidationViolationType.Warning, "AddInline: Unknown inline element: " + inline.ToString())); } } } }
/// <summary> /// Convert an flow document inlines into their (combined!) html representation. /// </summary> /// <param name="inlines">Flow document inlines collection.</param> /// <param name="htmlWriter">XmlTextWriter producing resulting html.</param> /// <param name="conversionResult">Conversion result to store error and warning messages. Can be null.</param> /// <remarks> /// Supported: Hyperlink, Bold, Underline, Italic as well as Run and InlineUIContainer for Image. /// </remarks> private static void AddInlines(InlineCollection inlines, XmlTextWriter htmlWriter, ValidationResult conversionResult) { List<InlineStyles> inheritedStyle = new List<InlineStyles>(); AddInlines(inlines, htmlWriter, conversionResult, inheritedStyle); for (int i = 0; i < inheritedStyle.Count; ++i) htmlWriter.WriteEndElement(); }
public void AddInline(Inline inline) { FlushAddedText(false); if (inlineCollection == null) { var para = new Paragraph(); para.Margin = new Thickness(0, 0, 0, 5); inlineCollection = para.Inlines; AddBlock(para); } inlineCollection.Add(inline); }
public static InlineStylesCount Count(InlineCollection collection, int startIndex) { InlineStylesCount stylesCount = new InlineStylesCount(); stylesCount.BoldCount = 0; stylesCount.ItalicCount = 0; stylesCount.UnderlinedCount = 0; stylesCount.BoldCountingFinished = false; stylesCount.UnderlinedCountingFinished = false; stylesCount.ItalicCountingFinished = false; stylesCount.Order = new List<InlineStyles>(); Count(collection, startIndex, stylesCount); // build order stylesCount.Order.Add(InlineStyles.Bold); if (stylesCount.ItalicCount > stylesCount.BoldCount) stylesCount.Order.Insert(0, InlineStyles.Italic); else stylesCount.Order.Add(InlineStyles.Italic); for (int z = 0; z < 2; ++z) { if (stylesCount.Order[z] == InlineStyles.Bold && stylesCount.UnderlinedCount > stylesCount.BoldCount) { stylesCount.Order.Insert(z, InlineStyles.Underlined); break; } else if (stylesCount.Order[z] == InlineStyles.Italic && stylesCount.UnderlinedCount > stylesCount.ItalicCount) { stylesCount.Order.Insert(z, InlineStyles.Underlined); break; } else if (z == 1) stylesCount.Order.Add(InlineStyles.Underlined); } // remove unneeded elements /* if (stylesCount.BoldCount == 0) stylesCount.Order.Remove(InlineStyles.Bold); if (stylesCount.ItalicCount == 0) stylesCount.Order.Remove(InlineStyles.Italic); if (stylesCount.UnderlinedCount == 0) stylesCount.Order.Remove(InlineStyles.Underlined); */ return stylesCount; }
private void ProcessInlines(RichTextBox textBox, InlineCollection inlines) { for (int inlineIndex = 0; inlineIndex < inlines.Count; inlineIndex++) { Inline i = inlines.ElementAt(inlineIndex); if (i is Run) { Run r = i as Run; string text = r.Text; string emoticonFound = string.Empty; int index = FindFirstEmoticon(text, 0, out emoticonFound); if (index >= 0) { TextPointer tp = i.ContentStart; bool reposition = false; while (!tp.GetTextInRun(LogicalDirection.Forward).StartsWith(emoticonFound)) tp = tp.GetNextInsertionPosition(LogicalDirection.Forward); TextPointer end = tp; for (int j = 0; j < emoticonFound.Length; j++) end = end.GetNextInsertionPosition(LogicalDirection.Forward); TextRange tr = new TextRange(tp, end); if (textBox != null) reposition = textBox.CaretPosition.CompareTo(tr.End) == 0; tr.Text = string.Empty; var image = GetImageForEmoticon(emoticonFound); InlineUIContainer iui = new InlineUIContainer(image, tp); iui.BaselineAlignment = BaselineAlignment.TextBottom; if (textBox != null && reposition) textBox.CaretPosition = tp.GetNextInsertionPosition(LogicalDirection.Forward); } } } }
void AddSpan(Span span, IEnumerable<XmlDocumentationElement> children) { AddInline(span); var oldInlineCollection = inlineCollection; try { inlineCollection = span.Inlines; foreach (var child in children) AddDocumentationElement(child); FlushAddedText(false); } finally { inlineCollection = oldInlineCollection; } }
void AddList(string type, IEnumerable<XmlDocumentationElement> items) { List list = new List(); AddBlock(list); list.Margin = new Thickness(0, 5, 0, 5); if (type == "number") list.MarkerStyle = TextMarkerStyle.Decimal; else if (type == "bullet") list.MarkerStyle = TextMarkerStyle.Disc; var oldBlockCollection = blockCollection; try { foreach (var itemElement in items) { if (itemElement.Name == "listheader" || itemElement.Name == "item") { ListItem item = new ListItem(); blockCollection = item.Blocks; inlineCollection = null; foreach (var prop in itemElement.Children) { AddDocumentationElement(prop); } FlushAddedText(false); list.ListItems.Add(item); } } } finally { blockCollection = oldBlockCollection; } }
void AddSection(Inline title, Action addChildren) { var section = new Section(); AddBlock(section); var oldBlockCollection = blockCollection; try { blockCollection = section.Blocks; inlineCollection = null; if (title != null) AddInline(new Bold(title)); addChildren(); FlushAddedText(false); } finally { blockCollection = oldBlockCollection; inlineCollection = null; } }
private static void Count(InlineCollection inlines, int startIndex, InlineStylesCount stylesCount) { for (int y = startIndex + 1; y < inlines.Count; ++y) { Inline inlineY = inlines.ElementAt(y); if (inlineY.FontStyle == System.Windows.FontStyles.Italic) stylesCount.ItalicCount++; else stylesCount.ItalicCountingFinished = true; if (inlineY.FontWeight == System.Windows.FontWeights.Bold) stylesCount.BoldCount++; else stylesCount.BoldCountingFinished = true; if (inlineY.TextDecorations.Contains(System.Windows.TextDecorations.Underline[0])) stylesCount.UnderlinedCount++; else stylesCount.UnderlinedCountingFinished = true; // continue with children if (inlineY is Span) { if (!stylesCount.BoldCountingFinished || !stylesCount.UnderlinedCountingFinished || !stylesCount.ItalicCountingFinished) { Count((inlineY as Span).Inlines, 0, stylesCount); } } if (stylesCount.BoldCountingFinished && stylesCount.UnderlinedCountingFinished && stylesCount.ItalicCountingFinished) break; } }
public static void ParseInlines(MessagePack msgPack, InlineCollection inlines) { foreach (Inline inline in inlines) { if (inline is Run) { ParseRun(msgPack, (Run)inline); } else if (inline is Span) { ParseSpan(msgPack, (Span)inline); } else if (inline is LineBreak) { ParseLineBreak(msgPack, (LineBreak)inline); } else if (inline is InlineUIContainer) { ParseInlineUIContainer(msgPack, (InlineUIContainer)inline); } } }
private void AddElementToCollection(Inline elm, InlineCollection coll) { if (elm is InlineParaGraph) { //coll.Add(new LineBreak()); coll.Add(new LineBreak()); } else if (elm is Table) { coll.Add(new LineBreak()); } else coll.Add(elm); }
public static void AddNormalText(InlineCollection inlines, string text) { inlines.Add(new Run(text)); }
/// <summary> /// Clears and populates the provided table with rows that have the following syntax: /// [row #] [state of new value] /// /// If the state of a value has changed, the value will be bolded. /// </summary> /// <param name="table">Table will be cleared and new rows will populate this table.</param> /// <param name="newValues">The new boolean values</param> /// <param name="oldValues">The boolean values that the new ones are being compared to</param> /// <param name="trueValue">Text if the new value is TRUE</param> /// <param name="falseValue">Text if the new vlaue is FALSE</param> public static Boolean CreateBooleanChartInTable( InlineCollection table, List<Boolean> newValues, List<Boolean> oldValues, String trueValue, String falseValue) { Boolean isBooleanChartCreated = false; // Make sure there are at least newValues to check or that there are the same number of old values as new values if ((newValues != null) && ((oldValues == null) || (newValues.Count == oldValues.Count))) { table.Clear(); // Each new value has it's own row for (int i = 0; i < (int)newValues.Count; i += 1) { var line = new Span(); // Row # var block = new Run(); block.Text = (i + 1).ToString("D", NumberFormatInfo.InvariantInfo); line.Inlines.Add(block); // Space between row # and the value (simulates a column) block = new Run(); block.Text = " "; line.Inlines.Add(block); // Print the textual form of TRUE/FALSE values block = new Run(); block.Text = newValues[i] ? trueValue : falseValue; // Bold values that have changed if ((oldValues != null) && (oldValues[i] != newValues[i])) { var bold = new Bold(); bold.Inlines.Add(block); line.Inlines.Add(bold); } else { line.Inlines.Add(block); } line.Inlines.Add(new LineBreak()); table.Add(line); } isBooleanChartCreated = true; } return isBooleanChartCreated; }
void AddParagraph(Paragraph para, IEnumerable<XmlDocumentationElement> children) { AddBlock(para); try { inlineCollection = para.Inlines; foreach (var child in children) AddDocumentationElement(child); FlushAddedText(false); } finally { inlineCollection = null; } }
private static void BuildStringFromInlineCollection(InlineCollection inlines, StringBuilder sb) { foreach (var inline in inlines) { if (inline != null) { var inlineText = GetStringFromInline(inline); if (!string.IsNullOrEmpty(inlineText)) { sb.Append(inlineText); } } } }
private void ParseInlines(MessagePack msgPack, InlineCollection inlines) { foreach (Inline inline in inlines) { if (inline is System.Windows.Documents.Run) { this.ParseRun(msgPack, (System.Windows.Documents.Run)inline); } else if (inline is Span) { this.ParseSpan(msgPack, (Span)inline); } else if (inline is LineBreak) { this.ParseLineBreak(msgPack, (LineBreak)inline); } else if (inline is InlineUIContainer) { this.ParseInlineUIContainer(msgPack, (InlineUIContainer)inline); } } }
private void DocTreeToTextElement(DocTree tree, InlineCollection coll) { if (tree.Element is Table) { coll.Add(new LineBreak()); AddElementToCollection(CreateGrid(tree), coll); } else { AddElementToCollection(tree.Element, coll); if (!tree.HasChildren) return; foreach (var child in tree.Children) { DocTreeToTextElement(child, coll); } } }
private void VerifyInlineCollectionsMatch(InlineCollection inlineCollectionExpected, InlineCollection inlineCollectionActual) { VerifyInlineListsMatch(new List<Inline>(inlineCollectionExpected), new List<Inline>(inlineCollectionActual)); }
private void CreateInlines(WebVTTCue cue, IWebVTTInternalNode node, InlineCollection inlines, Brush brush) { foreach (var child in node.Nodes) { var inline = CreateInline(child, brush); if (inline != null) { inlines.Add(inline); if (inline is Span && child is IWebVTTInternalNode) { CreateInlines(cue, (IWebVTTInternalNode)child, ((Span)inline).Inlines, brush); } if (NodeRendering != null) NodeRendering(this, new NodeRenderingEventArgs(cue, child, inline)); } } }
public static void CreateBooleanTable( InlineCollection Table, bool[] NewValues, bool[] OldValues, string IndexTitle, string ValueTitle, string TrueValue, string FalseValue ) { Table.Clear(); for (var i = 0; i < NewValues.Length; i += 1) { var line = new Span(); var block = new Run(); block.Text = (i + 1).ToString("###"); line.Inlines.Add(block); block = new Run(); block.Text = " "; line.Inlines.Add(block); block = new Run(); block.Text = NewValues[i] ? TrueValue : FalseValue; if ((OldValues != null) && (OldValues[i] != NewValues[i])) { var bold = new Bold(); bold.Inlines.Add(block); line.Inlines.Add(bold); } else { line.Inlines.Add(block); } line.Inlines.Add(new LineBreak()); Table.Add(line); } }