/// <summary> /// Renders the specified chat node to the client. /// </summary> /// <param name="node">The node to append.</param> /// <remarks> /// <para>The return value of this function is a reference to the outermost <see cref="HtmlElement">HtmlElement</see> constructed /// by this function. It may create additional inner elements as needed.</para> /// </remarks> /// <returns> /// Returns an object instance of <see cref="HtmlElement">HtmlElement</see> that can be appended to the HTML document. /// </returns> public override Inline Render(ChatNode node) { IIconProvider provider = ProfileResourceProvider.GetForClient(null).Icons; ImageChatNode icn = node as ImageChatNode; if (icn != null) { InlineUIContainer result = new InlineUIContainer(); Image img = new Image(); img.Source = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap((icn.Image as System.Drawing.Bitmap).GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); img.ToolTip = icn.Text; img.Width = provider.IconSize.Width; img.Height = provider.IconSize.Height; result.Child = img; if (icn.LinkUri != null) { Hyperlink container = new Hyperlink(result); container.NavigateUri = node.LinkUri; container.ToolTip = string.Format(CultureInfo.CurrentUICulture, "Link to {0}", node.LinkUri); return container; } return result; } else { return base.Render(node); } }
internal object GetObject() { if (_type == ElementType.Hyperlink || _type == ElementType.Paragraph || (_type >= ElementType.Table && _type <= ElementType.TableCell)) { if (_object == null) { _object = BuildObjectTree(); } return(_object); } if (!(_type == ElementType.Object || _type == ElementType.InlineUIContainer)) { // This is currently not implemented for any other type return(null); } Image im = GetImage(); object o = im; if (_type == ElementType.InlineUIContainer) { InlineUIContainer c = new InlineUIContainer(); c.Child = im; o = c; } return(o); }
Inline CreateBaseLink(string content, string contextHeader, string contextTag, MenuItem customButton = null) { var link = new HyperlinkButton { Content = content, FontSize = Text.FontSize, FontWeight = Text.FontWeight, FontStretch = Text.FontStretch, FontFamily = Text.FontFamily, TargetName = contextTag, Margin = new Thickness(-10, -5, -10, -8) }; link.Click += new RoutedEventHandler(link_Click); MenuItem item = new MenuItem { Header = contextHeader, Tag = contextTag, Foreground = new SolidColorBrush(Colors.Black) }; item.Click += new RoutedEventHandler(CopyLink); ContextMenu menu = new ContextMenu(); menu.Items.Add(item); if (customButton != null) menu.Items.Add(customButton); ContextMenuService.SetContextMenu(link, menu); InlineUIContainer container = new InlineUIContainer(); container.Child = link; return container; }
// Token: 0x06002D1E RID: 11550 RVA: 0x000CBA38 File Offset: 0x000C9C38 internal object GetObject() { if (this._type == FixedElement.ElementType.Hyperlink || this._type == FixedElement.ElementType.Paragraph || (this._type >= FixedElement.ElementType.Table && this._type <= FixedElement.ElementType.TableCell)) { if (this._object == null) { this._object = this.BuildObjectTree(); } return(this._object); } if (this._type != FixedElement.ElementType.Object && this._type != FixedElement.ElementType.InlineUIContainer) { return(null); } Image image = this.GetImage(); object result = image; if (this._type == FixedElement.ElementType.InlineUIContainer) { result = new InlineUIContainer { Child = image }; } return(result); }
// Token: 0x06003AFD RID: 15101 RVA: 0x0010A660 File Offset: 0x00108860 internal virtual void InsertEmbeddedUIElementVirtual(FrameworkElement embeddedElement) { Invariant.Assert(this.HasConcreteTextContainer, "Can't insert embedded object to non-TextContainer range!"); Invariant.Assert(embeddedElement != null); TextRangeBase.BeginChange(this); try { this.Text = string.Empty; TextPointer textPointer = TextRangeEditTables.EnsureInsertionPosition(this.Start); Paragraph paragraph = textPointer.Paragraph; if (paragraph != null) { if (Paragraph.HasNoTextContent(paragraph)) { BlockUIContainer blockUIContainer = new BlockUIContainer(embeddedElement); blockUIContainer.TextAlignment = TextRangeEdit.GetTextAlignmentFromHorizontalAlignment(embeddedElement.HorizontalAlignment); paragraph.SiblingBlocks.InsertAfter(paragraph, blockUIContainer); paragraph.SiblingBlocks.Remove(paragraph); this.Select(blockUIContainer.ContentStart, blockUIContainer.ContentEnd); } else { InlineUIContainer inlineUIContainer = new InlineUIContainer(embeddedElement); TextPointer textPointer2 = TextRangeEdit.SplitFormattingElements(this.Start, false); textPointer2.InsertTextElement(inlineUIContainer); this.Select(inlineUIContainer.ElementStart, inlineUIContainer.ElementEnd); } } } finally { TextRangeBase.EndChange(this); } }
/// <summary> /// Adds the picture to the rich textbox. /// </summary> /// <param name="imagelocation">The imagelocation.</param> private void AddPicture(string imagelocation) { var bitmap = new BitmapImage(new Uri(imagelocation)); var image = new Image {Source = bitmap, Width = 35}; var uiContainer = new InlineUIContainer(image); var tp = txtMessageToSend.CaretPosition; if (tp.Paragraph != null) tp.Paragraph.Inlines.Add(uiContainer); }
public MessageTextBlock(ResourceDictionary rd) { resDict = rd; Date = new Run(""); chatImage = null; Nickname = new Run(""); ToName = new Run(""); Message = new Run(""); }
private void UpdateVersions() { TextBlock.Blocks.Clear(); if (ConflictVersionInfo == null) { return; } var para = new Paragraph(); var navigateCommand = new NavigateToCommand(); var count = 1; foreach (var version in ConflictVersionInfo) { var versionId = version.Value<string>("Id"); var sourceId = version.Value<string>("SourceId"); ReplicationSourceInfo sourceInfo = null; if (ReplicationSourcesLookup != null) { ReplicationSourcesLookup.TryGetValue(sourceId, out sourceInfo); } var hyperlink = new InlineUIContainer() { Child = new HyperlinkButton() { Content = count.ToString() + (sourceInfo != null ? " (" + sourceInfo.Name + ")" : ""), Command = navigateCommand, CommandParameter = "/edit?id=" + versionId } }; if (sourceInfo != null) { var toolTip = CreateToolTip(versionId, sourceInfo); ToolTipService.SetToolTip(hyperlink.Child, toolTip); } para.Inlines.Add(hyperlink); para.Inlines.Add(" "); count++; } TextBlock.Blocks.Add(para); }
protected override void Write([NotNull] WpfRenderer renderer, [NotNull] MathInline obj) { var text = obj.Content.Text.Substring(obj.Content.Start, obj.Content.Length); TexFormula formula = null; try { formula = formulaParser.Parse(text); } catch (Exception) { renderer.WriteInline(new Run("[!!FORMULA PARSE ERROR!!]") { Tag = obj }); return; } var fontSize = renderer.CurrentFontSize(); var formulaRenderer = formula.GetRenderer(TexStyle.Display, fontSize, "Arial"); var geo = formulaRenderer.RenderToGeometry(0, 0); var geoD = new System.Windows.Media.GeometryDrawing(Brushes.Black, null, geo); var di = new DrawingImage(geoD); var uiImage = new System.Windows.Controls.Image() { Source = di }; uiImage.Height = formulaRenderer.RenderSize.Height; // size image to match rendersize -> get a zoom of 100% uiImage.Margin = new System.Windows.Thickness(0, 0, 0, -formulaRenderer.RenderSize.Height * formulaRenderer.RelativeDepth); // Move image so that baseline matches that of text var uiInline = new System.Windows.Documents.InlineUIContainer() { Child = uiImage, Background = Brushes.Yellow, BaselineAlignment = System.Windows.BaselineAlignment.Baseline, Tag = obj, }; renderer.WriteInline(uiInline); }
// Token: 0x060030A0 RID: 12448 RVA: 0x000DB424 File Offset: 0x000D9624 private int AddUIElement(UIElement uiElement, bool returnIndex) { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } InlineUIContainer inlineUIContainer = Inline.CreateImplicitInlineUIContainer(base.Parent); int result; if (returnIndex) { result = base.OnAdd(inlineUIContainer); } else { base.Add(inlineUIContainer); result = -1; } inlineUIContainer.Child = uiElement; return(result); }
// Worker for OnAdd and Add(UIElement). // If returnIndex == true, uses the more costly IList.Add // to calculate and return the index of the newly inserted // Run, otherwise returns -1. private int AddUIElement(UIElement uiElement, bool returnIndex) { if (uiElement == null) { throw new ArgumentNullException("uiElement"); } InlineUIContainer implicitInlineUIContainer = Run.CreateImplicitInlineUIContainer(this.Parent); int index; if (returnIndex) { index = base.OnAdd(implicitInlineUIContainer); } else { this.Add(implicitInlineUIContainer); index = -1; } implicitInlineUIContainer.Child = uiElement; return(index); }
public static void ParseInlineUIContainer(MessagePack msgPack, InlineUIContainer inlineUIContainer) { ImageEx child = inlineUIContainer.Child as ImageEx; if (child != null) { ParseImage(msgPack, child); } }
private void ParseInlineUIContainer(MessagePack msgPack, InlineUIContainer inlineUIContainer) { ImageEx child = inlineUIContainer.Child as ImageEx; if (child != null) { this.ParseImage(msgPack, child); } }
internal object GetObject() { if (_type == ElementType.Hyperlink || _type == ElementType.Paragraph || (_type >= ElementType.Table && _type <= ElementType.TableCell)) { if (_object == null) { _object = BuildObjectTree(); } return _object; } if (!(_type == ElementType.Object || _type == ElementType.InlineUIContainer)) { // This is currently not implemented for any other type return null; } Image im = GetImage(); object o = im; if (_type == ElementType.InlineUIContainer) { InlineUIContainer c = new InlineUIContainer(); c.Child = im; o = c; } return o; }
private void AppendImage(HtmlNode node, Paragraph paragraph) { AppendLineBreak(node, paragraph, null, false); InlineUIContainer inlineContainer = new InlineUIContainer(); Image image = new Image(); if (node.Attributes["src"] != null) { BitmapImage bitmap = new BitmapImage(new Uri(node.Attributes["src"].Value)); bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.ImageOpened += delegate { double bitmapWidth = bitmap.PixelWidth; double actualWidth = currentRtb.ActualWidth; image.Source = bitmap; if (bitmapWidth < actualWidth) { image.Width = bitmapWidth; } }; if(node.ParentNode.Name.Equals("a")) //is nedsted in hyperlink { //lets go to the link. image.Tap += (sender, args) => { PostPageView page = ControlFinder.FindParent<PostPageView>(this); if (page != null) { page.Browse(node.ParentNode.Attributes["href"].Value); } }; } } inlineContainer.Child = image; image.Stretch = Stretch.Uniform; paragraph.Inlines.Add(inlineContainer); AppendChildren(node, paragraph, null); AppendLineBreak(node, paragraph, null, false); }
private Inline CreateGrid(DocTree tree) { Grid g = new Grid(); int rowMax = 0; int colMax = 0; Dictionary<int, Dictionary<int, RichTextBox>> cells = new Dictionary<int, Dictionary<int, RichTextBox>>(); foreach (var child in tree.Children) { Span span = new Span(); DocTreeToTextElement(child, span.Inlines); int row = child.Row - 1; int col = child.Column - 1; if (!cells.ContainsKey(col)) cells.Add(col, new Dictionary<int, RichTextBox>()); var column = cells[col]; if (!column.ContainsKey(row)) { var spanel = new RichTextBox() { BorderThickness = new Thickness(0), IsReadOnly = true }; spanel.SetValue(Grid.ColumnProperty, col); spanel.SetValue(Grid.RowProperty, row); column.Add(row, spanel); g.Children.Add(spanel); } RichTextBox tb = column[row]; tb.Selection.Insert(span); rowMax = (int)Math.Max(rowMax, child.Row); colMax = (int)Math.Max(colMax, child.Column); } for (int i = 0; i < rowMax; i++) g.RowDefinitions.Add(new RowDefinition()); for (int i = 0; i < colMax; i++) g.ColumnDefinitions.Add(new ColumnDefinition()); InlineUIContainer c = new InlineUIContainer() { Child = g }; return c; }
private Inline GetImageControl(Uri uri, string url) { InlineUIContainer cacheItem = GetImage(url); InlineUIContainer container; BitmapImage bmp; if (cacheItem != null) //命中缓存 { container = cacheItem; //取出缓存 bmp = (BitmapImage)((Image)container.Child).Source; } else //缓存未命中 { //构建新的Container bmp = new BitmapImage(uri); Image img = new Image() { Width = 200, MaxHeight = 200, Source = bmp }; container = new InlineUIContainer(img); CacheImage(url, container); //存入缓存 } Hyperlink link = new Hyperlink(container); link.Tag = url; link.ToolTip = url; link.Click += Hyperlink_Click; link.DataContext = new { ImageUri = uri, ImageUrl = string.Intern(uri.ToString()), ShortUrl = url, Image = bmp, Link = link, }; link.ContextMenu = (ContextMenu)Application.Current.FindResource("ImageInlineMenu"); link.ContextMenuOpening += new ContextMenuEventHandler((sender_, ____) => { var hl = (Hyperlink)sender_; hl.ContextMenu.DataContext = hl.DataContext; }); link.TextDecorations = null; return link; }
// 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; }
/// <summary> /// Updates both text boxes. Applies lock icons to locked runs in the after box /// </summary> /// <param name="percent"></param> private void updateParagraphs(double percent) { currentPercent = percent; int newLength = (int)Math.Round(data.longestLength * percent); List<PatchSelection> selections = data.getPatchSelections(newLength); runMap = new Dictionary<Run, PatchSelection>(); List<Run> beforeRuns = getOriginalRuns(selections); before.Inlines.Clear(); before.Inlines.AddRange(beforeRuns); List<Run> afterRuns = getShortenedRuns(selections); after.Inlines.Clear(); after.Inlines.AddRange(afterRuns); //The list of locked runs. Must be dealt with later to avoid altering the collection we're iterating through List<Run> lockedRuns = new List<Run>(); foreach (Inline inline in after.Inlines) { if (!(inline is Run)) { continue; } Run tempRun = inline as Run; if ((runMap[tempRun].patch as ShortnPatch).isLocked) { lockedRuns.Add(tempRun); } } // Add the lock icon to the locked runs foreach (Run run in lockedRuns) { Image img = new Image(); BitmapImage bmi = new BitmapImage(new Uri(Soylent.GetAppDirectory() + @"lock.png")); img.Source = bmi; img.Height = 9; img.Width = 9; InlineUIContainer iuc = new InlineUIContainer(img, run.ContentEnd); // Can kill Word if that run.TextPointer is not currently displayed iuc.ContextMenu = run.ContextMenu; iuc.Cursor = Cursors.Hand; iuc.MouseUp +=new MouseButtonEventHandler(lockClickHandler); } }
/// <summary> /// Handle media link inline elements /// </summary> /// <param name="props">The element properties</param> private static void MediaLinkInlineElement(ElementProperties props) { InlineUIContainer inlineImage = new InlineUIContainer(); XElement imageElement = props.Element.Descendants(ddue + "image").FirstOrDefault(); XAttribute href; Image image = new Image(); KeyValuePair<string, string> imageInfo = new KeyValuePair<string, string>(null, null); string id = "???"; if(imageElement != null) { href = imageElement.Attribute(xlink + "href"); if(href != null) { id = href.Value; if(!props.Converter.MediaFiles.TryGetValue(id, out imageInfo)) imageInfo = new KeyValuePair<string, string>(null, null); } } if(!String.IsNullOrEmpty(imageInfo.Key) && File.Exists(imageInfo.Key)) { var bm = new BitmapImage(); // Cache on load to prevent it locking the image bm.BeginInit(); bm.CacheOption = BitmapCacheOption.OnLoad; bm.UriSource = new Uri(imageInfo.Key); bm.EndInit(); // Use the actual image size to mimic the HTML layout image.Height = bm.Height; image.Width = bm.Width; image.ToolTip = !String.IsNullOrEmpty(imageInfo.Value) ? imageInfo.Value : "ID: " + id + "\nFilename: " + imageInfo.Key; image.Margin = new Thickness(5, 0, 5, 0); image.Source = bm; inlineImage.Child = image; } else inlineImage.Child = new TextBlock { Text = String.Format(CultureInfo.InvariantCulture, "[INVALID IMAGE ID: {0}]", id), Background = new SolidColorBrush(Colors.Red), Foreground = new SolidColorBrush(Colors.White) }; props.Converter.AddInlineToContainer(inlineImage); props.ReturnToParent = props.ParseChildren = false; }
internal static IList<Inline> RichTranslateChatMessage(string message) { IList<Inline> inlines = new List<Inline>(); var parts = message.Split('#'); bool isFirst = false; foreach (var part in parts) { int index; if (isFirst || part.Length < 2 || !int.TryParse(part.Substring(0, 2), out index)) { inlines.Add(new Run(part)); continue; } string key = string.Format("Facial.{0}.Image", index); if (!_imageDict.Contains(key)) { inlines.Add(new Run(part)); continue; } else { InlineUIContainer container = new InlineUIContainer(new Image() { Source = _imageDict[key] as ImageSource, Width = 18, Height = 18 }); inlines.Add(container); if (part.Length > 2) { inlines.Add(new Run(part.Substring(2))); } } } return inlines; }
private void BuildText(ChatMessage msg) { var text = msg.Message; var weight = (msg.Type == ItemType.Question) ? FontWeights.Bold : FontWeights.Normal; var set = TwitchHttp.Instance.ImageSet; if (set == null) { var run = new Run(text) { FontWeight = weight, BaselineAlignment = BaselineAlignment.Center }; m_messages.Add(run); Inlines.Add(run); return; } int curr = 0; var emoticons = from item in set.Find(text, m_user.IconSet) orderby item.Item2, item.Item3 descending, item.Item1.Default select item; foreach (var item in emoticons) { var emote = item.Item1; var start = item.Item2; var len = item.Item3; if (start < curr) continue; Image img = GetImage(emote); if (img != null) { if (curr < start) { var run = new Run(text.Slice(curr, start)) { FontWeight = weight, BaselineAlignment = BaselineAlignment.Center }; m_messages.Add(run); Inlines.Add(run); } InlineUIContainer cont = new InlineUIContainer(img); cont.BaselineAlignment = BaselineAlignment.Center; Inlines.Add(cont); } else { var run = new Run(text.Slice(curr, start + len)) { FontWeight = weight, BaselineAlignment = BaselineAlignment.Center }; m_messages.Add(run); Inlines.Add(run); } curr = start + len; } if (curr < text.Length) { var run = new Run(text.Substring(curr)) { FontWeight = weight, BaselineAlignment = BaselineAlignment.Center }; m_messages.Add(run); Inlines.Add(run); } }
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) { ContentInfo content = value as ContentInfo; if (string.IsNullOrEmpty(content.content)) { return new FlowDocument(); } var flowDocument = new FlowDocument(); var para = new Paragraph(); TextBlock tb = new TextBlock(); var str = content.content; char surrogate1St = '\0'; StringBuilder unicodeCodes = new StringBuilder(); for (int i = 0; i < str.Length; i++) { int utf16Code = System.Convert.ToInt32(str[i]); string hexOutput = String.Format("{0:x}", utf16Code); if (surrogate1St != 0) { if (utf16Code >= 0xDC00 && utf16Code <= 0xDFFF) { int surrogate2Nd = utf16Code; String unicodeCode = String.Format("{0:x}", (surrogate1St - 0xD800) * (1 << 10) + (1 << 16) + (surrogate2Nd - 0xDC00)); unicodeCodes.Append(unicodeCode); if (EmojiStatic.EmojiList.Select(x => x.Key).Any(x => x == ("u" + unicodeCode))) { var bitmap = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + "//emoji//u" + unicodeCode + ".png")); var image = new Image { Width = 20, Height = 20, Stretch = Stretch.Uniform, Source = bitmap }; //图片缩放模式 InlineUIContainer iuc = new InlineUIContainer(image); tb.Inlines.Add(iuc); } else { } } surrogate1St = '\0'; } else if (utf16Code >= 0xD800 && utf16Code <= 0xDBFF) { surrogate1St = str[i]; } else { tb.Inlines.Add(new Run(str[i].ToString())); } } para.Inlines.Add(new InlineUIContainer(tb)); flowDocument.Blocks.Add(para); return flowDocument; }
//------------------------------------------------------------------- // // IContentHost Members // //------------------------------------------------------------------- #region IAddChild members ///<summary> /// Called to Add the object as a Child. ///</summary> ///<param name="value"> /// Object to add as a child ///</param> void IAddChild.AddChild(Object value) { if (value == null) { throw new ArgumentNullException("value"); } EnsureComplexContent(); if (!(_complexContent.TextContainer is TextContainer)) { throw new ArgumentException(SR.Get(SRID.TextPanelIllegalParaTypeForIAddChild, "value", value.GetType())); } // Get parent of the text container. Note that it can be not a "this" TextBlock - in case // when a TextBlock is used as a storage for plain TextBox - as an owner of a text container. Type parentType = _complexContent.TextContainer.Parent.GetType(); Type valueType = value.GetType(); // Do implicit conversion to allowed inline type - if possible if (!TextSchema.IsValidChildOfContainer(parentType, /*childType*/valueType)) { if (value is UIElement) { value = new InlineUIContainer((UIElement)value); } else { throw new ArgumentException(SR.Get(SRID.TextSchema_ChildTypeIsInvalid, parentType.Name, valueType.Name)); } } // Insert inline element into the text container Invariant.Assert(value is Inline, "Schema validation helper must guarantee that invalid element is not passed here"); TextContainer textContainer = (TextContainer)_complexContent.TextContainer; textContainer.BeginChange(); try { TextPointer endPosition = textContainer.End; textContainer.InsertElementInternal(endPosition, endPosition, (Inline)value); } finally { textContainer.EndChange(); } }
/// <summary> /// Renders DOM text elements recursively, i.e. including their childs. /// </summary> /// <param name="e">The root DOM text element.</param> /// <returns>The corresponding Wpf element.</returns> /// <exception cref="System.InvalidOperationException"> /// </exception> /// <exception cref="System.NotImplementedException"></exception> public object RenderRecursively(TextElement e) { object wpf = null; switch (e) { case BlockUIContainer buc: { wpf = new swd.BlockUIContainer(); } break; case FlowDocument flowDocument: { // make sure the standard colors were set flowDocument.Foreground = ExCSS.Color.Black; flowDocument.Background = ExCSS.Color.White; var flowDocumente = new swd.FlowDocument() { Name = NameOfFlowDocument }; if (TemplateBindingViewportWidth is null) { TemplateBindingViewportWidth = new Binding("ColumnWidth") { Source = flowDocumente } } ; if (TemplateBindingViewportHeight is null) { TemplateBindingViewportHeight = new Binding("ColumnWidth") { Source = flowDocumente } } ; // Binding to ColumnWidth is not optimal, but better than nothing! if (flowDocument.Background.HasValue) { flowDocumente.Background = GetBrushFromColor(flowDocument.Background.Value); } if (flowDocument.Foreground.HasValue) { flowDocumente.Foreground = GetBrushFromColor(flowDocument.Foreground.Value); } wpf = flowDocumente; } break; case Hyperlink hl: { var hle = new swd.Hyperlink(); if (!string.IsNullOrEmpty(hl.NavigateUri)) { if (System.Uri.TryCreate(hl.NavigateUri, UriKind.RelativeOrAbsolute, out var uri)) { hle.NavigateUri = uri; } } if (!string.IsNullOrEmpty(hl.TargetName)) { hle.TargetName = hl.TargetName; } wpf = hle; } break; case Image image: { var imagee = new System.Windows.Controls.Image(); if (!string.IsNullOrEmpty(image.Source)) { imagee.SetBinding(System.Windows.Controls.Image.SourceProperty, $"ImageProvider[{image.Source}]"); } if (image.Width == null && image.Height == null) { imagee.Stretch = System.Windows.Media.Stretch.Uniform; var binding = new Binding() { RelativeSource = RelativeSource.Self, Path = new System.Windows.PropertyPath("Source") }; binding.Converter = ImageToImageWidthConverter.Instance; imagee.SetBinding(System.Windows.Controls.Image.WidthProperty, binding); } else { imagee.Stretch = System.Windows.Media.Stretch.Uniform; } if (image.Width != null) { if (image.Width.IsPurelyAbsolute(out var widthPx)) { imagee.Width = widthPx; } else { var multibinding = new MultiBinding(); multibinding.Bindings.Add(new Binding() { Source = TemplateBindingViewportWidth.Source, Path = TemplateBindingViewportWidth.Path }); multibinding.Bindings.Add(new Binding() { Source = TemplateBindingViewportHeight.Source, Path = TemplateBindingViewportHeight.Path }); multibinding.Converter = CompoundLengthConverter.Instance; multibinding.ConverterParameter = GetCompoundLengthConverterParameters(image.Width); imagee.SetBinding(System.Windows.Controls.Image.WidthProperty, multibinding); } } if (image.Height != null) { if (image.Height.IsPurelyAbsolute(out var heightPx)) { imagee.Height = heightPx; } else { var multibinding = new MultiBinding(); multibinding.Bindings.Add(new Binding() { Source = TemplateBindingViewportWidth.Source, Path = TemplateBindingViewportWidth.Path }); multibinding.Bindings.Add(new Binding() { Source = TemplateBindingViewportHeight.Source, Path = TemplateBindingViewportHeight.Path }); multibinding.Converter = CompoundLengthConverter.Instance; multibinding.ConverterParameter = GetCompoundLengthConverterParameters(image.Height); imagee.SetBinding(System.Windows.Controls.Image.HeightProperty, multibinding); } } // set max-width and max-height if (image.MaxWidth != null && image.MaxWidth.Value.IsAbsolute) { imagee.MaxWidth = image.MaxWidth.Value.ToPixel(); } else if (image.MaxWidth == null || image.MaxWidth.Value.Type == ExCSS.Length.Unit.Vw) { double vwValue = image.MaxWidth.HasValue ? image.MaxWidth.Value.Value : 100; var binding = new Binding() { Source = TemplateBindingViewportWidth.Source, Path = TemplateBindingViewportWidth.Path }; binding.Converter = RelativeSizeConverter.Instance; binding.ConverterParameter = vwValue; imagee.SetBinding(System.Windows.Controls.Image.MaxWidthProperty, binding); } else { throw new InvalidProgramException(); } if (image.MaxHeight != null && image.MaxHeight.Value.IsAbsolute) { imagee.MaxHeight = image.MaxHeight.Value.ToPixel(); } else if (image.MaxHeight == null || image.MaxHeight.Value.Type == ExCSS.Length.Unit.Vh) { double vhValue = image.MaxHeight.HasValue ? image.MaxHeight.Value.Value : 100; var binding = new Binding() { Source = TemplateBindingViewportWidth.Source, Path = TemplateBindingViewportWidth.Path }; binding.Converter = RelativeSizeConverter.Instance; binding.ConverterParameter = vhValue; imagee.SetBinding(System.Windows.Controls.Image.MaxHeightProperty, binding); } else { throw new InvalidProgramException(); } wpf = imagee; } break; case InlineUIContainer iuc: { var inlineuiContainere = new swd.InlineUIContainer(); wpf = inlineuiContainere; } break; case LineBreak lb: { wpf = new swd.LineBreak(); } break; case List list: { var liste = new swd.List(); if (list.MarkerStyle.HasValue) { liste.MarkerStyle = ToMarkerStyle(list.MarkerStyle.Value); } wpf = liste; } break; case ListItem li: { wpf = new swd.ListItem(); } break; case Paragraph p: { var pe = new swd.Paragraph(); if (p.TextDecorations.HasValue) { pe.TextDecorations = ToTextDecorations(p.TextDecorations.Value); } if (p.TextIndent.HasValue) { pe.TextIndent = p.TextIndent.Value.IsAbsolute ? p.TextIndent.Value.ToPixel() : 0; } wpf = pe; } break; case Run run: { if (SplitIntoWords) { wpf = CreateTextElement_SeparateWords(run.Text); } else if (SplitIntoSentences) { wpf = CreateTextElement_SeparateSentences(run.Text); } else { wpf = new swd.Run(run.Text); } } break; case Section s: { wpf = new swd.Section(); } break; case Span span: { wpf = new swd.Span(); } break; case Table tb: { var tbe = new swd.Table(); foreach (var c in tb.Columns) { if (c.Width.HasValue) { tbe.Columns.Add(new swd.TableColumn() { Width = new System.Windows.GridLength(c.Width.Value) }); } else { tbe.Columns.Add(new swd.TableColumn()); } } wpf = tbe; } break; case TableCell tc: { var tce = new swd.TableCell(); if (1 != tc.ColumnSpan) { tce.ColumnSpan = tc.ColumnSpan; } if (1 != tc.RowSpan) { tce.RowSpan = tc.RowSpan; } if (tc.BorderBrush.HasValue) { tce.BorderBrush = new System.Windows.Media.SolidColorBrush(ToColor(tc.BorderBrush.Value)); } if (tc.BorderThickness.HasValue) { tce.BorderThickness = ToThickness(tc.BorderThickness.Value); } wpf = tce; } break; case TableRow trow: { wpf = new swd.TableRow(); } break; case TableRowGroup trg: { wpf = new swd.TableRowGroup(); } break; default: { wpf = null; } break; } // Render TextElement properties if (wpf is swd.TextElement te) { if (!string.IsNullOrEmpty(e.FontFamily)) { te.FontFamily = GetFontFamily(e.FontFamily); } if (e.FontSize.HasValue) { var fs = e.FontSize.Value; fs = Math.Max(0.004, fs); te.FontSize = fs; } if (e.FontStyle.HasValue) { te.FontStyle = ToFontStyle(e.FontStyle.Value); } if (e.FontWeight.HasValue) { te.FontWeight = ToFontWeight(e.FontWeight.Value); } if (e.Foreground.HasValue && e.Foreground != e.ForegroundInheritedOnly) { te.Foreground = GetBrushFromColor(e.Foreground.Value); } if (e.Background.HasValue && e.Background != e.BackgroundInheritedOnly) { te.Background = GetBrushFromColor(e.Background.Value); } } // now special properties if (e is Block b && wpf is swd.Block be) { if (b.Margin.HasValue) { be.Margin = ToThickness(b.Margin.Value); } if (b.Padding.HasValue) { be.Padding = ToThickness(b.Padding.Value); } if (b.BorderBrush.HasValue) { be.BorderBrush = new System.Windows.Media.SolidColorBrush(ToColor(b.BorderBrush.Value)); } if (b.BorderThickness.HasValue) { be.BorderThickness = ToThickness(b.BorderThickness.Value); } if (b.TextAlignment.HasValue) { be.TextAlignment = ToTextAlignment(b.TextAlignment.Value); } if (b.LineHeight.HasValue) { be.LineHeight = b.LineHeight.Value; } } if (e is Inline i && wpf is swd.Inline ie) { if (i.VerticalAlignment.HasValue) { ie.BaselineAlignment = ToBaselineAlignment(i.VerticalAlignment.Value); } } // finished rendering the attributes // now, render all children foreach (var child in e.Childs) { var childe = RenderRecursively(child); switch (wpf) { case swd.Figure figure: figure.Blocks.Add((swd.Block)childe); break; case swd.Floater floater: floater.Blocks.Add((swd.Block)childe); break; case swd.FlowDocument flowDocument: flowDocument.Blocks.Add((swd.Block)childe); break; case swd.List list: list.ListItems.Add((swd.ListItem)childe); break; case swd.ListItem listItem: listItem.Blocks.Add((swd.Block)childe); break; case swd.Section section: section.Blocks.Add((swd.Block)childe); break; case swd.Table table: table.RowGroups.Add((swd.TableRowGroup)childe); break; case swd.TableCell tableCell: tableCell.Blocks.Add((swd.Block)childe); break; case swd.TableRow tableRow: tableRow.Cells.Add((swd.TableCell)childe); break; case swd.TableRowGroup tableRowGroup: tableRowGroup.Rows.Add((swd.TableRow)childe); break; // now elements that can contain inlines case swd.Paragraph paragraph: paragraph.Inlines.Add((swd.Inline)childe); break; case swd.Span span: span.Inlines.Add((swd.Inline)childe); break; // now some specialties case swd.InlineUIContainer inlineUIContainer: if (inlineUIContainer.Child != null) { throw new InvalidOperationException($"{nameof(swd.InlineUIContainer)} can not contain more than one child"); } inlineUIContainer.Child = (System.Windows.UIElement)childe; break; case swd.BlockUIContainer blockUIContainer: if (blockUIContainer.Child != null) { throw new InvalidOperationException($"{nameof(swd.BlockUIContainer)} can not contain more than one child"); } blockUIContainer.Child = (System.Windows.UIElement)childe; break; default: throw new NotImplementedException(); } } if (AttachDomAsTags) { if (wpf is System.Windows.FrameworkContentElement conEle) { conEle.Tag = e; } else if (wpf is System.Windows.FrameworkElement uiEle) { uiEle.Tag = e; } } return(wpf); }
private void InsertImage(ImageEx image) { base.Selection.Text = ""; TextPointer insertionPosition = base.CaretPosition.GetInsertionPosition(LogicalDirection.Forward); InlineUIContainer container = new InlineUIContainer(image, insertionPosition); insertionPosition = insertionPosition.GetNextContextPosition(LogicalDirection.Forward); base.CaretPosition = container.ElementEnd; }
// Inserts an InkInteropObject at a specified position. private TextPointer InsertInkAtPosition(TextPointer insertionPosition, InkInteropObject inkobject, out UnsafeNativeMethods.TS_TEXTCHANGE change) { int symbolsAddedBefore = 0; int symbolsAddedAfter = 0; // Prepare an insertion position for InlineUIContainer. // As an optimization, shift outside of any formatting tags to avoid // splitting tags below. while (insertionPosition.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.ElementStart && TextSchema.IsFormattingType(insertionPosition.Parent.GetType())) { insertionPosition = insertionPosition.GetNextContextPosition(LogicalDirection.Backward); } while (insertionPosition.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementEnd && TextSchema.IsFormattingType(insertionPosition.Parent.GetType())) { insertionPosition = insertionPosition.GetNextContextPosition(LogicalDirection.Forward); } // If we need to, split the current parent TextElement and prepare // a suitable home for an InlineUIContainer. if (!TextSchema.IsValidParent(insertionPosition.Parent.GetType(), typeof(InlineUIContainer))) { insertionPosition = TextRangeEditTables.EnsureInsertionPosition(insertionPosition, out symbolsAddedBefore, out symbolsAddedAfter); Invariant.Assert(insertionPosition.Parent is Run, "position must be in Run scope"); insertionPosition = TextRangeEdit.SplitElement(insertionPosition); // We need to remember how many symbols were added into addition // to the InlineUIContainer itself. // Account for the two element edges just added. symbolsAddedBefore += 1; symbolsAddedAfter += 1; } // Create an InlineUIContainer. InlineUIContainer inlineUIContainer = new InlineUIContainer(inkobject); change.start = ((ITextPointer)insertionPosition).Offset - symbolsAddedBefore; change.oldEnd = change.start; // Insert it into the insertionPosition. This adds 3 symbols. insertionPosition.InsertTextElement(inlineUIContainer); change.newEnd = change.start + symbolsAddedBefore + inlineUIContainer.SymbolCount + symbolsAddedAfter; // Return a position after the inserted object. return inlineUIContainer.ElementEnd.GetInsertionPosition(LogicalDirection.Forward); }
private static void CacheImage(string url, InlineUIContainer item) { lock (_cacheLock) { if (UrlImageCache.ContainsKey(url)) { UrlImageCache[url] = item; } else { UrlImageCache.Add(url, item); } } }
//------------------------------------------------------ // // Internal Virtual Methods - TextSelection Extensibility // //------------------------------------------------------ #region Internal Virtual Methods //...................................................... // // Formatting // //...................................................... // Worker for AppendEmbeddedElement; enabled extensibility for TextSelection internal virtual void InsertEmbeddedUIElementVirtual(FrameworkElement embeddedElement) { Invariant.Assert(this.HasConcreteTextContainer, "Can't insert embedded object to non-TextContainer range!"); Invariant.Assert(embeddedElement != null); TextRangeBase.BeginChange(this); try { // Delete existing selected content this.Text = String.Empty; // Calling EnsureInsertionPosition has the effect of inserting a paragraph // before insert the embedded UIElement at BlockUIContainer or InlineUIConatiner. TextPointer startPosition = TextRangeEditTables.EnsureInsertionPosition(this.Start); // Choose what wrapper to use - BlockUIContainer or InlineUIContainer - // depending on the current paragraph emptiness Paragraph paragraph = startPosition.Paragraph; if (paragraph != null) { if (Paragraph.HasNoTextContent(paragraph)) { // Use BlockUIContainer as a replacement of the current paragraph BlockUIContainer blockUIContainer = new BlockUIContainer(embeddedElement); // Translate embedded element's horizontal alignment property to the BlockUIContainer's text alignment blockUIContainer.TextAlignment = TextRangeEdit.GetTextAlignmentFromHorizontalAlignment(embeddedElement.HorizontalAlignment); // Replace paragraph with BlockUIContainer paragraph.SiblingBlocks.InsertAfter(paragraph, blockUIContainer); paragraph.SiblingBlocks.Remove(paragraph); this.Select(blockUIContainer.ContentStart, blockUIContainer.ContentEnd); } else { // Use InlineUIContainer InlineUIContainer inlineUIContainer = new InlineUIContainer(embeddedElement); TextPointer insertionPosition = TextRangeEdit.SplitFormattingElements(this.Start, /*keepEmptyFormatting:*/false); insertionPosition.InsertTextElement(inlineUIContainer); this.Select(inlineUIContainer.ElementStart, inlineUIContainer.ElementEnd); } } } finally { TextRangeBase.EndChange(this); } }
/// <summary> /// Creates the visual tree for cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock outerBlock = new TextBlock(); Hyperlink link = new Hyperlink(); InlineUIContainer inlineContainer = new InlineUIContainer(); ContentPresenter innerContentPresenter = new ContentPresenter(); outerBlock.Inlines.Add(link); link.Inlines.Add(inlineContainer); inlineContainer.Child = innerContentPresenter; link.TargetName = TargetName; ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, outerBlock); ApplyBinding(link, Hyperlink.NavigateUriProperty); ApplyContentBinding(innerContentPresenter, ContentPresenter.ContentProperty); return outerBlock; }
private static void ExpandShrunkLink(Hyperlink link, Paragraph parent, RichTextBox rtb) { if (link.NavigateUri.AbsoluteUri.StartsWith("http://bit.ly")) { WebClient getBitly = new WebClient(); getBitly.DownloadStringCompleted += (sender, e) => { if (e.Error == null) { XElement result = XElement.Parse(e.Result); XElement long_url = GetPath(result, "data/entry/long_url"); if (long_url != null) { string url = long_url.Value; // ToolTipService.SetToolTip(link, url); InlineUIContainer container = new InlineUIContainer(); Ellipse ellipse = new Ellipse(); ellipse.Width = 6; ellipse.Height = 6; ellipse.VerticalAlignment = VerticalAlignment.Center; ellipse.Margin = new Thickness(3); ellipse.Fill = new SolidColorBrush(Colors.Orange); ToolTipService.SetToolTip(ellipse, url); container.Child = ellipse; parent.Inlines.Insert(parent.Inlines.IndexOf(link) + 1, container); //link.Inlines.Add(container); } } }; getBitly.DownloadStringAsync(new Uri("http://api.bit.ly/v3/expand?shortUrl=" + HttpUtility.UrlEncode(link.NavigateUri.AbsoluteUri) + "&login=jimlynn&apiKey=R_769e4a2d579cef3c9c18be33dc4b160c&format=xml", UriKind.Absolute)); } else if (link.NavigateUri.AbsoluteUri.StartsWith("http://twitpic.com/")) { string url = link.NavigateUri.AbsoluteUri + "/full"; WebClient getTwitpic = new WebClient(); getTwitpic.DownloadStringCompleted += (sender, e) => { if (e.Error == null) { //Regex getpic = new Regex("(<img(\\ [^=]+=\\\"[^\"]+\\\")*\\ *>)+"); Regex getpic = new Regex(@"(?<=img\s+.*src\=[\x27\x22])(?<Url>[^\x27\x22]*)(?=[\x27\x22])"); Match match = getpic.Match(e.Result); while (match.Success) { //if (match.Value.Contains("/images/logo-main.png") == false) if (match.Value.StartsWith("http://")) { var imgurl = match.Value; ICommand command = rtb.GetValue(StatusView.CommandProperty) as ICommand; if (command != null) { link.NavigateUri = null; link.Command = command; link.CommandParameter = imgurl; } break; } match = match.NextMatch(); } } }; getTwitpic.DownloadStringAsync(new Uri(url, UriKind.Absolute)); } else if (link.NavigateUri.AbsoluteUri.StartsWith("http://yfrog.com/")) { string id = link.NavigateUri.AbsoluteUri.Substring("http://yfrog.com/".Length); WebClient getYfrog = new WebClient(); getYfrog.DownloadStringCompleted+= (sender,e)=> { if (e.Error == null) { XElement xml = XElement.Parse(e.Result); XNamespace ns = "http://ns.imageshack.us/imginfo/7/"; var links = xml.Element(ns + "links"); ; if (links != null) { string url = links.Element(ns + "image_link").Value; ICommand command = rtb.GetValue(StatusView.CommandProperty) as ICommand; if (command != null) { link.NavigateUri = null; link.Command = command; link.CommandParameter = url; //link.Command = new RelayCommand<string>(Dis } //Regex getimg = new Regex("<link rel=\"image_src\" href=\"([^\"]+)\" />"); //Match match = getimg.Match(e.Result); //string url = match.Groups[1].Value; InlineUIContainer container = new InlineUIContainer(); Ellipse ellipse = new Ellipse(); ellipse.Width = 16; ellipse.Height = 16; ellipse.Fill = new SolidColorBrush(Colors.Orange); Image img = new Image(); BitmapImage bmp = new BitmapImage(new Uri(url, UriKind.Absolute)); img.Source = bmp; ToolTipService.SetToolTip(ellipse, img); container.Child = ellipse; parent.Inlines.Insert(parent.Inlines.IndexOf(link) + 1, container); } } }; getYfrog.DownloadStringAsync(new Uri("http://yfrog.com/api/xmlInfo?path=" + id, UriKind.Absolute)); } else if (link.NavigateUri.AbsoluteUri.StartsWith("http://tweetphoto.com/")) { string id = link.NavigateUri.AbsoluteUri.Substring("http://tweetphoto.com/".Length); WebClient getYfrog = new WebClient(); getYfrog.DownloadStringCompleted += (sender, e) => { if (e.Error == null) { XElement xml = XElement.Parse(e.Result); XNamespace ns = "http://tweetphotoapi.com"; string url = xml.Element(ns + "BigImageUrl").Value; ICommand command = rtb.GetValue(StatusView.CommandProperty) as ICommand; if (command != null) { link.NavigateUri = null; link.Command = command; link.CommandParameter = url; //link.Command = new RelayCommand<string>(Dis } //Regex getimg = new Regex("<link rel=\"image_src\" href=\"([^\"]+)\" />"); //Match match = getimg.Match(e.Result); //string url = match.Groups[1].Value; InlineUIContainer container = new InlineUIContainer(); Ellipse ellipse = new Ellipse(); ellipse.Width = 16; ellipse.Height = 16; ellipse.Fill = new SolidColorBrush(Colors.Orange); Image img = new Image(); BitmapImage bmp = new BitmapImage(new Uri(url, UriKind.Absolute)); img.Source = bmp; ToolTipService.SetToolTip(ellipse, img); container.Child = ellipse; parent.Inlines.Insert(parent.Inlines.IndexOf(link) + 1, container); } }; getYfrog.DownloadStringAsync(new Uri("http://tweetphotoapi.com/api/tpapi.svc/photos/" + id, UriKind.Absolute)); } else if (link.NavigateUri.AbsoluteUri.StartsWith("http://twitgoo.com/")) { string id = link.NavigateUri.AbsoluteUri.Substring("http://twitgoo.com/".Length); WebClient getYfrog = new WebClient(); getYfrog.DownloadStringCompleted += (sender, e) => { if (e.Error == null) { XElement xml = XElement.Parse(e.Result); string url = xml.Element("imageurl").Value; ICommand command = rtb.GetValue(StatusView.CommandProperty) as ICommand; if (command != null) { link.NavigateUri = null; link.Command = command; link.CommandParameter = url; //link.Command = new RelayCommand<string>(Dis } //Regex getimg = new Regex("<link rel=\"image_src\" href=\"([^\"]+)\" />"); //Match match = getimg.Match(e.Result); //string url = match.Groups[1].Value; InlineUIContainer container = new InlineUIContainer(); Ellipse ellipse = new Ellipse(); ellipse.Width = 16; ellipse.Height = 16; ellipse.Fill = new SolidColorBrush(Colors.Orange); Image img = new Image(); BitmapImage bmp = new BitmapImage(new Uri(url, UriKind.Absolute)); img.Source = bmp; ToolTipService.SetToolTip(ellipse, img); container.Child = ellipse; parent.Inlines.Insert(parent.Inlines.IndexOf(link) + 1, container); } }; getYfrog.DownloadStringAsync(new Uri("http://twitgoo.com/api/message/info/" + id, UriKind.Absolute)); } else if (link.NavigateUri.AbsoluteUri.Contains("imgur.com") && link.NavigateUri.AbsoluteUri.EndsWith(".jpg")) { string url = link.NavigateUri.AbsoluteUri; ICommand command = rtb.GetValue(StatusView.CommandProperty) as ICommand; if (command != null) { link.NavigateUri = null; link.Command = command; link.CommandParameter = url; //link.Command = new RelayCommand<string>(Dis } } }
private void AppendIframe(HtmlNode node, Paragraph paragraph) { #region Youtube Iframe if (node.Attributes["src"] != null && node.Attributes["src"].Value.Contains("youtube")) { //scrape youtube Id #region ID Scraping string link = node.Attributes["src"].Value; string youtubeID = link.Remove(0, link.IndexOf("embed/") + 6); if (youtubeID.IndexOf("?") > 0) youtubeID = youtubeID.Remove(youtubeID.IndexOf("?"), youtubeID.Length - youtubeID.IndexOf("?")); #endregion InlineUIContainer inlineContainer = new InlineUIContainer(); Image image = new Image(); if (node.Attributes["src"] != null) { BitmapImage bitmap = new BitmapImage(new Uri("http://img.youtube.com/vi/"+ youtubeID + "/0.jpg")); bitmap.CreateOptions = BitmapCreateOptions.None; bitmap.ImageOpened += delegate { double bitmapWidth = bitmap.PixelWidth; double actualWidth = currentRtb.ActualWidth; image.Source = bitmap; if (bitmapWidth < actualWidth) { image.Width = bitmapWidth; } else { image.Width = 436; } }; } Image playbtn = new Image() { Source = new BitmapImage(new Uri("/WindowsFanDkApp;component/Content/play_overlay_icon.png", UriKind.Relative))}; playbtn.Height = 200; Canvas.SetLeft(playbtn, 50); Canvas.SetTop(playbtn, 70); Canvas canvas = new Canvas(); canvas.Children.Add(image); canvas.Children.Add(playbtn); canvas.Height = 360; inlineContainer.Child = canvas; image.Stretch = Stretch.Uniform; canvas.Tap += (sender, args) => { PostPageView page = ControlFinder.FindParent<PostPageView>(this); if (page != null) { page.Browse("http://m.youtube.com/watch?v=" + youtubeID + "&feature=player_embedded"); //page.Browse(node.Attributes["src"].Value); } }; paragraph.Inlines.Add(inlineContainer); AppendChildren(node, paragraph, null); } #endregion else { Debug.WriteLine(String.Format("Element {0} not implemented", node.Name)); } }
private static void GetImage(Hyperlink link, Paragraph parent, string html, string id) { Regex getpic = new Regex("<img(\\ [^=]+=\\\"[^\"]+\\\")*(\\ id=\\\"" + id + "\\\")+(\\ [^=]+=\\\"[^\"]+\\\")*\\ *>"); Match match = getpic.Match(html); if (match.Success) { var srcmatch = (from g in match.Groups.Cast<Group>() where g.Value.StartsWith(" src") select g).FirstOrDefault(); if (srcmatch == null) { return; } var url = srcmatch.Value.Substring(" src=\"".Length).TrimEnd('"'); //link.NavigateUri = new Uri(url, UriKind.Absolute); InlineUIContainer container = new InlineUIContainer(); Ellipse ellipse = new Ellipse(); ellipse.Width = 16; ellipse.Height = 16; ellipse.Fill = new SolidColorBrush(Colors.Orange); Image img = new Image(); BitmapImage bmp = new BitmapImage(new Uri(url, UriKind.Absolute)); img.Source = bmp; ToolTipService.SetToolTip(ellipse, img); container.Child = ellipse; parent.Inlines.Insert(parent.Inlines.IndexOf(link) + 1, container); } }
private void ParseAndSetSpecifiedText(string text) { // Clear the collection of Inlines SelectAll(); this.Selection.Text = ""; // Wrap the input in a <div> (so even plain text becomes valid XML) using (var stringReader = new StringReader(string.Concat("<div>", text, "</div>"))) { DocTree RootElement = new DocTree(new Span(), 0, 0) { FontSize = 10 }; DocTree currentElement = RootElement; // Read the input using (var xmlReader = XmlReader.Create(stringReader)) { // State variables var bold = 0; var italic = 0; var underline = 0; var td = 0; var tr = 0; Stack<double> fontSize = new Stack<double>(); fontSize.Push(10); System.Collections.Generic.Stack<TextElement> elementTree = new System.Collections.Generic.Stack<TextElement>(); string link = null; var lastElement = elementP; // Read the entire XML DOM... while (xmlReader.Read()) { var nameUpper = xmlReader.Name.ToUpper(); switch (xmlReader.NodeType) { case XmlNodeType.Element: // Handle the begin element switch (nameUpper) { case "H1": fontSize.Push(24); break; case "H2": fontSize.Push(18); break; case "H3": fontSize.Push(14); break; case "H4": fontSize.Push(12); break; case elementA: link = ""; // Look for the HREF attribute (can't use .MoveToAttribute because it's case-sensitive) if (xmlReader.MoveToFirstAttribute()) { do { if ("HREF" == xmlReader.Name.ToUpper()) { // Store the link target link = xmlReader.Value; break; } } while (xmlReader.MoveToNextAttribute()); } break; case elementB: case elementSTRONG: bold++; break; case elementI: case elementEM: italic++; break; case elementU: underline++; break; case elementBR: currentElement.Children.Add(new DocTree(new LineBreak(), tr, td)); break; //Selection.Insert(new LineBreak() ); break; case elementTR: tr++; td = 0; break; case elementTD: td++; break; case "TH": td++; bold++; break; case elementTABLE: DocTree p = new DocTree(new Table(), tr, td); currentElement.Children.Add(p); tr = 0; td = 0; currentElement = p; break; case elementP: DocTree p2 = new DocTree(new InlineParaGraph(), tr, td); currentElement.Children.Add(p2); currentElement = p2; break; case elementImage: var img = new InlineUIContainer() { Child = new Image() { Source = new System.Windows.Media.Imaging.BitmapImage( new System.Uri(xmlReader.GetAttribute("src"), System.UriKind.Absolute) ), Stretch = Stretch.None //This should be improved to read image size if set } }; currentElement.Children.Add(new DocTree(img, tr, td)); break; } lastElement = nameUpper; break; case XmlNodeType.EndElement: // Handle the end element switch (nameUpper) { case elementA: link = null; break; case elementB: case elementSTRONG: bold--; break; case elementI: case elementEM: italic--; break; case elementU: underline--; break; case "H1": case "H2": case "H3": case "H4": fontSize.Pop(); break; case elementTR: td = 0; break; case elementTD: break; case "TH": bold--; break; case elementTABLE: tr = 0; td = 0; currentElement = currentElement.Parent ?? RootElement; break; case elementP: currentElement = currentElement.Parent ?? RootElement; //Selection.Insert(elementTree.Pop()); //Selection.Insert(new LineBreak()); //Selection.Insert(new LineBreak()); break; } lastElement = nameUpper; break; case XmlNodeType.Text: case XmlNodeType.Whitespace: // Create a Run for the visible text // Collapse contiguous whitespace per HTML behavior StringBuilder builder = new StringBuilder(xmlReader.Value.Length); var last = '\0'; foreach (char c in xmlReader.Value.Replace('\n', ' ')) { if ((' ' != last) || (' ' != c)) { builder.Append(c); } last = c; } // Trim leading whitespace if following a <P> or <BR> element per HTML behavior var builderString = builder.ToString(); if ((elementP == lastElement) || (elementBR == lastElement)) { builderString = builderString.TrimStart(); } // If any text remains to display... if (0 < builderString.Length) { // Create a Run to display it Run run = new Run { Text = builderString, FontSize = currentElement.FontSize }; // Style the Run appropriately if (0 < bold) run.FontWeight = FontWeights.Bold; if (0 < italic) run.FontStyle = FontStyles.Italic; if (0 < underline) run.TextDecorations = System.Windows.TextDecorations.Underline; if (fontSize.Count > 0) run.FontSize = fontSize.Peek(); if (null != link) { // Links get styled and display their HREF since Run doesn't support MouseLeftButton* events run.TextDecorations = System.Windows.TextDecorations.Underline; run.Foreground = HyperlinkColor ?? new SolidColorBrush { Color = Color.FromArgb(255, 177, 211, 250) }; Hyperlink hlink = new Hyperlink() { NavigateUri = new System.Uri(link, System.UriKind.RelativeOrAbsolute), TargetName = "_blank" }; hlink.Inlines.Add(run); currentElement.Children.Add(new DocTree(hlink, tr, td)); } else // Add the Run to the collection currentElement.Children.Add(new DocTree(run, tr, td)); lastElement = null; } break; } } } Span s = new Span(); DocTreeToTextElement(RootElement, s.Inlines); Selection.Insert(s); } }
static void HtmlDocSourceChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e) { var current = sender as RichTextBoxFromHtml; if (current == null) return; // throw exception HtmlDocument doc = e.NewValue as HtmlDocument; if (doc == null) return; Brush linkForeGround = Application.Current.Resources["DefaultGreenBrush"] as Brush; Brush linkMouseOverForeGround = Application.Current.Resources["DefaultBlueBrush"] as Brush; var p = new List<Inline>(); foreach (var item in doc.DocumentNode.ChildNodes) { var r = new Run(); switch (item.NodeType) { case HtmlNodeType.Comment: throw new NotImplementedException(); case HtmlNodeType.Document: throw new NotImplementedException(); case HtmlNodeType.Element: if (item.Name == "br") { if (p.Count == 0 || p.Last().GetType() != typeof(LineBreak)) p.Add(new LineBreak()); continue; } else if (item.Name == "blockquote") { // TODO: iterate into the element for one more level r.Foreground = current.SubtleForeground; r.Text = item.InnerText; } else if (item.Name == "img") { if (Microsoft.Phone.Info.DeviceStatus.DeviceTotalMemory / 1048576 < 256) { r.Foreground = current.Foreground; r.Text = item.GetAttributeValue("src", "<有图片>"); } else { Image MyImage = new Image(); var _imgsrc = new BitmapImage(); _imgsrc.CreateOptions = BitmapCreateOptions.BackgroundCreation | BitmapCreateOptions.DelayCreation; _imgsrc.UriSource = new Uri(item.Attributes["src"].Value, UriKind.Absolute); _imgsrc.ImageFailed += (ss, ee) => { WebClient wc = new WebClient(); wc.Headers["Referer"] = "http://www.guokr.com"; wc.OpenReadCompleted += (s, eee) => { try { _imgsrc.SetSource(eee.Result); } catch { } }; wc.OpenReadAsync(_imgsrc.UriSource); }; MyImage.Source = _imgsrc; InlineUIContainer MyUI = new InlineUIContainer(); MyImage.HorizontalAlignment = HorizontalAlignment.Left; MyImage.MaxWidth = 300; MyUI.Child = MyImage; p.Add(MyUI); continue; } } else if (item.Name == "a") { var h = new Hyperlink(); h.Foreground = linkForeGround; h.TextDecorations = null; h.MouseOverForeground = linkMouseOverForeGround; h.MouseOverTextDecorations = null; h.Inlines.Add(HtmlEntity.DeEntitize(item.InnerText)); if (item.Attributes.Contains("href")) { string url = item.Attributes["href"].Value; h.Click += (ss, ee) => { var t = new WebBrowserTask(); t.Uri = new Uri(url, UriKind.Absolute); t.Show(); }; } p.Add(h); continue; } else if (item.Name == "b") { r.FontWeight = FontWeights.Bold; r.Foreground = current.Foreground; r.Text = HtmlEntity.DeEntitize(item.InnerText); } else if (item.Name == "i") { r.FontStyle = FontStyles.Italic; r.Foreground = current.Foreground; r.Text = HtmlEntity.DeEntitize(item.InnerText); } else { //throw new NotImplementedException(); r.Foreground = current.Foreground; r.Text = item.InnerText; } break; case HtmlNodeType.Text: r.Foreground = current.Foreground; r.Text = HtmlEntity.DeEntitize(item.InnerText); while (r.Text.Length > 2000) { var rr = r; rr.Foreground = r.Foreground; rr.Text = r.Text.Substring(0, 2000); p.Add(rr); r.Text = r.Text.Substring(2000); } break; default: throw new NotImplementedException(); } p.Add(r); } var rtb = current.InternalRTB; rtb.Blocks.Clear(); rtb.Blocks.Add(new Paragraph()); var sp = current.LayoutRoot; sp.Children.Clear(); sp.Children.Add(rtb); foreach (var item in p) { if ((rtb.Blocks.Last() as Paragraph).Inlines.Count > 15) { rtb = new RichTextBox(); rtb.Blocks.Add(new Paragraph()); sp.Children.Add(rtb); } (rtb.Blocks.Last() as Paragraph).Inlines.Add(item); } }
private void SetMessage(ChatMessage msg) { m_user = msg.User; m_ban = new TimeOutIcon(GetImage(s_ban), GetImage(s_check)); m_ban.BaselineAlignment = BaselineAlignment.Center; m_ban.Clicked += m_ban_Clicked; m_ban.Restore += Unban; m_eight = new TimeOutIcon(GetImage(s_eight), GetImage(s_check)); m_eight.BaselineAlignment = BaselineAlignment.Center; m_eight.Clicked += m_eight_Clicked; m_eight.Restore += Unban; m_timeout = new TimeOutIcon(GetImage(s_timeout), GetImage(s_check)); m_timeout.Clicked += m_timeout_Clicked; m_timeout.BaselineAlignment = BaselineAlignment.Center; m_timeout.Restore += Unban; if (Controller.ShowTimestamps) Inlines.Add(new Run(DateTime.Now.ToString("hh:mm ")) { Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#707070")), BaselineAlignment = BaselineAlignment.Center }); if (Controller.ShowIcons && Controller.CurrentUser.IsModerator) { Inlines.Add(m_ban); Inlines.Add(m_eight); Inlines.Add(m_timeout); } if (m_user.IsModerator) { m_mod = new InlineUIContainer(GetImage(s_mod)); m_mod.BaselineAlignment = BaselineAlignment.Center; Inlines.Add(m_mod); } var user = msg.User; if (user.IsSubscriber) { var sub = new InlineUIContainer(GetImage(s_sub)); sub.BaselineAlignment = BaselineAlignment.Center; Inlines.Add(sub); } Brush userColor = Brushes.Black; if (user.Color != null) { try { userColor = (SolidColorBrush)(new BrushConverter().ConvertFrom(msg.User.Color)); } catch (NotSupportedException) { } } m_name = new Run(user.Name) { FontWeight = FontWeights.Bold, Foreground = userColor, BaselineAlignment = BaselineAlignment.Center }; Inlines.Add(m_name); if (msg.Type != ItemType.Action) Inlines.Add(new Run(": ") { BaselineAlignment = BaselineAlignment.Center }); BuildText(msg); }
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); } } } }