From 28986641046c8ee1dc2aba0055dfa36b811b25d2 Mon Sep 17 00:00:00 2001 From: k0st1x Date: Sun, 30 Sep 2012 23:22:25 +0400 Subject: replace TextBlock by RichTextBox --- Juick/Classes/RichTextConverter.cs | 68 ++++++++++++++++++++++---------------- 1 file changed, 39 insertions(+), 29 deletions(-) (limited to 'Juick/Classes/RichTextConverter.cs') diff --git a/Juick/Classes/RichTextConverter.cs b/Juick/Classes/RichTextConverter.cs index ee6ffa7..cdc1938 100644 --- a/Juick/Classes/RichTextConverter.cs +++ b/Juick/Classes/RichTextConverter.cs @@ -1,53 +1,63 @@ using System; using System.Collections.Generic; using System.Globalization; -using System.Net; -using System.Windows; -using System.Windows.Controls; +using System.Linq; +using System.Text.RegularExpressions; using System.Windows.Data; using System.Windows.Documents; -using System.Windows.Ink; -using System.Windows.Input; -using System.Windows.Media; -using System.Windows.Media.Animation; -using System.Windows.Shapes; -using Microsoft.Phone.Tasks; namespace Juick.Classes { public class RichTextConverter : IValueConverter { + static readonly Regex UrlRegex = new Regex(@"http(s)?://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?", RegexOptions.Compiled); + public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { - var message = value as string; - var runs = new List(); - - foreach (var word in message.Split(new char[] {' ', '\n'})) + var stringValue = (string)value; + if (string.IsNullOrEmpty(stringValue)) { - Uri uri; + return Enumerable.Empty(); + } - if (Uri.TryCreate(word, UriKind.Absolute, out uri) || - (word.StartsWith("www.") && Uri.TryCreate("http://" + word, UriKind.Absolute, out uri))) + var result = new List(); + var index = 0; + foreach (var match in UrlRegex.Matches(stringValue).Cast()) + { + Uri uri = null; + if (!Uri.TryCreate(match.Value, UriKind.Absolute, out uri)) { - var link = new Hyperlink(); - link.Inlines.Add(new Run() { Text = word }); - link.Click += (sender, e) => - { - var hyperLink = (sender as Hyperlink); - new WebBrowserTask() { Uri = uri }.Show(); - }; - - runs.Add(link); + continue; } - else + if (match.Index > 0) { - runs.Add(new Run() { Text = word }); + var length = match.Index - index; + if (length > 0) + { + result.Add(new Run { Text = stringValue.Substring(index, length) }); + } } - runs.Add(new Run() { Text = " " }); + var hyperLink = new Hyperlink + { + NavigateUri = uri, + TargetName = "_blank" + }; + hyperLink.Inlines.Add(uri.Host); + result.Add(hyperLink); + + index = match.Index + match.Length; } - return runs; + if (index == 0 || index < stringValue.Length - 1) + { + var lastRunText = stringValue.Substring(index); + if (lastRunText.Length > 0) + { + result.Add(new Run { Text = lastRunText }); + } + } + return result; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) -- cgit v1.2.3