// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information. Code forked from Betsegaw Tadele's https://github.com/betsegaw/windowwalker/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Security;
using System.Windows.Data;
using System.Windows.Markup;
using System.Xml;
using WindowWalker.Components;
namespace WindowWalker
{
///
/// Converts a string containing valid XAML into WPF objects.
///
[ValueConversion(typeof(SearchResult), typeof(object))]
public sealed class WindowSearchResultToXamlConverter : IValueConverter
{
///
/// Converts a string containing valid XAML into WPF objects.
///
/// The string to convert.
/// This parameter is not used.
/// This parameter is not used.
/// This parameter is not used.
/// A WPF object.
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is SearchResult input)
{
string withTags;
if (input.BestScoreSource == SearchResult.TextType.ProcessName)
{
withTags = input.Result.Title;
withTags += $" ({InsertHighlightTags(input.Result.ProcessName, input.SearchMatchesInProcessName)})";
}
else
{
withTags = InsertHighlightTags(input.Result.Title, input.SearchMatchesInTitle);
withTags += $" ({input.Result.ProcessName})";
}
withTags = SecurityElement.Escape(withTags);
withTags = withTags.Replace("[[", "").
Replace("]]", "");
string wrappedInput = string.Format("{0}", withTags);
using (StringReader stringReader = new StringReader(wrappedInput))
{
using (XmlReader xmlReader = XmlReader.Create(stringReader))
{
return XamlReader.Load(xmlReader);
}
}
}
return null;
}
///
/// Converts WPF framework objects into a XAML string.
///
/// The WPF Famework object to convert.
/// This parameter is not used.
/// This parameter is not used.
/// This parameter is not used.
/// A string containg XAML.
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException("This converter cannot be used in two-way binding.");
}
private string InsertHighlightTags(string content, List indexes)
{
int offset = 0;
var result = content.Replace("[[", "**").Replace("]]", "**");
string startTag = "[[";
string stopTag = "]]";
foreach (var index in indexes)
{
result = result.Insert(index + offset, startTag);
result = result.Insert(index + offset + startTag.Length + 1, stopTag);
offset += startTag.Length + stopTag.Length;
}
return result;
}
}
}