public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { List<Inline> inlines = new List<Inline>(); if (value == null) { return inlines; } var currentRoute = value as Route; if (currentRoute == null) { return inlines; } Italic noOrders = new Italic(new Run((string)App.Current.FindResource("NoOrdersCellText"))); noOrders.Foreground = new SolidColorBrush(Colors.Gray); noOrders.FontSize = (double)App.Current.FindResource("StandartHelpFontSize"); inlines.Add(new Run(currentRoute.Name + " ")); if (currentRoute.Stops.Count == 0) inlines.Add(noOrders); return inlines; }
protected override void AddEmptyConversationMessage() { List<Paragraph> emptyParagraphList = new List<Paragraph>(); Italic noConversationItalic = new Italic(new Run(_noConversationMessage)); emptyParagraphList.Add(new Paragraph(noConversationItalic)); _paragraphs = emptyParagraphList; }
public static void Append(this Paragraph paragraph, string value = "", Brush background = null, Brush foreground = null, bool bold = false, bool italic = false, bool underline = false) { Inline run = new Run(value); if (background != null) run.Background = background; if (foreground != null) run.Foreground = foreground; if (bold) run = new Bold(run); if (italic) run = new Italic(run); if (underline) run = new Underline(run); paragraph.Inlines.Add(run); }
private Inline GetInlineWithStyling( string line, System.Drawing.FontStyle style ) { Inline styledText = new Run( line ); if ( style.HasFlag( System.Drawing.FontStyle.Bold ) ) styledText = new Bold( styledText ); if ( style.HasFlag( System.Drawing.FontStyle.Italic ) ) styledText = new Italic( styledText ); if ( style.HasFlag( System.Drawing.FontStyle.Underline ) ) styledText = new Underline( styledText ); return styledText; }
public MainWindow() { InitializeComponent(); Doc = new FlowDocument(); Paragraph para = new Paragraph(); para.Inlines.Add("normal"); Bold b = new Bold(); b.Inlines.Add("Bold"); para.Inlines.Add(b); Italic it = new Italic(); it.Inlines.Add("italic"); para.Inlines.Add(it); Doc.Blocks.Add(para); this.DataContext = Doc; }
public static FlowDocument PrintRecipe(Recipe r) { // Before printing check that all fields are valid if (r.Name == String.Empty || r.Time == String.Empty || r.Instructions == String.Empty || r.Writer == String.Empty) { throw new Exception("Reseptissä ei voi olla tyhjiä kenttiä!"); } // If all fields are valid print the recipe else { // Create a FlowDocument FlowDocument doc = new FlowDocument(); // Create a Section Section sec = new Section(); Section sec2 = new Section(); // Create first Paragraph Paragraph p1 = new Paragraph(); Paragraph p2 = new Paragraph(); // Create and add a new Bold, Italic and Underline Bold bld = new Bold(); bld.Inlines.Add(new Run(r.Name)); Italic italicBld = new Italic(); italicBld.Inlines.Add(bld); Underline underlineItalicBld = new Underline(); underlineItalicBld.Inlines.Add(italicBld); // Add Bold, Italic, Underline to Paragraph p1.Inlines.Add(underlineItalicBld); p1.Inlines.Add(new Run("\n" + r.Time)); p1.Inlines.Add(new Run("\n" + r.Writer)); p2.Inlines.Add(new Run(r.Instructions)); // Add Paragraph to Section sec.Blocks.Add(p1); sec2.Blocks.Add(p2); // Add Section to FlowDocument doc.Blocks.Add(sec); doc.Blocks.Add(sec2); return doc; } }
public void parse_DownloadWikiPageCompleted(Object sender, HtmlDocumentLoadCompleted e) { if (e != null && e.Document != null && e.Document.DocumentNode != null) { IList<Block> pageBody = new List<Block>(); IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); Paragraph paragraph = new Paragraph(); Boolean flag = false; Boolean flag_table = false; foreach (HtmlNode htmlNode in hnc) { try { if (flag_table && htmlNode.PreviousSibling != null && htmlNode.PreviousSibling.Name.ToLower() == "table") { flag_table = false; } } catch (Exception err) { Console.Error.Write(err.StackTrace); } if (htmlNode.Name.ToLower() == "div") { foreach (HtmlAttribute att in htmlNode.Attributes) { if (att.Name.ToLower() == "id" && att.Value == "bodyContent") { flag = true; break; } else if (att.Name.ToLower() == "class" && att.Value == "printfooter") { flag = false; goto BreakParseLoop; } } } else if (htmlNode.Name.ToLower() == "table") { flag_table = true; } else if (flag && !flag_table && htmlNode.Name.ToLower() == "h2") { if (!(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "toctitle")) { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(h2); para.Inlines.Add(new LineBreak()); pageBody.Add(para); } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "h3") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(h2); para.Inlines.Add(new LineBreak()); pageBody.Add(para); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "#text") { if (htmlNode.ParentNode.Name.ToLower() != "a" && htmlNode.ParentNode.Name.ToLower() != "b" && htmlNode.ParentNode.Name.ToLower() != "p" && htmlNode.ParentNode.Name.ToLower() != "i" && htmlNode.ParentNode.Name.ToLower() != "ul" && htmlNode.ParentNode.Name.ToLower() != "li" && htmlNode.ParentNode.Name.ToLower() != "h2" && htmlNode.ParentNode.Name.ToLower() != "h3" && htmlNode.ParentNode.Name.ToLower() != "td" && htmlNode.ParentNode.Name.ToLower() != "tr" && htmlNode.ParentNode.Name.ToLower() != "table" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "jump-to-nav") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "td") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "tr") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "table") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "li") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "ul") && !(htmlNode.ParentNode.Name.ToLower() == "i" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "p") && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "editsection") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Name == "class" && htmlNode.ParentNode.Attributes[0].Value == "toctext") && !(htmlNode.ParentNode.Name.ToLower() == "span" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Name == "class" && htmlNode.ParentNode.Attributes[0].Value == "tocnumber") && htmlNode.ParentNode.Name.ToLower() != "script" && htmlNode.ParentNode.Name.ToLower() != "#comment" && htmlNode.ParentNode.Name.ToLower() != "dd" && htmlNode.ParentNode.Name.ToLower() != "dl") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "a") { if (htmlNode.ParentNode.Name != "p" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "jump-to-nav") && htmlNode.ParentNode.Name.ToLower() != "li" && htmlNode.ParentNode.Name.ToLower() != "ul" && htmlNode.ParentNode.Name.ToLower() != "dd" && htmlNode.ParentNode.Name.ToLower() != "dl" && !(htmlNode.ParentNode.Name.ToLower() == "div" && htmlNode.ParentNode.Attributes.Count > 0 && htmlNode.ParentNode.Attributes[0].Value == "editsection") && !(htmlNode.ParentNode.Name.ToLower() == "i" && htmlNode.ParentNode.ParentNode.Name.ToLower() == "p")) { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(htmlNode.InnerText); foreach (HtmlAttribute att1 in htmlNode.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href="+att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { // hl.Click += new RoutedEventHandler(hyperlink_Click); paragraph.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = htmlNode.InnerText; paragraph.Inlines.Add(r); } } } else if (flag && !flag_table && htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode pc in htmlNode.DescendantNodes().ToList()) { if (pc.Name.ToLower() == "a") { if (pc.ParentNode.Name.ToLower() != "i" && pc.ParentNode.Name.ToLower() != "b") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(pc.InnerText); foreach (HtmlAttribute att1 in pc.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { np.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = pc.InnerText; np.Inlines.Add(r); } } } else if (pc.Name.ToLower() == "#text") { if (pc.ParentNode.Name.ToLower() != "a" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(pc.InnerText); if (str != " ") { Run run = new Run(); run.Text = pc.InnerText; np.Inlines.Add(run); } } } else if (pc.Name.ToLower() == "b") { Bold b = new Bold(); foreach(HtmlNode n in pc.DescendantNodes().ToList()){ if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a"){ b.Inlines.Add(n.InnerText); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { b.Inlines.Add(hl); } else { b.Inlines.Add(n.InnerText); } } } np.Inlines.Add(b); } else if (pc.Name.ToLower() == "i") { Italic i = new Italic(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { i.Inlines.Add(n.InnerText); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { i.Inlines.Add(hl); } else { i.Inlines.Add(n.InnerText); } } } np.Inlines.Add(i); } } pageBody.Add(np); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "dl") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); np.TextAlignment = TextAlignment.Justify; foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href="+att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText; np.Inlines.Add(r); } } else if (a.Name.ToLower() == "dd") { try { if (a.PreviousSibling != null & a.PreviousSibling.Name.ToLower() == "dd") { np.Inlines.Add(new LineBreak()); } } catch (Exception err) { Console.Error.Write(err.StackTrace); } } else if (a.Name.ToLower() == "b") { Bold b = new Bold(); b.Inlines.Add(a.InnerText); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { Italic i = new Italic(); i.Inlines.Add(str); np.Inlines.Add(i); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } else if (flag && !flag_table && htmlNode.Name.ToLower() == "ul") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } if (htmlNode.ParentNode.Name.ToLower() != "td" && htmlNode.ParentNode.Name.ToLower() != "tr" && htmlNode.ParentNode.Name.ToLower() != "table" && !(htmlNode.ParentNode.Name.ToLower() == "ul" && htmlNode.ParentNode.ParentNode != null && htmlNode.ParentNode.ParentNode.Name.ToLower() == "td") && !(htmlNode.ParentNode.Name.ToLower() == "li" && htmlNode.ParentNode.ParentNode != null && htmlNode.ParentNode.ParentNode.Name.ToLower() == "ul" && htmlNode.ParentNode.ParentNode.ParentNode.Name.ToLower() == "td")) { Paragraph np = new Paragraph(); foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/WikiContentPage.xaml?href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText; np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { try { if (a.PreviousSibling != null & a.PreviousSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } catch (Exception err) { Console.Error.Write(err.StackTrace); } Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b") { Bold b = new Bold(); b.Inlines.Add(a.InnerText); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; np.Inlines.Add(run); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } else if (htmlNode.Name.ToLower() == "h1") { foreach (HtmlAttribute att2 in htmlNode.Attributes) { if (att2.Name.ToLower() == "class" && att2.Value == "firstHeading") { PageTitle.Text = htmlNode.InnerText; } } } } BreakParseLoop: if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollViewer1.InvalidateArrange(); scrollViewer1.InvalidateMeasure(); scrollViewer1.InvalidateScrollInfo(); } else { this.NavigationService.Navigate(new Uri("/ContentLoadError.xaml?href="+CurrentPage, UriKind.Relative)); } progress.Visibility = Visibility.Collapsed; }
public void parse_DownloadProductReportPageCompleted(Object sender, HtmlDocumentLoadCompleted e) { if (e != null && e.Document != null && e.Document.DocumentNode != null) { IList<Block> pageBody = new List<Block>(); IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); Paragraph paragraph = new Paragraph(); Boolean content_flag = false; foreach (HtmlNode htmlNode in hnc) { if (htmlNode.Name.ToLower() == "h1" && htmlNode.Attributes.Count == 0) { PageTitle.Text = htmlNode.InnerText.Replace("�", "'"); content_flag = true; } else if (content_flag && htmlNode.Name.ToLower() == "h2") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } if (htmlNode.InnerText == "Related Health Canada Web content:") { content_flag = false; } else { Paragraph h2 = new Paragraph(); h2.FontSize = 25.333; h2.Inlines.Add(htmlNode.InnerText.Trim()); pageBody.Add(h2); } } else if (content_flag && htmlNode.Name.ToLower() == "ul") { if (htmlNode.ParentNode.Name.ToLower() != "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b" || a.ParentNode.Name.ToLower() == "strong") { Bold b = new Bold(); b.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "strong" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } if (a.NextSibling != null && a.NextSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } else if (content_flag && htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Paragraph np = new Paragraph(); foreach (HtmlNode pc in htmlNode.DescendantNodes().ToList()) { if (content_flag && htmlNode.Name.ToLower() == "ul") { foreach (HtmlNode a in htmlNode.DescendantNodes().ToList()) { if (a.Name.ToLower() == "a") { Boolean err_flag = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(a.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in a.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { err_flag = true; } } catch (Exception err) { err_flag = true; } break; } } if (!err_flag) { np.Inlines.Add(hl); } else { Run r = new Run(); r.Text = a.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } else if (a.Name.ToLower() == "li") { Bold b = new Bold(); b.Inlines.Add("- "); np.Inlines.Add(b); } else if (a.Name.ToLower() == "b" || a.ParentNode.Name.ToLower() == "strong") { Bold b = new Bold(); b.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(b); } else if (a.Name.ToLower() == "i") { Italic i = new Italic(); i.Inlines.Add(a.InnerText.Replace(" ", "")); np.Inlines.Add(i); } else if (a.Name.ToLower() == "#text") { if (a.ParentNode.Name.ToLower() != "a" && a.ParentNode.Name.ToLower() != "b" && a.ParentNode.Name.ToLower() != "strong" && a.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(a.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } if (a.NextSibling != null && a.NextSibling.Name.ToLower() == "li") { np.Inlines.Add(new LineBreak()); } } } } np.Inlines.Add(new LineBreak()); } else if (pc.Name.ToLower() == "a") { if (pc.ParentNode.Name.ToLower() != "i" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "strong") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(pc.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in pc.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { np.Inlines.Add(hl); } else if (flag_local) { Run r = new Run(); r.Text = pc.InnerText.Replace(" ", ""); np.Inlines.Add(r); } } } else if (pc.Name.ToLower() == "#text") { if (pc.ParentNode.Name.ToLower() != "a" && pc.ParentNode.Name.ToLower() != "b" && pc.ParentNode.Name.ToLower() != "strong" && pc.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(pc.InnerText); if (str != " ") { str = str.Replace(""", "\""); Run run = new Run(); run.Text = str.Replace(" ", ""); np.Inlines.Add(run); } } } else if (pc.Name.ToLower() == "b" || pc.Name.ToLower() == "strong") { Bold b = new Bold(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { b.Inlines.Add(n.InnerText.Replace(" ", "")); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { b.Inlines.Add(hl); } else { b.Inlines.Add(n.InnerText.Replace(" ", "")); } } } np.Inlines.Add(b); } else if (pc.Name.ToLower() == "br") { // Run r = new Run(); // r.Text = "\n"; // np.Inlines.Add(r); } else if (pc.Name.ToLower() == "i") { Italic i = new Italic(); foreach (HtmlNode n in pc.DescendantNodes().ToList()) { if (n.Name.ToLower() == "#text" && n.ParentNode.Name.ToLower() != "a") { i.Inlines.Add(n.InnerText.Replace(" ", "")); } else if (n.Name.ToLower() == "a") { Boolean image_flag = false; Boolean flag_local = false; Hyperlink hl = new Hyperlink(); hl.Inlines.Add(n.InnerText.Replace(" ", "")); foreach (HtmlAttribute att1 in n.Attributes) { if (att1.Name.ToLower() == "href") { try { if (att1.Value.ToCharArray()[0] != '#') { hl.NavigateUri = new Uri("/ProductReportPage.xaml?external=true&href=" + att1.Value, UriKind.Relative); } else { flag_local = true; } } catch (Exception err) { image_flag = true; } } else if (att1.Name.ToLower() == "class" && att1.Value == "image") { image_flag = true; } } if (!image_flag && !flag_local) { i.Inlines.Add(hl); } else { i.Inlines.Add(n.InnerText.Replace(" ", "")); } } } np.Inlines.Add(i); } } np.Inlines.Add(new LineBreak()); pageBody.Add(np); } } if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } LoadingProductScreen.IsOpen = false; PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollerViewer.InvalidateArrange(); scrollerViewer.InvalidateMeasure(); scrollerViewer.InvalidateScrollInfo(); Content.InvalidateArrange(); Content.InvalidateMeasure(); } }
void InsertDateTimeStamp() { string timeStamp = ""; Paragraph textParagraph = new Paragraph(); Italic its = new Italic(); for (int i = 0; i < 18; i++) timeStamp += "-"; timeStamp += DateTime.Now.ToString(); for (int i = 0; i < 18; i++) timeStamp += "-"; if (string.IsNullOrEmpty(RichTextControl.Text)) { its.Inlines.Add(timeStamp); textParagraph.Inlines.Add(its); RichTextControl.Document.Blocks.Add(textParagraph); textParagraph = new Paragraph(); RichTextControl.Document.Blocks.Add(textParagraph); RichTextControl.CaretPosition = RichTextControl.Document.ContentEnd; } else { RichTextControl.CaretPosition = RichTextControl.Document.ContentEnd; RichTextControl.CaretPosition.InsertTextInRun("\u2028"); its.Inlines.Add(timeStamp); textParagraph.Inlines.Add(its); RichTextControl.Document.Blocks.Add(textParagraph); textParagraph = new Paragraph(); RichTextControl.Document.Blocks.Add(textParagraph); RichTextControl.CaretPosition = RichTextControl.Document.ContentEnd; } RichTextControl.Text = RichTextControl.Text; }
/// <summary> /// Parses an html string to an InlineCollection. The opening tags /// and closing tags MUST match, otherwise the result is undefined. /// </summary> /// <param name="html"></param> /// <remarks> /// The following HTML tags are supported: /// a -> Hyperlink /// b -> Bold /// i -> Italic /// u -> Underline /// br -> LineBreak (close tag optional) /// (plain text) -> Run /// /// The following WPF elements that are valid child elements of Span /// are not supported by this method: /// Figure, Floater, InlineUIContainer. /// </remarks> /// <returns></returns> private static Inline ConvertHtmlToInlines(string html) { if (html == null) throw new ArgumentNullException("html"); // Maintain a stack of the top Span element. For example, // <b><a href="somewhere">click me</a> if you <i>want</i>.</b> // would push an element to the stack for each open tag, and // pop an element from the stack for each close tag. Stack<Span> elementStack = new Stack<Span>(); Span top = new Span(); elementStack.Push(top); for (int index = 0; index < html.Length; ) { int k1 = html.IndexOf('<', index); if (k1 == -1) // all text { top.Inlines.Add(new Run(html.Substring(index))); break; } if (k1 > index) // at least some text { top.Inlines.Add(new Run(html.Substring(index, k1 - index))); index = k1; } // Now 'index' points to '<'. Search for '>'. int k2 = html.IndexOf('>', index + 1); if (k2 == -1) // '<' without '>' { top.Inlines.Add(new Run(html.Substring(index))); break; } string tagString = html.Substring(k1 + 1, k2 - k1 - 1); HtmlElement tag = HtmlElement.Parse(tagString); string tagName = (tag != null) ? tag.Name.ToLowerInvariant() : null; if (tagName == null) // parse failed; output as is { top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } else if (tagName != "" && tagName[0] == '/') // close tag { if (tagName == "/a" && top is Hyperlink || tagName == "/b" && top is Bold || tagName == "/i" && top is Italic || tagName == "/u" && top is Underline || tagName == "/span" && top is Span) // TBD: might pop top element { elementStack.Pop(); top = elementStack.Peek(); } else { // unmatched close tag; output as is. top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } } else // open tag or open-close tag (e.g. <br/>) { Inline element = null; switch (tagName) { case "span": element = new Span(); break; case "a": { Hyperlink hyperlink = new Hyperlink(); if (tag.Attributes != null) { foreach (HtmlAttribute attr in tag.Attributes) { if (attr.Name == "href") hyperlink.NavigateUri = new Uri(attr.Value, UriKind.RelativeOrAbsolute); } } element = hyperlink; } break; case "b": element = new Bold(); break; case "i": element = new Italic(); break; case "u": element = new Underline(); break; case "br": break; } if (element != null) // supported element { // Check global attributes. if (tag.Attributes != null) { foreach (HtmlAttribute attr in tag.Attributes) { if (attr.Name == "title") { ToolTipService.SetShowDuration(element, 60000); element.ToolTip = attr.Value; } } } top.Inlines.Add(element); if (element is Span && // not br html[k2 - 1] != '/') // not self-closed tag { elementStack.Push((Span)element); top = (Span)element; } } else // unsupported element, treat as text { top.Inlines.Add(new Run(html.Substring(k1, k2 - k1 + 1))); } } index = k2 + 1; } // Return the root element. Note that some open tags may not be // closed, but we ignore that. while (elementStack.Count > 0) { top = elementStack.Pop(); } return top; // .Inlines; }
/// <summary> /// Converts an HTML node into an Inline. /// </summary> private static Inline ToInline( HtmlNode node ) { switch ( node.Name ) { case "br": return new LineBreak(); case "a": string text = node.InnerText; string url = node.GetAttributeValue( "href", "" ); if ( string.IsNullOrWhiteSpace( text ) ) { text = url; } var link = new Hyperlink { Inlines = { new Run { Text = text, Foreground = new SolidColorBrush( Colors.Blue ) } }, NavigateUri = new Uri( url, UriKind.Absolute ), TargetName = "42" // can be anything, it just needs to be set }; link.Click += ( _, __ ) => LauncherEx.Launch( url ); return new Span { Inlines = { new Run { Text = " " }, link, new Run { Text = " " }, } }; case "strong": case "b": var bold = new Bold(); foreach ( var child in node.ChildNodes ) { bold.Inlines.Add( ToInline( child ) ); } return bold; case "em": case "i": var italic = new Italic(); foreach ( var child in node.ChildNodes ) { italic.Inlines.Add( ToInline( child ) ); } return italic; case "ul": var unorderedList = new Span(); foreach ( var child in node.ChildNodes ) { var listElem = new Span(); listElem.Inlines.Add( new Run { Text = "● " } ); listElem.Inlines.Add( ToInline( child ) ); unorderedList.Inlines.Add( listElem ); unorderedList.Inlines.Add( new LineBreak() ); } return unorderedList; case "ol": var orderedList = new Span(); for ( int n = 0; n < node.ChildNodes.Count; n++ ) { var listElem = new Span(); listElem.Inlines.Add( new Run { Text = n.ToString() + " " } ); listElem.Inlines.Add( ToInline( node.ChildNodes[n] ) ); orderedList.Inlines.Add( listElem ); orderedList.Inlines.Add( new LineBreak() ); } return orderedList; case "h1": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Bold, FontSize = 32 }; case "h2": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.SemiBold, FontSize = 24 }; case "h3": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.SemiBold, FontSize = 19 }; case "h4": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Medium, FontSize = 17 }; case "h5": return new Run { Text = node.InnerText + Environment.NewLine, FontWeight = FontWeights.Medium, FontSize = 16 }; case "div": case "p": case "blockquote": var container = new Span(); foreach ( var child in node.ChildNodes ) { container.Inlines.Add( ToInline( child ) ); } container.Inlines.Add( new LineBreak() ); container.Inlines.Add( new LineBreak() ); return container; } return new Run { Text = node.PreviousSibling == null ? node.InnerText.TrimStart() : node.InnerText }; }
/// <summary> /// Handle math elements /// </summary> /// <param name="props">The element properties</param> private static void MathElement(ElementProperties props) { Italic i = new Italic(); props.Converter.AddInlineToContainer(i); i.SetResourceReference(Italic.StyleProperty, NamedStyle.Math); }
private static Inline GetInline(FrameworkElement element, InlineDescription description) { Style style = null; if (!string.IsNullOrEmpty(description.StyleName)) { style = element.FindResource(description.StyleName) as Style; if (style == null) throw new InvalidOperationException("The style '" + description.StyleName + "' cannot be found"); } Inline inline = null; switch (description.Type) { case InlineType.Run: var run = new Run(description.Text); inline = run; break; case InlineType.LineBreak: var lineBreak = new LineBreak(); inline = lineBreak; break; case InlineType.Span: var span = new Span(); inline = span; break; case InlineType.Bold: var bold = new Bold(); inline = bold; break; case InlineType.Italic: var italic = new Italic(); inline = italic; break; case InlineType.Hyperlink: var hyperlink = new Hyperlink(); inline = hyperlink; break; case InlineType.Underline: var underline = new Underline(); inline = underline; break; } if (inline != null) { var span = inline as Span; if (span != null) { var childInlines = description.Inlines.Select(inlineDescription => GetInline(element, inlineDescription)) .Where(childInline => childInline != null) .ToList(); span.Inlines.AddRange(childInlines); } if (style != null) inline.Style = style; } return inline; }
public void parse_TalkOriginsContentFAQCompleted(object sender, HtmlDocumentLoadCompleted e) { if (e.Document != null) { e.Document.OptionCheckSyntax = false; IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); int count = 0; IList<Block> pageBody = new List<Block>(); Paragraph paragraph = new Paragraph(); Boolean flag_enteredP = false; foreach (HtmlNode htmlNode in hnc) { if (htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } if (htmlNode.ParentNode != null && htmlNode.ParentNode.Name.ToLower() == "noscript") { continue; } foreach (HtmlNode p in htmlNode.DescendantNodes().ToList()) { flag_enteredP = true; if (p.Name.ToLower() == "i" || p.Name.ToLower() == "em") { String str = ConvertWhitespacesToSingleSpaces(p.InnerText); if (str != " ") { Italic i = new Italic(); i.Inlines.Add(str); paragraph.Inlines.Add(i); } } else if (p.Name.ToLower() == "a") { Hyperlink hl = new Hyperlink(); hl.Inlines.Add(p.InnerText); foreach (HtmlAttribute att1 in p.Attributes) { if (att1.Name.ToLower() == "href") { if (att1.Value.ToCharArray()[0] != '#' && !att1.Value.Contains("ackbib.html")) { String uri = att1.Value; if (!att1.Value.Contains("http://")) { uri = uri + "&topic=" + p.InnerText; } hl.NavigateUri = new Uri("/TalkOriginContentPage.xaml?href=" + uri, UriKind.Relative); paragraph.Inlines.Add(hl); } else { String str = ConvertWhitespacesToSingleSpaces(p.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } } } else if (p.Name.ToLower() == "b") { if (p.ParentNode.Name.ToLower() != "i" && p.ParentNode.Name.ToLower() != "em") { String str = ConvertWhitespacesToSingleSpaces(p.InnerText); if (str != " ") { Bold i = new Bold(); i.Inlines.Add(str); paragraph.Inlines.Add(i); } } } else if (p.Name.ToLower() == "#text") { if (p.ParentNode.Name.ToLower() != "b" && p.ParentNode.Name.ToLower() != "a" && p.ParentNode.Name.ToLower() != "em" && p.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(p.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } else if (p.Name.ToLower() == "img") { foreach (HtmlAttribute a in p.Attributes) { if (a.Name.ToLower() == "alt") { Run run = new Run(); run.Text = a.Value; paragraph.Inlines.Add(run); } } } } paragraph.Inlines.Add(new LineBreak()); } else if (htmlNode.Name.ToLower() == "h1") { PageTitle.Text = htmlNode.InnerText; } /* Problem with other info being pulled along with it else if (htmlNode.Name.ToLower() == "div" && htmlNode.Attributes.Count() > 0) { if (htmlNode.Attributes[0].Name.ToLower() == "class" && htmlNode.Attributes[0].Value == "minus1") { Run run = new Run(); String str = htmlNode.InnerText.Replace("©", "©"); run.Text = " " + htmlNode.InnerText; paragraph.Inlines.Add(run); } }//*/ else if (htmlNode.Name.ToLower() == "address" && htmlNode.Attributes.Count() == 0) { Run run = new Run(); run.Text = "by " + htmlNode.InnerText; paragraph.Inlines.Add(run); } else if (htmlNode.Name.ToLower() == "h2") { TextBlock t = new TextBlock(); t.Text = htmlNode.InnerText; t.TextWrapping = TextWrapping.Wrap; t.Style = (Style)Application.Current.Resources["PhoneTextExtraLargeStyle"]; if (pageBody.Count > 0 || paragraph.Inlines.Count > 0) { if (paragraph.Inlines.Count > 0) { paragraph.Inlines.Add(new LineBreak()); pageBody.Add(paragraph); paragraph = new Paragraph(); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } } pageBody.Clear(); PageBody.Children.Add(t); } } if (!flag_enteredP) { pageBody.Clear(); PageBody.Children.Clear(); paragraph = new Paragraph(); Boolean flag_begin = false; foreach (HtmlNode htmlNode in hnc) { if (htmlNode.Name.ToLower() == "body") { // flag_begin = true; }else if(htmlNode.Name.ToLower()=="#comment"){ if (htmlNode.InnerText.Trim() == "<!-- begin trailer -->") { break; } else if (htmlNode.InnerText.Trim() == "<!-- end header -->") { flag_begin = true; } } else if (flag_begin && htmlNode.Name.ToLower() == "p") { if (paragraph.Inlines.Count > 0 ) { paragraph.Inlines.Add(new LineBreak()); pageBody.Add(paragraph); paragraph = new Paragraph(); } } else if (flag_begin && htmlNode.Name.ToLower() == "#text") { if (htmlNode.ParentNode != null && htmlNode.ParentNode.Name.ToLower() != "b" && htmlNode.ParentNode.Name.ToLower() != "h1" && htmlNode.ParentNode.Name.ToLower() != "h2" && htmlNode.ParentNode.Name.ToLower() != "i" && htmlNode.ParentNode.Name.ToLower() != "em" && htmlNode.ParentNode.Name.ToLower() != "a" && htmlNode.ParentNode.Name.ToLower() != "img" && htmlNode.ParentNode.Name.ToLower() != "area" && htmlNode.ParentNode.Name.ToLower() != "map" && htmlNode.ParentNode.Name.ToLower() != "font" && htmlNode.ParentNode.Name.ToLower() != "#comment") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } else if (flag_begin && htmlNode.ParentNode != null && htmlNode.ParentNode.Name.ToLower() == "noscript") { continue; } else if (flag_begin && htmlNode.Name.ToLower() == "i" || htmlNode.Name.ToLower() == "em") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Italic i = new Italic(); i.Inlines.Add(str); paragraph.Inlines.Add(i); } } else if (flag_begin && htmlNode.Name.ToLower() == "a") { if (!(htmlNode.ParentNode != null && htmlNode.ParentNode.Name.ToLower() == "font")) { Hyperlink hl = new Hyperlink(); hl.Inlines.Add(htmlNode.InnerText); foreach (HtmlAttribute att1 in htmlNode.Attributes) { if (att1.Name.ToLower() == "href") { if (att1.Value.ToCharArray()[0] != '#' && !att1.Value.Contains("ackbib.html")) { String uri = att1.Value; if (!att1.Value.Contains("http://")) { uri = uri + "&topic=" + htmlNode.InnerText; } hl.NavigateUri = new Uri("/TalkOriginContentPage.xaml?href=" + uri, UriKind.Relative); paragraph.Inlines.Add(hl); } else { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } } } } else if (flag_begin && htmlNode.Name.ToLower() == "b" || htmlNode.Name.ToLower() == "strong") { if (htmlNode.ParentNode.Name.ToLower() != "i" && htmlNode.ParentNode.Name.ToLower() != "em") { if (paragraph.Inlines.Count > 0 && htmlNode.ParentNode != null && htmlNode.ParentNode.Name.ToLower() == "dt") { paragraph.Inlines.Add(new LineBreak()); pageBody.Add(paragraph); paragraph = new Paragraph(); } String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Bold i = new Bold(); i.Inlines.Add(str); paragraph.Inlines.Add(i); } if(htmlNode.ParentNode!=null && htmlNode.ParentNode.Name.ToLower()=="dt" && htmlNode.NextSibling!=null && htmlNode.NextSibling.Name.ToLower() != "p"){ paragraph.Inlines.Add(new LineBreak()); } } } else if (flag_begin && htmlNode.Name.ToLower() == "img") { foreach (HtmlAttribute a in htmlNode.Attributes) { if (a.Name.ToLower() == "alt") { Run run = new Run(); run.Text = a.Value; paragraph.Inlines.Add(run); } } } else if (htmlNode.Name.ToLower() == "h1") { PageTitle.Text = htmlNode.InnerText; } else if (htmlNode.Name.ToLower() == "font") { foreach (HtmlAttribute att in htmlNode.Attributes) { if (att.Name.ToLower() == "size" && att.Value == "+2") { TextBlock t = new TextBlock(); t.Text = htmlNode.InnerText.Trim(); t.TextWrapping = TextWrapping.Wrap; t.Style = (Style)Application.Current.Resources["PhoneTextExtraLargeStyle"]; PageBody.Children.Add(t); } else if (att.Name.ToLower() == "size" && att.Value == "-1") { Run run = new Run(); String str = htmlNode.InnerText.Replace("©", "©"); str = str.Replace("©", "©"); run.Text = str.Trim(); paragraph.Inlines.Add(run); } } } else if (htmlNode.Name.ToLower() == "address" && htmlNode.Attributes.Count() == 0) { Run run = new Run(); run.Text = "by " + htmlNode.InnerText; paragraph.Inlines.Add(run); } else if (htmlNode.Name.ToLower() == "h2") { TextBlock t = new TextBlock(); t.Text = htmlNode.InnerText; t.TextWrapping = TextWrapping.Wrap; t.Style = (Style)Application.Current.Resources["PhoneTextExtraLargeStyle"]; if (pageBody.Count > 0 || paragraph.Inlines.Count > 0) { if (paragraph.Inlines.Count > 0) { paragraph.Inlines.Add(new LineBreak()); pageBody.Add(paragraph); paragraph = new Paragraph(); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } } pageBody.Clear(); PageBody.Children.Add(t); } } } if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollViewer1.InvalidateArrange(); scrollViewer1.InvalidateMeasure(); scrollViewer1.InvalidateScrollInfo(); } else { this.NavigationService.Navigate(new Uri("/ContentLoadError.xaml?href="+CurrentPage, UriKind.Relative)); } progress.Visibility = Visibility.Collapsed; }
public void parse_TalkOriginsContentIndexCompleted(object sender, HtmlDocumentLoadCompleted e) { if (e.Document != null) { IList<HtmlNode> hnc = e.Document.DocumentNode.DescendantNodes().ToList(); Boolean flag_content = false; int count = 0; IList<Block> pageBody = new List<Block>(); Paragraph paragraph = new Paragraph(); foreach (HtmlNode htmlNode in hnc) { if (htmlNode.Name.ToLower() == "h2" && htmlNode.Attributes.Count > 0 && htmlNode.Attributes[0].Name.ToLower() == "class" && htmlNode.Attributes[0].Value == "c") { flag_content = true; if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(h2); para.Inlines.Add(new LineBreak()); pageBody.Add(para); } else if (!flag_content && htmlNode.Name.ToLower() == "small" && htmlNode.InnerText.Contains("edited")) { String str = htmlNode.InnerText; str = str.Substring(0, 1).ToUpper() + str.Substring(1, str.Count() - 1); str = str.Replace(" ", " "); str = str.Replace("©", "©"); Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } else if (flag_content && htmlNode.Name.ToLower() == "#text") { if (htmlNode.ParentNode.Name.ToLower() != "h2" && htmlNode.ParentNode.Name.ToLower() != "h3" && htmlNode.ParentNode.Name.ToLower() != "a" && htmlNode.ParentNode.Name.ToLower() != "i") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } else if (flag_content && htmlNode.Name.ToLower() == "i") { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Italic i = new Italic(); i.Inlines.Add(str); paragraph.Inlines.Add(i); } } else if (flag_content && htmlNode.Name.ToLower() == "h3") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(new LineBreak()); para.Inlines.Add(h2); pageBody.Add(para); } else if (flag_content && htmlNode.Name.ToLower() == "h2") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Bold h2 = new Bold(); h2.Inlines.Add(htmlNode.InnerText); Paragraph para = new Paragraph(); para.Inlines.Add(new LineBreak()); para.Inlines.Add(h2); pageBody.Add(para); } else if (flag_content && htmlNode.Name.ToLower() == "ol") { count = 0; } else if (flag_content && htmlNode.Name.ToLower() == "a") { Hyperlink hl = new Hyperlink(); hl.Inlines.Add(htmlNode.InnerText); foreach (HtmlAttribute att1 in htmlNode.Attributes) { if (att1.Name.ToLower() == "href") { if (att1.Value.ToCharArray()[0] != '#') { String p = att1.Value; if (!att1.Value.Contains("http://")) { p = p + "&topic=" + htmlNode.InnerText; } hl.NavigateUri = new Uri("/TalkOriginContentPage.xaml?href=" + p, UriKind.Relative); paragraph.Inlines.Add(hl); } else { String str = ConvertWhitespacesToSingleSpaces(htmlNode.InnerText); if (str != " ") { Run run = new Run(); run.Text = str; paragraph.Inlines.Add(run); } } } } } else if (flag_content && htmlNode.Name.ToLower() == "div" && htmlNode.InnerText.Contains("Previous Claim")) { flag_content = false; } else if (flag_content && htmlNode.Name.ToLower() == "li") { if (paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); paragraph = new Paragraph(); } Run run = new Run(); if (htmlNode.ParentNode.Name.ToLower() == "ol") { count++; run.Text = count + ". "; } else { run.Text = "- "; } paragraph.Inlines.Add(run); } } if (paragraph != null && paragraph.Inlines.Count > 0) { pageBody.Add(paragraph); } foreach (Block b in pageBody) { RichTextBox rtb = new RichTextBox(); rtb.IsReadOnly = true; rtb.VerticalAlignment = VerticalAlignment.Top; rtb.Blocks.Add(b); PageBody.Children.Add(rtb); } PageBody.InvalidateArrange(); PageBody.InvalidateMeasure(); scrollViewer1.InvalidateArrange(); scrollViewer1.InvalidateMeasure(); scrollViewer1.InvalidateScrollInfo(); } else { this.NavigationService.Navigate(new Uri("/ContentLoadError.xaml?href=" + CurrentPage, UriKind.Relative)); } progress.Visibility = Visibility.Collapsed; }
public void TreeWalks_GetNextInsertionPosition () { rtb.SelectAll (); rtb.Selection.Text = ""; // we create the following tree: // paragraph // / \ // bold italic // | // run // Section sec = new Section (); Paragraph p = new Paragraph (); Bold b = new Bold (); Italic i = new Italic (); Run r1 = new Run { Text = "Bold text" }; p.Inlines.Add (b); p.Inlines.Add (i); b.Inlines.Add (r1); rtb.Selection.Insert (p); // now let's do a lot of checks for moving // textpointers around. TextPointer tp; // move forward from paragraph.ContentStart tp = p.ContentStart; tp = tp.GetNextInsertionPosition (LogicalDirection.Forward); Assert.AreEqual (b, tp.Parent, "#7"); // backing up from element.ContentStart gets // us... someplace. and TextPointer.Parent is // bizarre. tp = r1.ContentStart; Assert.AreSame (r1, tp.Parent, "#0"); tp = tp.GetNextInsertionPosition (LogicalDirection.Backward); Assert.AreEqual (typeof (Run), tp.Parent.GetType(), "#1"); Assert.AreNotEqual (r1, tp.Parent, "#2"); Assert.AreEqual (-1, tp.CompareTo (r1.ElementStart), "#3"); // backing up from element.ElementStart gets // us... someplace else. and // TextPointer.Parent is still bizarre. tp = r1.ElementStart.GetNextInsertionPosition (LogicalDirection.Backward); Assert.AreEqual (typeof (Run), tp.Parent.GetType(), "#5"); Assert.AreNotEqual (r1, tp.Parent, "#5"); Assert.AreEqual (-1, tp.CompareTo (r1.ContentStart), "#6"); }
public void TreeWalks_GetPositionAtOffset (FlowDirection fd) { rtb.SelectAll (); rtb.Selection.Text = ""; // we create the following tree: // paragraph // / \ // bold italic // | / \ // run run run // Section sec = new Section (); Paragraph p = new Paragraph (); Bold b = new Bold (); Italic i = new Italic (); Run r1 = new Run { Text = "Bold text" }; Run r2 = new Run { Text = "Italic text1" }; Run r3 = new Run { Text = "Italic text2" }; p.Inlines.Add (b); p.Inlines.Add (i); b.Inlines.Add (r1); i.Inlines.Add (r2); i.Inlines.Add (r3); rtb.Selection.Insert (p); TextPointer tp; int offset = 0; // forward tests from p.ContentStart //////////////////////////////////// // forward 0 offset keeps us at p.ContentStart Console.WriteLine ("1"); tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (p, tp.Parent, "#1-0"); Assert.AreEqual (0, tp.CompareTo (p.ContentStart), "#1-1"); Assert.IsFalse (tp.IsAtInsertionPosition, "#1-2"); // forward 1 offset moves us to b.ContentStart Console.WriteLine ("2"); offset++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (b, tp.Parent, "#2-0"); Assert.AreEqual (0, tp.CompareTo (b.ContentStart), "#2-1"); Assert.IsFalse (tp.IsAtInsertionPosition, "#2-2"); // forward 2 offset moves us to r1.ContentStart Console.WriteLine ("3"); offset++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (r1, tp.Parent, "#3-0"); Assert.AreEqual (0, tp.CompareTo (r1.ContentStart), "#3-1"); Assert.IsTrue (tp.IsAtInsertionPosition, "#3-2"); // forward 3 offset moves us 1 character into the interior of r1 Console.WriteLine ("4"); offset++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (r1, tp.Parent, "#4-0"); Assert.AreEqual (1, tp.CompareTo (r1.ContentStart), "#4-1"); Assert.IsTrue (tp.IsAtInsertionPosition, "#4-2"); // forward 2 + r1.Text.Length moves us to r1.ContentEnd Console.WriteLine ("5"); offset += r1.Text.Length - 1; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (r1, tp.Parent, "#5-0"); Assert.AreEqual (0, tp.CompareTo (r1.ContentEnd), "#5-1"); Assert.IsTrue (tp.IsAtInsertionPosition, "#5-2"); // forward 1 more and we'll be at b.ContentEnd Console.WriteLine ("6"); offset ++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (b, tp.Parent, "#6-0"); Assert.AreEqual (0, tp.CompareTo (b.ContentEnd), "#6-1"); Assert.IsFalse (tp.IsAtInsertionPosition, "#6-2"); // forward 1 more and we're back in the paragraph, between the bold and italic elements Console.WriteLine ("7"); offset++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (p, tp.Parent, "#7-0"); Assert.AreEqual (1, tp.CompareTo (b.ContentEnd), "#7-1"); Assert.AreEqual (-1, tp.CompareTo (i.ContentStart), "#7-2"); Assert.IsFalse (tp.IsAtInsertionPosition, "#7-3"); // forward 1 more and we'll be at i.ContentStart Console.WriteLine ("8"); offset++; tp = p.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Forward); Assert.AreEqual (i, tp.Parent, "#8-0"); Assert.AreEqual (0, tp.CompareTo (i.ContentStart), "#8-1"); Assert.IsFalse (tp.IsAtInsertionPosition, "#8-2"); // backward tests from r3.ContentStart ////////////////////////////////////// // backward 0 keeps us at r3.ContentStart Console.WriteLine ("9"); offset = 0; tp = r3.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Backward); Assert.AreEqual (r3, tp.Parent, "#9-0"); Assert.AreEqual (0, tp.CompareTo (r3.ContentStart), "#9-1"); Assert.IsTrue (tp.IsAtInsertionPosition, "#9-2"); // backward 1 more and we're in the italic element, between r2 and r3 Console.WriteLine ("10"); offset--; tp = r3.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Backward); Assert.AreEqual (i, tp.Parent, "#10-0"); Assert.AreEqual (-1, tp.CompareTo (r3.ContentStart), "#10-1"); Assert.AreEqual (1, tp.CompareTo (r2.ContentEnd), "#10-2"); Assert.IsFalse (tp.IsAtInsertionPosition, "#10-2"); // backward 1 more and we're at r2.ContentEnd offset--; tp = r3.ContentStart.GetPositionAtOffset (offset, LogicalDirection.Backward); Assert.AreEqual (r2, tp.Parent, "#11-0"); Assert.AreEqual (0, tp.CompareTo (r2.ContentEnd), "#11-1"); Assert.IsTrue (tp.IsAtInsertionPosition, "#11-2"); }
private void BuildFeedItemList() { StackPanel_FeedItems.Children.Clear(); Indices.Clear(); // Bygg en lista med index:ar för alla FeedItems och deras associerade Feed. for (int i = 0; i < Feeds.Count; i++) { for (int j = 0; j < Feeds[i].Items.Count; j++) { if (string.IsNullOrWhiteSpace(TextBox_Filter.Text)) { Indices.Add(new SortableIndices(i, j, Feeds[i].Items[j].PublicationDate)); } else if (Feeds[i].Category.Name != null && Feeds[i].Category.Name.Contains(TextBox_Filter.Text)) { Indices.Add(new SortableIndices(i, j, Feeds[i].Items[j].PublicationDate)); } } } // Sortera index-listan efter publikationsdatum (nyast först) Indices.Sort((a, b) => b.PublicationDate.CompareTo(a.PublicationDate)); // Skriv ut föremålen och all relaterad data i StackPanel_FeedItems foreach(SortableIndices index in Indices.Take(30)) { TextBlock textBlock = new TextBlock(); // Skriv ut avsnittets titel { var s = new Span(); s.FontSize = 16; s.FontWeight = FontWeights.Bold; s.Inlines.Add(Feeds[index.FeedIndex].Items[index.FeedItemIndex].Title); textBlock.Inlines.Add(s); } // Skriv ut författare + publiceringsdatum { var i = new Italic(); i.Foreground = Brushes.Gray; i.Inlines.Add("\nby " + Feeds[index.FeedIndex].Title + " on " + Feeds[index.FeedIndex].Items[index.FeedItemIndex].PublicationDate.ToString()); textBlock.Inlines.Add(i); } // Skriv ut play + details-knappar { var h = new Hyperlink(); h.Tag = index; // Spara indicerna så att vi kan nå rätt föremål senare h.Click += new RoutedEventHandler(Hyperlink_Click_DisplayItemDetails); h.TextDecorations = null; h.Inlines.Add("details"); textBlock.Inlines.Add("\n["); textBlock.Inlines.Add(h); textBlock.Inlines.Add("] "); var s = new Span(); s.FontWeight = FontWeights.Bold; var h2 = new Hyperlink(); h2.Tag = index; h2.NavigateUri = new Uri(Feeds[index.FeedIndex].Items[index.FeedItemIndex].MediaUrl); h2.RequestNavigate += new RequestNavigateEventHandler(Hyperlink_RequestNavigate); h2.Click += new RoutedEventHandler(Hyperlink_SetFeedItemHasBeenPlayed); h2.TextDecorations = null; h2.Inlines.Add("play item"); s.Inlines.Add("["); s.Inlines.Add(h2); s.Inlines.Add("] "); var s2 = new Span(); if (Feeds[index.FeedIndex].Items[index.FeedItemIndex].HasBeenPlayed) { s2.Foreground = Brushes.Green; s2.Inlines.Add("Played"); } else { s2.Foreground = Brushes.Red; s2.Inlines.Add("Unplayed"); } s.Inlines.Add(s2); textBlock.Inlines.Add(s); } StackPanel_FeedItems.Children.Add(textBlock); StackPanel_FeedItems.Children.Add(new Separator() { Margin = new Thickness(0, 8, 4, 8) }); } }
private int _formatStackTrace(Exception exception) { var list = new List(); StackTrace stack = null; if (exception != null) { stack = new StackTrace(exception, true); } else { stack = new StackTrace(true); } for (int i = 0; i < stack.FrameCount; i++) { // get next method call var frame = stack.GetFrame(i); var method = frame.GetMethod(); if (method == null) break; if (method.HasAttribute<DebuggerNonUserCodeAttribute>(true)) continue; // skip framework method calls var methodClass = method.ReflectedType; if (methodClass == null) continue; if (_skipNamespaces.IsMatch(methodClass.Namespace)) continue; if (methodClass.HasAttribute<CompilerGeneratedAttribute>(true)) continue; if (_skipClasses.Contains(methodClass)) continue; // format method signature var methodName = methodClass.Name.Nvl("<Module>"); if (method.Name.IndexOf(".ctor") < 0) methodName += "." + method.Name; var methodArgs = ""; ParameterInfo[] P = method.GetParameters(); for (int j = 0, len2 = P.Length; j < len2; j++) { methodArgs += (j > 0 ? ", " : "") + P[j].Name; } var signature = TEXT.FatalError_Signature.Substitute(methodName, methodArgs); // format file location var fileName = frame.GetFileName(); var lineNum = frame.GetFileLineNumber(); if (fileName.NotEmpty()) { fileName = Path.GetFullPath(fileName); } var location = TEXT.FatalError_Location.Substitute(fileName, lineNum); // build list item var row1 = new Run(signature); var row2 = new Italic(new Run(location)); row1.Foreground = BLACK; row2.Foreground = GRAY; var para = new Paragraph(); para.Inlines.Add(row1); para.Inlines.Add(new LineBreak()); para.Inlines.Add(row2); var item = new ListItem(para); item.Margin = new Thickness(0, 0, 0, 5); list.ListItems.Add(item); } var count = list.ListItems.Count; if (count > 0) { var header = new Paragraph(new Run(TEXT.FatalError_StackTrace)); header.FontWeight = FontWeights.Bold; header.Margin = new Thickness(5, 10, 0, 5); _detailsDoc.Blocks.Add(header); list.Margin = new Thickness(0); list.MarkerStyle = TextMarkerStyle.Decimal; list.Padding = new Thickness(25, 0, 0, 0); _detailsDoc.Blocks.Add(list); } return count; }
/// <summary> /// Method creates collection of specialties an add it to the end of object name /// </summary> /// <param name="inlines"></param> /// <param name="specialties"></param> private void _CreateListOfSpecialties(List<Inline> inlines, object parentObject) { string collectionOfSpecialties = null; StringBuilder sb = new StringBuilder(); if (parentObject is Vehicle) foreach (VehicleSpecialty specialty in ((Vehicle)parentObject).Specialties) { if (0 < sb.Length) sb.Append(", "); sb.Append(specialty.Name); } else if (parentObject is Driver) foreach (DriverSpecialty specialty in ((Driver)parentObject).Specialties) { if (0 < sb.Length) sb.Append(", "); sb.Append(specialty.Name); } collectionOfSpecialties += sb.ToString(); if (!string.IsNullOrEmpty(collectionOfSpecialties)) { collectionOfSpecialties = string.Format((string)App.Current.FindResource("SpecialtiesCellText"), collectionOfSpecialties); Italic noOrders = new Italic(new Run(collectionOfSpecialties)); noOrders.Foreground = new SolidColorBrush(Colors.Gray); noOrders.FontSize = (double)App.Current.FindResource("StandartHelpFontSize"); inlines.Add(noOrders); } }
private int _formatErrorLog(ErrorList errorList) { var header = new Paragraph(new Run(TEXT.FatalError_ErrorCount.Substitute(errorList.Summary))); header.FontWeight = FontWeights.Bold; header.Margin = new Thickness(5, 10, 0, 5); _detailsDoc.Blocks.Add(header); var table = new Table(); table.Columns.Add(new TableColumn()); table.Columns.Add(new TableColumn()); table.RowGroups.Add(new TableRowGroup()); table.Columns[0].Width = new GridLength(24); table.Margin = new Thickness(0); foreach (var msg in errorList.Items) { // build list item var icon = new BlockUIContainer(msg.Severity.ToImage(16, new Thickness(4, 0, 4, 3))); var para = new Paragraph(new Run(msg.Text)); if (msg.Details.NotEmpty()) { var details = new Italic(new Run(msg.Details)); details.Foreground = GRAY; para.Inlines.Add(new LineBreak()); para.Inlines.Add(details); para.Margin = new Thickness(0, 0, 0, 4); } var row = new TableRow(); row.Cells.Add(new TableCell(icon)); row.Cells.Add(new TableCell(para)); table.RowGroups[0].Rows.Add(row); } _detailsDoc.Blocks.Add(table); return table.RowGroups[0].Rows.Count; }
public object Convert(object value, Type targetType, object parameter, CultureInfo culture, List<HighlightMatch> highlightSections = null) { if (false == value is List<Section>) { throw new Exception("value must be of type List<Section>."); } if (targetType != typeof(List<Inline>)) { throw new Exception("targetType must be of type List<Inline>."); } //take a COPY of the sections, so that we don't modify the originals List<Section> sections = new List<Section>(value as List<Section>); Section lastSection = new Section(); HighlightMatch[] highlightSectionArray = null == highlightSections ? null : highlightSections.ToArray(); int currentSectionIndex = 0; int progressedSectionLength = 0; List<Section> newSections = new List<Section>(); if (null == highlightSections) { newSections = sections; } else { //parameters: start index, whether we highlight, and whether it's current match List<Tuple<int, bool, bool>> splitPoints = new List<Tuple<int, bool, bool>>(); highlightSections.ForEach(x => { splitPoints.Add(new Tuple<int, bool, bool>(x.MatchStartIndex, true, x.CurrentMatch)); splitPoints.Add(new Tuple<int, bool, bool>(x.MatchStartIndex + x.MatchLength, false, false)); }); bool isHighlighting = false; Brush highlightBrush = null; foreach (var splitPoint in splitPoints) { while (progressedSectionLength + sections[currentSectionIndex].Text.Length < splitPoint.Item1) { Section currentSection = sections[currentSectionIndex]; if (isHighlighting) currentSection.Background = highlightBrush; newSections.Add(currentSection); currentSectionIndex++; progressedSectionLength += currentSection.Text.Length; } int splitIntoSection = splitPoint.Item1 - progressedSectionLength; Section section1 = sections[currentSectionIndex].Clone(); section1.Text = section1.Text.Substring(0, splitIntoSection); section1.Background = isHighlighting ? highlightBrush : null; newSections.Add(section1); progressedSectionLength += section1.Text.Length; Section section2 = sections[currentSectionIndex].Clone(); section2.Text = section2.Text.Substring(splitIntoSection); isHighlighting = splitPoint.Item2; highlightBrush = splitPoint.Item3 ? HighlightingCurrentBrush : HighlightingBrush; section2.Background = isHighlighting ? highlightBrush : null; //newSections.Add(section2); sections[currentSectionIndex] = section2; } for (int i = currentSectionIndex; i < sections.Count; i++) newSections.Add(sections[i]); } List<Inline> result = new List<Inline>(); foreach (Section section in newSections) { Inline inline = new Run(section.Text); if (section.Colour != lastSection.Colour) { inline.Foreground = new SolidColorBrush(section.Colour); } if (section.Style != lastSection.Style) { if (section.Style == NoteStyle.Italic) { inline = new Italic(inline); } } if (section.Weight != lastSection.Weight) { if (section.Weight == NoteWeight.Bold) { inline = new Bold(inline); } } if (section.Background != null) { inline.Background = section.Background; } result.Add(inline); } return result; }
private static Span CreateSpan(InlineType inlineType, string param) { Span span = null; switch (inlineType) { case InlineType.Hyperlink: Hyperlink link = new Hyperlink(); Uri uri; if (Uri.TryCreate(param, UriKind.Absolute, out uri)) { link.NavigateUri = uri; } span = link; break; case InlineType.Bold: span = new Bold(); break; case InlineType.Italic: span = new Italic(); break; case InlineType.Underline: span = new Underline(); break; default: span = new Span(); break; } return span; }
// Recursively parses the given Html node into a corresponding Inline element private static Inline _parseHTMLNode(XNode node, HtmlBlock source) { if (node.NodeType == XmlNodeType.Text) { var text = ((XText)node).Value; text = text.ReplaceAll(_reWhitespace, " "); text = text.ReplaceAll(_reEncodedEntity, match => { var code = match.Groups[1].Value; if (code.At(0) == "#") { return Char.ConvertFromUtf32(Int32.Parse(code.After(0))); } else if (_htmlEntities.ContainsKey(code)) { return Char.ConvertFromUtf32(_htmlEntities[code]); } else { throw new Exception(TEXT.HtmlBlock_UnrecognizedChar.Substitute(code)); } }); return new Run(text); } if (node.NodeType != XmlNodeType.Element) { return null; } var tag = (XElement)node; var name = tag.Name.LocalName.ToLower(); Span outer = null; Brush emphBrush = null; double fontSize = 11; double paraBreak = 0; if (source != null) { emphBrush = source.EmphasizedForeground; fontSize = Double.IsNaN(source.FontSize) ? 11 : source.FontSize; } // hyperlink if (name == "a") { var link = new Hyperlink(); var href = tag.Get<Uri>("href"); if (href != null) link.NavigateUri = href; var trg = tag.Get("target"); if (trg.NotEmpty()) link.TargetName = trg; outer = link; } // bold else if (name == "b") { outer = new Bold(); } // big else if (name == "big") { outer = new Span(); outer.FontSize = fontSize * _fontFactors[4]; } // line break else if (name == "br") { return new LineBreak(); } // code else if (name == "c" || name == "code") { outer = new Span(); outer.FontFamily = new FontFamily("Courier New"); } // code else if (name == "em") { outer = new Span(); if (emphBrush != null) outer.Foreground = emphBrush; } // font style else if (name == "font") { outer = new Span(); var face = tag.Get("face"); if (face.NotEmpty()) outer.FontFamily = new FontFamily(face); var brush = tag.Get<Brush>("color", null); if (brush != null) outer.Foreground = brush; var size = tag.Get<int>("size", -1); if (size > 0) outer.FontSize = size; } // header 1-6 else if (name.Matches(_reHeaderTag)) { outer = new Bold(); if (emphBrush != null) outer.Foreground = emphBrush; outer.FontSize = fontSize * _fontFactors[7-Int32.Parse(name.At(1))]; paraBreak = 1; } // italic else if (name == "i") { outer = new Italic(); } // image else if (name == "img") { outer = new Span(); var uic = new InlineUIContainer(); var img = new Image(); var src = tag.GetImage("src"); if (src != null) img.Source = src; var w = tag.Get<int>("width", -1); if (w >= 0) img.Width = w; var h = tag.Get<int>("height", -1); if (h >= 0) img.Height = h; uic.Child = img; outer.Inlines.Add(uic); } // paragraph else if (name == "p") { outer = new Span(); paraBreak = 4; } // small else if (name == "small") { outer = new Span(); outer.FontSize = fontSize * _fontFactors[2]; } // span else if (name == "span") { outer = new Span(); } // underline else if (name == "u") { outer = new Underline(); } // invalid tag else { throw new Exception(TEXT.HtmlBlock_UnrecognizedTag.Substitute(tag.Name.LocalName)); } var tip = tag.GetImage("title"); if (tip != null) { outer.ToolTip = tip; } foreach (var child in tag.Nodes()) { var inner = _parseHTMLNode(child, source); if (inner != null) outer.Inlines.Add(inner); } if (paraBreak == 0) return outer; var para = new Span(); para.Inlines.Add(outer); para.Inlines.Add(new LineBreak()); var blankline = new Span(); blankline.FontSize = paraBreak; para.Inlines.Add(blankline); para.Inlines.Add(new LineBreak()); return para; }
private static Inline GetInline(FrameworkElement element, SubtitleDescription description) { FontFamily fontFamily = null; if (description.FontFace != null) fontFamily = new FontFamily(description.FontFace); Style style = null; Inline inline = null; switch (description.Type) { case InlineType.Run: var run = new Run(description.Text); if (description.FontSize != null) run.FontSize = double.Parse(description.FontSize); if (fontFamily != null) run.FontFamily = fontFamily; inline = run; break; case InlineType.LineBreak: var lineBreak = new LineBreak(); inline = lineBreak; break; case InlineType.Span: var span = new Span(); inline = span; break; case InlineType.Bold: var bold = new Bold(); inline = bold; break; case InlineType.Italic: var italic = new Italic(); inline = italic; break; case InlineType.Hyperlink: var hyperlink = new Hyperlink(); inline = hyperlink; break; case InlineType.Underline: var underline = new Underline(); inline = underline; break; } if (inline != null) { var span = inline as Span; if (span != null) { var childInlines = new List<Inline>(); foreach (var inlineDescription in description.Subtitles) { var childInline = GetInline(element, inlineDescription); if (childInline == null) continue; childInlines.Add(childInline); } span.Inlines.AddRange(childInlines); } } return inline; }