private void ShowDialogInternal(Inline targetInline, Action<Inline, Inline> replaceCallback, RadRichTextBox owner) { if (targetInline is ImageInline) { this.originalImageInline = (ImageInline)targetInline; } else if (targetInline is FloatingImageBlock) { this.originalImageInline = ((FloatingImageBlock)targetInline).ImageInline; } else { throw new InvalidOperationException("Unable to find image element."); } this.SetOwner(owner); this.replaceCurrentInlineCallback = replaceCallback; this.originalInline = targetInline; this.ShowDialog(); this.Dispatcher.BeginInvoke(new Action(() => { this.FillUI(this.originalInline); })); }
public void ShowDialogInternal(Inline orgInline, Action<Inline, Inline> replaceCurrentImageCallback, string executeToolName, RadRichTextBox owner) { this.SetOwner(owner); this.originalInline = orgInline; if (orgInline is ImageInline) { this.originalImageInline = (ImageInline)orgInline; } else if (orgInline is FloatingImageBlock) { this.originalImageInline = ((FloatingImageBlock)orgInline).ImageInline; } else { throw new InvalidOperationException("Unable to find image element."); } RadBitmap image = new RadBitmap(this.originalImageInline.ImageSource); this.isRotated = false; this.originalAspect = new Size(this.originalImageInline.Width / image.Width, this.originalImageInline.Height / image.Height); this.originalRotateAngle = this.originalImageInline.RotateAngle; this.replaceCurrentImageCallback = replaceCurrentImageCallback; this.ImageEditorUI.Image = image; this.ShowDialog(); this.StartExecuteTool(executeToolName); }
private void FillUI(Inline targetInline) { if (targetInline == null) { return; } this.positionProperties.FillUI(targetInline); this.textWrappingProperties.FillUI(targetInline); }
protected override void WriteInline(Inline inline, bool isOpening, bool isClosing, out bool ignoreChildNodes) { if (inline.Tag == InlineTag.Link && !this.RenderPlainTextInlines.Peek()) { ignoreChildNodes = false; if (isOpening) { Write(inline.LiteralContent); } } else { base.WriteInline(inline, isOpening, isClosing, out ignoreChildNodes); } }
internal void FillUI(Inline targetInline) { FloatingBlock flaotingBlock = targetInline as FloatingBlock; if (flaotingBlock != null) { this.FillUIFromFloatingBlock(flaotingBlock); } else { ImageInline image = targetInline as ImageInline; Debug.Assert(image != null, "Unexpected inline type"); if (image != null) { this.FillUIFromImage(image); } } }
protected override void WriteInline(Inline inline, bool isOpening, bool isClosing, out bool ignoreChildNodes) { if (inline.Tag == InlineTag.Link && !this.RenderPlainTextInlines.Peek()) { ignoreChildNodes = false; // start and end of each node may be visited separately if (isOpening) { this.Write("<u>"); this.Write(inline.LiteralContent); } if (isClosing) { this.Write("</u>"); } } else { base.WriteInline(inline, isOpening, isClosing, out ignoreChildNodes); } }
/// <summary> /// Writes the inline list to the given writer as HTML code. /// </summary> private static void InlinesToHtml(HtmlTextWriter writer, Inline inline, CommonMarkSettings settings, Stack <InlineStackEntry> stack) { var uriResolver = settings.UriResolver; bool withinLink = false; bool stackWithinLink = false; bool visitChildren; bool trackPositions = settings.TrackSourcePosition; string stackLiteral = null; while (inline != null) { visitChildren = false; switch (inline.Tag) { case InlineTag.String: if (trackPositions) { writer.WriteConstant("<span"); PrintPosition(writer, inline); writer.Write('>'); EscapeHtml(inline.LiteralContentValue, writer); writer.WriteConstant("</span>"); } else { EscapeHtml(inline.LiteralContentValue, writer); } break; case InlineTag.LineBreak: writer.WriteLineConstant("<br />"); break; case InlineTag.SoftBreak: if (settings.RenderSoftLineBreaksAsLineBreaks) { writer.WriteLineConstant("<br />"); } else { writer.WriteLine(); } break; case InlineTag.Code: writer.WriteConstant("<code"); if (trackPositions) { PrintPosition(writer, inline); } writer.Write('>'); EscapeHtml(inline.LiteralContentValue, writer); writer.WriteConstant("</code>"); break; case InlineTag.RawHtml: // cannot output source position for HTML blocks writer.Write(inline.LiteralContentValue); break; case InlineTag.Link: if (withinLink) { writer.Write('['); stackLiteral = "]"; stackWithinLink = true; visitChildren = true; } else { writer.WriteConstant("<a href=\""); if (uriResolver != null) { EscapeUrl(uriResolver(inline.TargetUrl), writer); } else { EscapeUrl(inline.TargetUrl, writer); } writer.Write('\"'); if (inline.LiteralContentValue.Length > 0) { writer.WriteConstant(" title=\""); EscapeHtml(inline.LiteralContentValue, writer); writer.Write('\"'); } if (trackPositions) { PrintPosition(writer, inline); } writer.Write('>'); visitChildren = true; stackWithinLink = true; stackLiteral = "</a>"; } break; case InlineTag.Image: writer.WriteConstant("<img src=\""); if (uriResolver != null) { EscapeUrl(uriResolver(inline.TargetUrl), writer); } else { EscapeUrl(inline.TargetUrl, writer); } writer.WriteConstant("\" alt=\""); InlinesToPlainText(writer, inline.FirstChild, stack); writer.Write('\"'); if (inline.LiteralContentValue.Length > 0) { writer.WriteConstant(" title=\""); EscapeHtml(inline.LiteralContentValue, writer); writer.Write('\"'); } if (trackPositions) { PrintPosition(writer, inline); } writer.WriteConstant(" />"); break; case InlineTag.Strong: writer.WriteConstant("<strong"); if (trackPositions) { PrintPosition(writer, inline); } writer.Write('>'); stackLiteral = "</strong>"; stackWithinLink = withinLink; visitChildren = true; break; case InlineTag.Emphasis: writer.WriteConstant("<em"); if (trackPositions) { PrintPosition(writer, inline); } writer.Write('>'); stackLiteral = "</em>"; visitChildren = true; stackWithinLink = withinLink; break; case InlineTag.Strikethrough: writer.WriteConstant("<del"); if (trackPositions) { PrintPosition(writer, inline); } writer.Write('>'); stackLiteral = "</del>"; visitChildren = true; stackWithinLink = withinLink; break; default: throw new CommonMarkException("Inline type " + inline.Tag + " is not supported.", inline); } if (visitChildren) { stack.Push(new InlineStackEntry(stackLiteral, inline.NextSibling, withinLink)); withinLink = stackWithinLink; inline = inline.FirstChild; } else if (inline.NextSibling != null) { inline = inline.NextSibling; } else { inline = null; } while (inline == null && stack.Count > 0) { var entry = stack.Pop(); writer.WriteConstant(entry.Literal); inline = entry.Target; withinLink = entry.IsWithinLink; } } }
public void Add(Inline inline) { _innerContainer.Add(inline); }
/// <summary> /// Razor template using @Html.Localize("id") /// </summary> /// <param name="helper"></param> /// <param name="lang"></param> /// <returns></returns> public static MvcHtmlString Localize(this HtmlHelper helper, Inline lang) { return(new MvcHtmlString(Localization.Localize(lang))); }
private static TextDecorationCollection GetUnderlineTextDecorations(XmlReader reader, Inline inline) { TextDecoration textDecoration; Brush brush; var color = GetColor(reader[ColorAttribute, WordprocessingMLNamespace]); if (color.HasValue) { brush = new SolidColorBrush(color.Value); } else { brush = inline.Foreground; } var textDecorations = new TextDecorationCollection() { (textDecoration = new TextDecoration() { Location = TextDecorationLocation.Underline, Pen = new Pen() { Brush = brush } }) }; switch (GetValueAttribute(reader)) { case "single": break; case "double": textDecoration.PenOffset = inline.FontSize * 0.05; textDecoration = textDecoration.Clone(); textDecoration.PenOffset = inline.FontSize * -0.05; textDecorations.Add(textDecoration); break; case "dotted": textDecoration.Pen.DashStyle = DashStyles.Dot; break; case "dash": textDecoration.Pen.DashStyle = DashStyles.Dash; break; case "dotDash": textDecoration.Pen.DashStyle = DashStyles.DashDot; break; case "dotDotDash": textDecoration.Pen.DashStyle = DashStyles.DashDotDot; break; case "none": default: // If underline type is none or unsupported then it will be ignored. return(null); } return(textDecorations); }
private void ProcessInlines(Inline inline, ref TagProperties tagProperties, ref Line currentLine) { while (inline != null) { switch (inline.Tag) { case InlineTag.String: if (currentLine.Entities.Count > 0) { Entity?merged = Entity.MergeString(currentLine.Entities.Last(), ref tagProperties, inline.LiteralContent); if (merged.HasValue) { currentLine.Entities.RemoveAt(currentLine.Entities.Count - 1); currentLine.Add(merged.Value); break; } } currentLine.Add(new Entity(EntityType.String, ref tagProperties, inline.LiteralContent)); break; case InlineTag.LineBreak: currentLine = AddLine(); break; case InlineTag.SoftBreak: currentLine = AddLine(); if (tagProperties.ListIndex != 0) { currentLine.Add(new Entity(EntityType.ListIndent, ref tagProperties, null)); } break; case InlineTag.Code: ConsoleEx.WriteLine(inline.LiteralContent); break; case InlineTag.RawHtml: ConsoleEx.WriteLine(inline.LiteralContent); break; case InlineTag.Link: { TagProperties newProps = tagProperties; newProps.Url = inline.TargetUrl; ProcessInlines(inline.FirstChild, ref newProps, ref currentLine); } break; case InlineTag.Image: { currentLine.Add(new Entity(EntityType.Image, ref tagProperties, inline.TargetUrl)); } break; case InlineTag.Strong: { TagProperties newProps = tagProperties; switch (newProps.FontType) { case FontType.i: newProps.FontType = FontType.bi; break; default: newProps.FontType = FontType.b; break; } ProcessInlines(inline.FirstChild, ref newProps, ref currentLine); } break; case InlineTag.Emphasis: { TagProperties newProps = tagProperties; switch (newProps.FontType) { case FontType.b: newProps.FontType = FontType.bi; break; default: newProps.FontType = FontType.i; break; } ProcessInlines(inline.FirstChild, ref newProps, ref currentLine); } break; case InlineTag.Strikethrough: break; default: throw new CommonMarkException("Inline type " + inline.Tag + " is not supported.", inline); } inline = inline.NextSibling; } }
private void AddChatText(Inline headerRun, string chat, Brush fB = null, Brush bB = null) { if (fB == null) { fB = _bOtherColor; } if (bB == null) { bB = _bBackColor; } bool rtbatbottom = false; // bool firstAutoScroll = true; // never used //check to see if the richtextbox is scrolled to the bottom. //---------------------------------------------------------------------------------- double dVer = richTextBox1.VerticalOffset; //get the vertical size of the scrollable content area double dViewport = richTextBox1.ViewportHeight; //get the vertical size of the visible content area double dExtent = richTextBox1.ExtentHeight; if (Math.Abs(dVer - 0) < double.Epsilon && dViewport < dExtent) { rtbatbottom = true; } if (Math.Abs(dVer - 0) > double.Epsilon) { if (Math.Abs(dVer + dViewport - dExtent) < double.Epsilon) { rtbatbottom = true; _justScrolledToBottom = false; } else { if (!_justScrolledToBottom) { var pa = new Paragraph(); var ru = new Run("------------------------------") { Foreground = Brushes.Red }; pa.Inlines.Add(new Bold(ru)); richTextBox1.Document.Blocks.Add(pa); _justScrolledToBottom = true; } } } //---------------------------------------------------------------------------- var p = new Paragraph(); p.Inlines.Add(headerRun); if (chat.Contains("\n")) { String[] lines = chat.Split(new[] { '\n' }); foreach ( Inline inn in lines.Select(line => line.Split(new[] { ' ' })).SelectMany( words => words.Select(word => StringToRun(word, fB)))) { if (inn != null) { p.Inlines.Add(inn); } p.Inlines.Add(new Run(" ")); } } else { String[] words = chat.Split(new[] { ' ' }); foreach (Inline inn in words.Select(word => StringToRun(word, fB))) { if (inn != null) { p.Inlines.Add(inn); } p.Inlines.Add(new Run(" ")); } } p.Background = bB; richTextBox1.Document.Blocks.Add(p); if (richTextBox1.Document.Blocks.Count > 1000) { try { richTextBox1.Document.Blocks.Remove(richTextBox1.Document.Blocks.FirstBlock); } catch (Exception e) { Debug.WriteLine(e); if (Debugger.IsAttached) { Debugger.Break(); } } } if (rtbatbottom) { richTextBox1.ScrollToEnd(); } }
private void makeControls(ReferenceItem referenceItem) { if (!referenceItem.HasParameters) { return; } Panel panel = new Panel(); panel.Style.Add("border", "none"); panel.Style.Add("margin-bottom", "10px"); Literal literal = new Literal(); literal.Text = string.Format("<strong>{0}</strong><br/>", referenceItem.Name); panel.ID = Control.GetUniqueID(string.Concat("params_", referenceItem.GetType().Name.ToLower(), "_", referenceItem.Name.ToLower(), "_")); panel.Controls.Add(literal); foreach (var pi in referenceItem.Parameters) { Inline i = new Inline(); Label l = new Label(); l.Header = pi.Title + ":"; l.Style.Add("font-weight", "bold"); l.Style.Add("margin-right", "10px"); l.Style.Add("margin-left", "20px"); l.Style.Add("width", "100px"); l.Style.Add("text-align", "right"); l.Style.Add("float", "left"); Control input = pi.MakeControl(); l.For = input.ID; i.Style.Add("display", "block"); i.Style.Add("margin-top", "5px"); i.Value = input.ID; i.ID = Control.GetUniqueID("params_" + pi.Name + "_"); i.Controls.Add(l); i.Controls.Add(input); Literal lit = new Literal(); lit.Text = "<br/>"; i.Controls.Add(lit); panel.Controls.Add(i); } ConfigSection.Controls.Add(panel); }
/// <summary> /// Return formatting object for span element /// </summary> /// <param name="regionId"></param> /// <param name="tick"></param> /// <returns></returns> public override FormattingObject GetFormattingObject(TimeCode tick) { if (TemporallyActive(tick)) { var block = new Inline(this); foreach (var child in Children) { if (child is BrElement || child is AnonymousSpanElement) { #region Add text to the Inline formatting object var fo = (child as TimedTextElementBase).GetFormattingObject(tick); if (fo != null) { fo.Parent = block; block.Children.Add(fo); } #region copy metadata across to inline, since we want to use this foreach (var d in this.Metadata) { if (!child.Metadata.ContainsKey(d.Key)) { child.Metadata.Add(d.Key, d.Value); } } #endregion #endregion } else if (child is SpanElement) { #region flatten span hierarchy var fo = (child as SpanElement).GetFormattingObject(tick); if (fo != null) { /* /// Flattened nested <span>A<span>B</span>C</span> /// -> <Inline>A</Inline><Inline>B</Inline><Inline>C</Inline> /// by hoisting out to outer context. /// Hoisted elements will still inherit correctly, as style is inherited through /// the Timed Text tree, not the formatting object tree. /// something to watch out for when computing relative /// values though. */ foreach (var nestedInline in fo.Children) { nestedInline.Parent = block; block.Children.Add(nestedInline); } } #endregion } if (child is SetElement) { #region Add animations to Inline var fo = ((child as SetElement).GetFormattingObject(tick)) as Animation; if (fo != null) { block.Animations.Add(fo); } #endregion } } return block; } else { return null; } }
// ======================================== // constructor // ======================================== public MergeInlineCommand(Inline target, Inline merged) { _target = target; _merged = merged; }
private void Init() { if (this.Inlines != null) { Inline[] array = new Inline[this.Inlines.Count]; this.Inlines.CopyTo(array, 0x0); foreach (Inline inline in array) { this.paragraph_Info.Inlines.Add(inline); } } else { Util_MessageBox.AnalyzeUrl(this.paragraph_Info, this.MessageBoxText); } if (string.IsNullOrEmpty(this.Caption)) { base.Title = "QQ"; } else { base.Title = this.Caption; } if (this.MessageBoxImage != MessageBoxImage.None) { this.iconInfo.Visibility = Visibility.Visible; string str = null; switch (this.MessageBoxImage) { case MessageBoxImage.Hand: str = "Error.png"; break; case MessageBoxImage.Question: str = "Question.png"; break; case MessageBoxImage.Exclamation: str = "Warning.png"; break; case MessageBoxImage.Asterisk: str = "Information.png"; break; default: this.iconInfo.Visibility = Visibility.Collapsed; break; } string uriString = "pack://application:,,,/Bama.QQ.Controls;Component/res/IAProMessageBox/" + str; BitmapImage image = new BitmapImage(); image.BeginInit(); image.UriSource = new Uri(uriString); image.EndInit(); this.iconInfo.Source = image; } switch (this.MessageBoxButton) { case MessageBoxButton.OK: this.okButton.Visibility = Visibility.Visible; this.okButton.Focus(); this.okButton.IsCancel = true; this.okButton.IsDefault = true; this.MessageBoxResult = MessageBoxResult.OK; return; case MessageBoxButton.OKCancel: this.okButton.Visibility = Visibility.Visible; this.cancelButton.Visibility = Visibility.Visible; this.okButton.Focus(); this.okButton.IsDefault = true; this.cancelButton.IsCancel = true; this.MessageBoxResult = MessageBoxResult.Cancel; return; case ((MessageBoxButton)0x2): break; case MessageBoxButton.YesNoCancel: this.yesButton.Visibility = Visibility.Visible; this.noButton.Visibility = Visibility.Visible; this.cancelButton.Visibility = Visibility.Visible; this.yesButton.Focus(); this.yesButton.IsDefault = true; this.cancelButton.IsCancel = true; this.MessageBoxResult = MessageBoxResult.Cancel; break; case MessageBoxButton.YesNo: this.yesButton.Visibility = Visibility.Visible; this.noButton.Visibility = Visibility.Visible; this.yesButton.Focus(); this.yesButton.IsDefault = true; this.noButton.IsCancel = true; this.MessageBoxResult = MessageBoxResult.No; return; default: return; } }
public override void VisitMethodDeclaration (MethodDeclaration methodDeclaration) { base.VisitMethodDeclaration (methodDeclaration); var i = new Inline (); while (i.KeepGoing) { i.KeepGoing = false; methodDeclaration.AcceptVisitor (i); } }
private void RadWindow_Closed(object sender, WindowClosedEventArgs e) { this.Owner = null; this.originalImageInline = null; this.originalInline = null; this.replaceCurrentInlineCallback = null; }
public void ShowDialog(Inline targetInline, Action<Inline, Inline> replaceCurrentInlineCallback) { this.ShowDialogInternal(targetInline, replaceCurrentInlineCallback, null); }
internal static int MatchInlineStack(InlineStack opener, Subject subj, int closingDelimeterCount, InlineStack closer, InlineTag?singleCharTag, InlineTag?doubleCharTag) { // calculate the actual number of delimeters used from this closer int useDelims; var openerDelims = opener.DelimeterCount; if (closingDelimeterCount < 3 || openerDelims < 3) { useDelims = closingDelimeterCount <= openerDelims ? closingDelimeterCount : openerDelims; if (useDelims == 1 && singleCharTag == null) { return(0); } } else if (singleCharTag == null) { useDelims = 2; } else if (doubleCharTag == null) { useDelims = 1; } else { useDelims = closingDelimeterCount % 2 == 0 ? 2 : 1; } Inline inl = opener.StartingInline; if (openerDelims == useDelims) { // the opener is completely used up - remove the stack entry and reuse the inline element inl.Tag = useDelims == 1 ? singleCharTag.Value : doubleCharTag.Value; inl.LiteralContent = null; inl.FirstChild = inl.NextSibling; inl.NextSibling = null; InlineStack.RemoveStackEntry(opener, subj, closer.Previous); } else { // the opener will only partially be used - stack entry remains (truncated) and a new inline is added. opener.DelimeterCount -= useDelims; inl.LiteralContent = inl.LiteralContent.Substring(0, opener.DelimeterCount); inl.SourceLastPosition -= useDelims; inl.NextSibling = new Inline(useDelims == 1 ? singleCharTag.Value : doubleCharTag.Value, inl.NextSibling); inl = inl.NextSibling; inl.SourcePosition = opener.StartingInline.SourcePosition + opener.DelimeterCount; } // there are two callers for this method, distinguished by the `closer` argument. // if closer == null it means the method is called during the initial subject parsing and the closer // characters are at the current position in the subject. The main benefit is that there is nothing // parsed that is located after the matched inline element. // if closer != null it means the method is called when the second pass for previously unmatched // stack elements is done. The drawback is that there can be other elements after the closer. if (closer != null) { var clInl = closer.StartingInline; if ((closer.DelimeterCount -= useDelims) > 0) { // a new inline element must be created because the old one has to be the one that // finalizes the children of the emphasis var newCloserInline = new Inline(clInl.LiteralContent.Substring(useDelims)); newCloserInline.SourcePosition = inl.SourceLastPosition = clInl.SourcePosition + useDelims; newCloserInline.SourceLength = closer.DelimeterCount; newCloserInline.NextSibling = clInl.NextSibling; clInl.LiteralContent = null; clInl.NextSibling = null; inl.NextSibling = closer.StartingInline = newCloserInline; } else { inl.SourceLastPosition = clInl.SourceLastPosition; clInl.LiteralContent = null; inl.NextSibling = clInl.NextSibling; clInl.NextSibling = null; } } else if (subj != null) { inl.SourceLastPosition = subj.Position - closingDelimeterCount + useDelims; subj.LastInline = inl; } return(useDelims); }
/// <summary> /// Initializes a new instance of Underline element and adds a given Subscript element as its first child. /// </summary> /// <param name="childInline"> /// Inline element added as an initial child to this Underline element /// </param> public Underline(Inline childInline) : base(childInline) { }
/// <summary>Initializes a new instance of the <see cref="CommonMarkException" /> class with a specified error message, a reference to the element that caused it and a reference to the inner exception that is the cause of this exception.</summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="inline">The inline element that is related to the exception cause.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a <c>null</c> reference (<c>Nothing</c> in Visual Basic) if no inner exception is specified.</param> public CommonMarkException(string message, Inline inline, Exception innerException = null) : base(message, innerException) { this.InlineElement = inline; }
/// <summary> /// Creates a new Underline instance. /// </summary> /// <param name="childInline"> /// Optional child Inline for the new Underline. May be null. /// </param> /// <param name="insertionPosition"> /// Optional position at which to insert the new Underline. May be null. /// </param> public Underline(Inline childInline, TextPointer insertionPosition) : base(childInline, insertionPosition) { }
/// <summary> /// Creates a new Italic instance. /// </summary> /// <param name="childInline"> /// Optional child Inline for the new Italic. May be null. /// </param> /// <param name="insertionPosition"> /// Optional position at which to insert the new Italic. May be null. /// </param> public Italic(Inline childInline, TextPointer insertionPosition) : base(childInline, insertionPosition) { }
/// <summary> /// Shows the dialog. Specified insert image callback is applied on user confirmation. /// </summary> /// <param name="selectedImage">The selected image.</param> /// <param name="replaceCurrentInlineCallback">The replace image callback.</param> public void ShowDialog(Inline selectedImage, Action<Inline, Inline> replaceCurrentInlineCallback, string executeToolName) { this.ShowDialogInternal(selectedImage, replaceCurrentInlineCallback, executeToolName, null); }
/// <summary> /// Shows the dialog. Specified insert image callback is applied on user confirmation. /// </summary> /// <param name="selectedImage">The selected image.</param> /// <param name="replaceCurrentImageCallback">The insert image callback.</param> /// <param name="executeToolName"></param> /// <param name="owner">The owner of the dialog.</param> public void ShowDialog(Inline selectedImage, Action<Inline, Inline> replaceCurrentImageCallback, string executeToolName, RadRichTextBox owner) { this.ShowDialogInternal(selectedImage, replaceCurrentImageCallback, executeToolName, owner); }
public static Bold Bold(this Inline inline) { Argument.IsNotNull(() => inline); return(new Bold(inline)); }
//public static void ChangeBlockFontSize(this Table block, int change) //{ // if (change == 0) return; // block.FontSize = Math.Max(1, block.FontSize + change); // foreach (var inline in block.RowGroups) // { // foreach (var row in inline.Rows) // { // } // } //} public static void ChangeFontSize(this Inline inline, int change) { inline.FontSize = Math.Max(1, inline.FontSize + change); }
public Inline StringToRun(String s, Brush b) { Inline ret = null; const string strUrlRegex = "(?i)\\b((?:[a-z][\\w-]+:(?:/{1,3}|[a-z0-9%])|www\\d{0,3}[.]|[a-z0-9.\\-]+[.][a-z]{2,4}/)(?:[^\\s()<>]+|\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\))+(?:\\(([^\\s()<>]+|(\\([^\\s()<>]+\\)))*\\)|[^\\s`!()\\[\\]{};:'\".,<>?«»“”‘’]))"; var reg = new Regex(strUrlRegex); s = s.Trim(); //b = Brushes.Black; Inline r = new Run(s); if (reg.IsMatch(s)) { b = Brushes.LightBlue; var h = new Hyperlink(r); h.RequestNavigate += HRequestNavigate; try { h.NavigateUri = new Uri(s); } catch (UriFormatException) { s = "http://" + s; try { h.NavigateUri = new Uri(s); } catch (Exception) { r.Foreground = b; //var ul = new Underline(r); } } ret = h; } else { if (s.Equals(Program.LobbyClient.Username)) { b = Brushes.Blue; ret = new Bold(r); } else { Boolean fUser = false; if (listBox1.Items.Cast <NewUser>().Any(u => u.User.User == s)) { b = Brushes.LightGreen; ret = new Bold(r) { ToolTip = "Click to whisper" }; r.Cursor = Cursors.Hand; r.Background = Brushes.White; r.MouseEnter += delegate { r.Background = new RadialGradientBrush(Colors.DarkGray, Colors.WhiteSmoke); }; r.MouseLeave += delegate { r.Background = Brushes.White; }; fUser = true; } if (!fUser) { ret = new Run(s); } } } ret.Foreground = b; return(ret); }
protected abstract bool HandleHtmlElement(XmlProperty xmlProp, TreeNode node, Inline nodeRun);
static void ProcessMessage(MessageData data, Paragraph messageParagraph, bool append) { List <string> urls = new List <string>(); List <int> indices = new List <int>(); string[] parts = data.Message.Split(' '); foreach (string part in parts) { if (Regex.IsMatch(part, @"(((file|gopher|news|nntp|telnet|http|ftp|https|ftps|sftp)://)|(www\.))+(([a-zA-Z0-9\._-]+\.[a-zA-Z]{2,6})|([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}))(/[a-zA-Z0-9\&%_\./-~-]*)?", RegexOptions.IgnoreCase) /*Regex.IsMatch(part, @"^(http|https|ftp|)\://|[a-zA-Z0-9\-\.]+\.[a-zA-Z](:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&%\$#\=~])*[^\.\,\)\(\s]$")*/) { urls.Add(part); } } if (urls.Count > 0) { foreach (string url in urls) { indices.Add(data.Message.IndexOf(url)); data.Message = data.Message.Replace(url, ""); } if (!append) { messageParagraph.Inlines.Add(data.Message); } else { messageParagraph.Inlines.Add("\n" + data.Message); } Inline inline = messageParagraph.Inlines.LastInline; for (int i = indices.Count; i-- > 0;) { string url = urls[i]; int index = append ? indices[i] + 1 : indices[i]; Run run = new Run(url); TextPointer pointer = new TextRange(inline.ContentStart, inline.ContentEnd).Text == "\n" ? inline.ContentEnd : inline.ContentStart; Hyperlink link = new Hyperlink(run, pointer.GetPositionAtOffset(index)); link.IsEnabled = true; link.Click += delegate(object sender, RoutedEventArgs args) { try { Process.Start(url); } catch { try { Process.Start("http://" + url); } catch { } } }; } } else { if (!append) { messageParagraph.Inlines.Add(data.Message); } else { messageParagraph.Inlines.Add("\n" + data.Message); } } }
public TextBlockEx(Inline inline) : base(inline) { this.Loaded += OnLoaded; }
/// <summary> /// Writes the inline list to the given writer as plain text (without any HTML tags). /// </summary> /// <seealso href="https://github.com/jgm/CommonMark/issues/145"/> private static void InlinesToPlainText(HtmlTextWriter writer, Inline inline, Stack <InlineStackEntry> stack) { bool withinLink = false; bool stackWithinLink = false; bool visitChildren; string stackLiteral = null; var origStackCount = stack.Count; while (inline != null) { visitChildren = false; switch (inline.Tag) { case InlineTag.String: case InlineTag.Code: case InlineTag.RawHtml: EscapeHtml(inline.LiteralContentValue, writer); break; case InlineTag.LineBreak: case InlineTag.SoftBreak: writer.WriteLine(); break; case InlineTag.Link: if (withinLink) { writer.Write('['); stackLiteral = "]"; visitChildren = true; stackWithinLink = true; } else { visitChildren = true; stackWithinLink = true; stackLiteral = string.Empty; } break; case InlineTag.Image: visitChildren = true; stackWithinLink = true; stackLiteral = string.Empty; break; case InlineTag.Strong: case InlineTag.Emphasis: case InlineTag.Strikethrough: stackLiteral = string.Empty; stackWithinLink = withinLink; visitChildren = true; break; default: throw new CommonMarkException("Inline type " + inline.Tag + " is not supported.", inline); } if (visitChildren) { stack.Push(new InlineStackEntry(stackLiteral, inline.NextSibling, withinLink)); withinLink = stackWithinLink; inline = inline.FirstChild; } else if (inline.NextSibling != null) { inline = inline.NextSibling; } else { inline = null; } while (inline == null && stack.Count > origStackCount) { var entry = stack.Pop(); writer.WriteConstant(entry.Literal); inline = entry.Target; withinLink = entry.IsWithinLink; } } }
public RCONOutput_TimedCommand(Inline output) : this() { base.Inlines.Add(output); }
public InlineStackEntry(string literal, Inline target, bool isWithinLink) { Literal = literal; Target = target; IsWithinLink = isWithinLink; }
void Siblings() { // <Snippet_Inline_SiblingBase> // A host paragraph to hold the example Inline elements.. Paragraph par = new Paragraph(); // Some arbitrary Inline elements. Run run1 = new Run("Text run number 1."); Run run2 = new Run("Text run number 2."); Bold bold = new Bold(new Run("Bold text.")); Italic ital = new Italic(new Run("Italic text.")); Span span1 = new Span(new Run("Span number 1")); Span span2 = new Span(new Run("Span number 2")); // Add the Inline elements to the Paragraph. Note the order // of the inline elements in the paragraph; the order is // arbitrary, but the notion of an order is important with // respect to what are 'previous' and 'next' elements. par.Inlines.Add(run1); par.Inlines.Add(run2); par.Inlines.Add(bold); par.Inlines.Add(ital); par.Inlines.Add(span1); par.Inlines.Add(span2); // </Snippet_Inline_SiblingBase> // <Snippet_Inline_NextSibling> // After this line executes, "nextSibling" holds "run2", which is // the next peer-level Inline following "run1". Inline nextSibling = run1.NextInline; // After this line executes, "nextSibling" holds "span1", which is // the next peer-level Inline following "ital". nextSibling = ital.NextInline; // After this line executes, "nextSibling" is null, since "span2" is the // last Inline element in the Paragraph. nextSibling = span2.NextInline; // </Snippet_Inline_NextSibling> // <Snippet_Inline_PreviousSibling> // After this line exectues, "previousSibling" is null, since "run1" is // the first Inline element in the Paragraph. Inline previousSibling = run1.PreviousInline; // After this line executes, "previousSibling" holds "bold", which is the // first peer-level Inline preceeding "ital". previousSibling = ital.PreviousInline; // After this line executes, "previousSibling" holds "span1", which is the // first peer-level Inline preceeding "span1". previousSibling = span2.NextInline; // </Snippet_Inline_PreviousSibling> // <Snippet_Inline_Siblings> // After this line executes, "siblingInlines" holds "run1", "run2", // "bold", "ital", "span1", and "span2", which are all of the sibling // Inline elements for "run1" (including "run1"); InlineCollection siblingInlines = run1.SiblingInlines; // Since "bold" is a sibling to "run1", this call will return the // same collection of sibling elements as the previous call. siblingInlines = bold.SiblingInlines; // </Snippet_Inline_Siblings> }
/// <summary> /// Update the properties on the inline instance. /// </summary> /// <param name="inline">The instance.</param> public override void UpdateInline(Inline inline) { ((Run)inline).Text = _text; }
/// <summary> /// Initializes a new instance of Bold element and adds a given Inline element as its first child. /// </summary> /// <param name="childInline"> /// Inline element added as an initial child to this Bold element /// </param> public Bold(Inline childInline) : base(childInline) { }
/// <summary> /// Creates a new Bold instance. /// </summary> /// <param name="childInline"> /// Optional child Inline for the new Bold. May be null. /// </param> /// <param name="insertionPosition"> /// Optional position at which to insert the new Bold. May be null. /// </param> public Bold(Inline childInline, TextPointer insertionPosition) : base(childInline, insertionPosition) { }
private static Inline HandleRightSquareBracket(Subject subj) { // move past ']' subj.Position++; bool canClose; var istack = InlineStack.FindMatchingOpener(subj.LastPendingInline, InlineStack.InlineStackPriority.Links, '[', out canClose); if (istack != null) { // if the opener is "inactive" then it means that there was a nested link if (istack.DelimeterCount == -1) { InlineStack.RemoveStackEntry(istack, subj, istack); return(new Inline("]", subj.Position - 1, subj.Position)); } var endpos = subj.Position; // try parsing details for '[foo](/url "title")' or '[foo][bar]' var details = ParseLinkDetails(subj); // try lookup of the brackets themselves if (details == null || details == Reference.SelfReference) { var startpos = istack.StartPosition; var label = new StringPart(subj.Buffer, startpos, endpos - startpos - 1); details = LookupReference(subj.ReferenceMap, label); } if (details == Reference.InvalidReference) { details = null; } MatchSquareBracketStack(istack, subj, details); return(null); } var inlText = new Inline("]", subj.Position - 1, subj.Position); if (canClose) { // note that the current implementation will not work if there are other inlines with priority // higher than Links. // to fix this the parsed link details should be added to the closer element in the stack. throw new NotSupportedException("It is not supported to have inline stack priority higher than Links."); ////istack = new InlineStack(); ////istack.Delimeter = '['; ////istack.StartingInline = inlText; ////istack.StartPosition = subj.Position; ////istack.Priority = InlineStack.InlineStackPriority.Links; ////istack.Flags = InlineStack.InlineStackFlags.Closer; ////InlineStack.AppendStackEntry(istack, subj); } return(inlText); }
// ------------------------------------------------------------------ // Fetch the next run at element open edge position. // // position - current position in the text array // ------------------------------------------------------------------ private TextRun HandleElementStartEdge(StaticTextPointer position) { Debug.Assert(position.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.ElementStart, "TextPointer does not point to element start edge."); // TextRun run = null; TextElement element = (TextElement)position.GetAdjacentElement(LogicalDirection.Forward); Debug.Assert(element != null, "Cannot use ITextContainer that does not provide TextElement instances."); if (element is LineBreak) { run = new TextEndOfLine(_elementEdgeCharacterLength * 2); } else if (element.IsEmpty) { // Empty TextElement should affect line metrics. // TextFormatter does not support this feature right now, so as workaround // TextRun with ZERO WIDTH SPACE is used. TextRunProperties textProps = new TextProperties(element, position, false /* inline objects */, true /* get background */); char[] textBuffer = new char[_elementEdgeCharacterLength * 2]; textBuffer[0] = (char)0x200B; textBuffer[1] = (char)0x200B; run = new TextCharacters(textBuffer, 0, textBuffer.Length, textProps); } else { Inline inline = element as Inline; if (inline == null) { run = new TextHidden(_elementEdgeCharacterLength); } else { DependencyObject parent = inline.Parent; FlowDirection inlineFlowDirection = inline.FlowDirection; FlowDirection parentFlowDirection = inlineFlowDirection; if (parent != null) { parentFlowDirection = (FlowDirection)parent.GetValue(FrameworkElement.FlowDirectionProperty); } TextDecorationCollection inlineTextDecorations = DynamicPropertyReader.GetTextDecorations(inline); if (inlineFlowDirection != parentFlowDirection) { // Inline's flow direction is different from its parent. Need to create new TextSpanModifier with flow direction if (inlineTextDecorations == null || inlineTextDecorations.Count == 0) { run = new TextSpanModifier( _elementEdgeCharacterLength, null, null, inlineFlowDirection ); } else { run = new TextSpanModifier( _elementEdgeCharacterLength, inlineTextDecorations, inline.Foreground, inlineFlowDirection ); } } else { if (inlineTextDecorations == null || inlineTextDecorations.Count == 0) { run = new TextHidden(_elementEdgeCharacterLength); } else { run = new TextSpanModifier( _elementEdgeCharacterLength, inlineTextDecorations, inline.Foreground ); } } } } return(run); }
public void AddInline(Inline inline) { TextBlockInformation.Inlines.Add(inline); }
/// <summary> /// Event handler for KeyDown event to auto-detect hyperlinks on space, enter and backspace keys. /// </summary> private static void OnKeyDown(object sender, KeyEventArgs e) { var myRichTextBox = (MyRichTextBox)sender; if (e.Key != Key.Space && e.Key != Key.Back && e.Key != Key.Return) { return; } if (!myRichTextBox.Selection.IsEmpty) { myRichTextBox.Selection.Text = String.Empty; } TextPointer caretPosition = myRichTextBox.Selection.Start; if (e.Key == Key.Space || e.Key == Key.Return) { TextPointer wordStartPosition; string word = GetPreceedingWordInParagraph(caretPosition, out wordStartPosition); if (word == "www.microsoft.com") // A real app would need a more sophisticated RegEx match expression for hyperlinks. { // Insert hyperlink element at word boundaries. var start = wordStartPosition.GetPositionAtOffset(0, LogicalDirection.Backward); var end = caretPosition.GetPositionAtOffset(0, LogicalDirection.Forward); if (start != null) { if (end != null) { new Hyperlink(start , end); } } // No need to update RichTextBox caret position, // since we only inserted a Hyperlink ElementEnd following current caretPosition. // Subsequent handling of space input by base RichTextBox will update selection. } } else // Key.Back { TextPointer backspacePosition = caretPosition.GetNextInsertionPosition(LogicalDirection.Backward); Hyperlink hyperlink; if (backspacePosition != null && IsHyperlinkBoundaryCrossed(caretPosition, backspacePosition, out hyperlink)) { // Remember caretPosition with forward gravity. This is necessary since we are going to delete // the hyperlink element preceeding caretPosition and after deletion current caretPosition // (with backward gravity) will follow content preceeding the hyperlink. // We want to remember content following the hyperlink to set new caret position at. TextPointer newCaretPosition = caretPosition.GetPositionAtOffset(0, LogicalDirection.Forward); // Deleting the hyperlink is done using logic below. // 1. Copy its children Inline to a temporary array. InlineCollection hyperlinkChildren = hyperlink.Inlines; var inlines = new Inline[hyperlinkChildren.Count]; hyperlinkChildren.CopyTo(inlines, 0); // 2. Remove each child from parent hyperlink element and insert it after the hyperlink. for (int i = inlines.Length - 1; i >= 0; i--) { hyperlinkChildren.Remove(inlines[i]); if (hyperlink.SiblingInlines != null) { hyperlink.SiblingInlines.InsertAfter(hyperlink, inlines[i]); } } // 3. Apply hyperlink's local formatting properties to inlines (which are now outside hyperlink scope). LocalValueEnumerator localProperties = hyperlink.GetLocalValueEnumerator(); var inlineRange = new TextRange(inlines[0].ContentStart, inlines[inlines.Length - 1].ContentEnd); while (localProperties.MoveNext()) { LocalValueEntry property = localProperties.Current; DependencyProperty dp = property.Property; object value = property.Value; if (!dp.ReadOnly && dp != Inline.TextDecorationsProperty && // Ignore hyperlink defaults. dp != TextElement.ForegroundProperty && !IsHyperlinkProperty(dp)) { inlineRange.ApplyPropertyValue(dp, value); } } // 4. Delete the (empty) hyperlink element. if (hyperlink.SiblingInlines != null) { hyperlink.SiblingInlines.Remove(hyperlink); } // 5. Update selection, since we deleted Hyperlink element and caretPosition was at that Hyperlink's end boundary. if (newCaretPosition != null) { myRichTextBox.Selection.Select(newCaretPosition, newCaretPosition); } } } }
private bool MakeControls(ReferenceItem referenceItem) { if (!referenceItem.HasParameters) { return false; } var panel = new Panel(); panel.Style.Add("border", "none"); panel.Style.Add("margin-bottom", "10px"); var literal = new Literal { Text = string.Format("<div style=\"margin-left:10px;margin-top:4px;font-weight:bold\">{0}</div><br/>", referenceItem.PrettyName) }; panel.ID = Control.GetUniqueID( string.Concat("params_", referenceItem.GetType().Name.ToLower(), "_", referenceItem.Name.ToLower(), "_")); panel.Controls.Add(literal); foreach (var pi in referenceItem.Parameters) { var i = new Inline(); var l = new Label {Header = pi.Title + ":"}; l.Style.Add("font-weight", "bold"); l.Style.Add("padding-top", "5px"); l.Style.Add("margin-right", "10px"); l.Style.Add("margin-left", "20px"); l.Style.Add("width", "100px"); l.Style.Add("text-align", "right"); l.Style.Add("float", "left"); var input = pi.MakeControl(); l.For = input.ID; i.Style.Add("display", "block"); i.Style.Add("margin-top", "5px"); i.Value = input.ID; i.ID = Control.GetUniqueID("params_" + pi.Name + "_"); i.Controls.Add(l); i.Controls.Add(input); var lit = new Literal {Text = "<br/>"}; i.Controls.Add(lit); panel.Controls.Add(i); } ConfigSection.Controls.Add(panel); return true; }
public void Add(Inline text) { _span.Inlines.Add(text); }
/// <summary> /// Initializes a new instance of Italic element and adds a given Inline element as its first child. /// </summary> /// <param name="childInline"> /// Inline element added as an initial child to this Italic element /// </param> public Italic(Inline childInline) : base(childInline) { }
public Paragraph AddToParentParagraph(Inline text) => _parent.AddToParentParagraph(text);
private static IEnumerable<Inline> EnumerateInlines(Inline inline) { if (inline == null) yield break; var stack = new Stack<Inline>(); stack.Push(inline); while (stack.Any()) { var next = stack.Pop(); yield return next; if (next.NextSibling != null) stack.Push(next.NextSibling); if (next.FirstChild != null) stack.Push(next.FirstChild); } }
static StandardElementMapping() { foObjs = new Hashtable(); // Declarations and Pagination and Layout Formatting Objects foObjs.Add("root", Root.GetMaker()); foObjs.Add("declarations", Declarations.GetMaker()); foObjs.Add("color-profile", ColorProfile.GetMaker()); foObjs.Add("page-sequence", PageSequence.GetMaker()); foObjs.Add("layout-master-set", LayoutMasterSet.GetMaker()); foObjs.Add("page-sequence-master", PageSequenceMaster.GetMaker()); foObjs.Add("single-page-master-reference", SinglePageMasterReference.GetMaker()); foObjs.Add("repeatable-page-master-reference", RepeatablePageMasterReference.GetMaker()); foObjs.Add("repeatable-page-master-alternatives", RepeatablePageMasterAlternatives.GetMaker()); foObjs.Add("conditional-page-master-reference", ConditionalPageMasterReference.GetMaker()); foObjs.Add("simple-page-master", SimplePageMaster.GetMaker()); foObjs.Add("region-body", RegionBody.GetMaker()); foObjs.Add("region-before", RegionBefore.GetMaker()); foObjs.Add("region-after", RegionAfter.GetMaker()); foObjs.Add("region-start", RegionStart.GetMaker()); foObjs.Add("region-end", RegionEnd.GetMaker()); foObjs.Add("flow", Flow.Flow.GetMaker()); foObjs.Add("static-content", StaticContent.GetMaker()); foObjs.Add("title", Title.GetMaker()); // Block-level Formatting Objects foObjs.Add("block", Block.GetMaker()); foObjs.Add("block-container", BlockContainer.GetMaker()); // Inline-level Formatting Objects foObjs.Add("bidi-override", BidiOverride.GetMaker()); foObjs.Add("character", Character.GetMaker()); foObjs.Add("initial-property-set", InitialPropertySet.GetMaker()); foObjs.Add("external-graphic", ExternalGraphic.GetMaker()); foObjs.Add("instream-foreign-object", InstreamForeignObject.GetMaker()); foObjs.Add("inline", Inline.GetMaker()); foObjs.Add("inline-container", InlineContainer.GetMaker()); foObjs.Add("leader", Leader.GetMaker()); foObjs.Add("page-number", PageNumber.GetMaker()); foObjs.Add("page-number-citation", PageNumberCitation.GetMaker()); // Formatting Objects for Tables foObjs.Add("table-and-caption", TableAndCaption.GetMaker()); foObjs.Add("table", Table.GetMaker()); foObjs.Add("table-column", TableColumn.GetMaker()); foObjs.Add("table-caption", TableCaption.GetMaker()); foObjs.Add("table-header", TableHeader.GetMaker()); foObjs.Add("table-footer", TableFooter.GetMaker()); foObjs.Add("table-body", TableBody.GetMaker()); foObjs.Add("table-row", TableRow.GetMaker()); foObjs.Add("table-cell", TableCell.GetMaker()); // Formatting Objects for Lists foObjs.Add("list-block", ListBlock.GetMaker()); foObjs.Add("list-item", ListItem.GetMaker()); foObjs.Add("list-item-body", ListItemBody.GetMaker()); foObjs.Add("list-item-label", ListItemLabel.GetMaker()); // Dynamic Effects: Link and Multi Formatting Objects foObjs.Add("basic-link", BasicLink.GetMaker()); foObjs.Add("multi-switch", MultiSwitch.GetMaker()); foObjs.Add("multi-case", MultiCase.GetMaker()); foObjs.Add("multi-toggle", MultiToggle.GetMaker()); foObjs.Add("multi-properties", MultiProperties.GetMaker()); foObjs.Add("multi-property-set", MultiPropertySet.GetMaker()); // Out-of-Line Formatting Objects foObjs.Add("float", Float.GetMaker()); foObjs.Add("footnote", Footnote.GetMaker()); foObjs.Add("footnote-body", FootnoteBody.GetMaker()); // Other Formatting Objects foObjs.Add("wrapper", Wrapper.GetMaker()); foObjs.Add("marker", Marker.GetMaker()); foObjs.Add("retrieve-marker", RetrieveMarker.GetMaker()); }
public NodeRenderingEventArgs(WebVTTCue cue, IWebVTTNode node, Inline inline) { Cue = cue; Node = node; Inline = inline; }
public void ShowDialog(Inline targetInline, Action<Inline, Inline> replaceCurrentInlineCallback, RadRichTextBox owner) { this.ShowDialogInternal(targetInline, replaceCurrentInlineCallback, owner); }