PowerToys/Wox.Infrastructure/StringMatcher.cs

321 lines
12 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Wox.Infrastructure.Logger;
using Wox.Infrastructure.UserSettings;
using static Wox.Infrastructure.StringMatcher;
namespace Wox.Infrastructure
2015-02-07 16:53:33 +08:00
{
public static class StringMatcher
2015-02-07 16:53:33 +08:00
{
2019-10-20 20:45:06 +08:00
public static MatchOption DefaultMatchOption = new MatchOption();
2019-10-17 18:37:09 +08:00
public static int UserSettingSearchPrecision { get; set; }
public static bool ShouldUsePinyin { get; set; }
[Obsolete("This method is obsolete and should not be used. Please use the static function StringMatcher.FuzzySearch")]
public static int Score(string source, string target)
2015-02-07 16:53:33 +08:00
{
if (!string.IsNullOrEmpty(source) && !string.IsNullOrEmpty(target))
{
2019-10-20 20:45:06 +08:00
return FuzzySearch(target, source, DefaultMatchOption).Score;
}
else
{
return 0;
}
}
2015-02-07 16:53:33 +08:00
[Obsolete("This method is obsolete and should not be used. Please use the static function StringMatcher.FuzzySearch")]
public static bool IsMatch(string source, string target)
{
2019-10-20 20:45:06 +08:00
return FuzzySearch(target, source, DefaultMatchOption).Score > 0;
}
2019-09-29 13:03:30 +08:00
public static MatchResult FuzzySearch(string query, string stringToCompare)
{
2019-10-20 20:45:06 +08:00
return FuzzySearch(query, stringToCompare, DefaultMatchOption);
}
/// <summary>
/// refer to https://github.com/mattyork/fuzzy
/// </summary>
public static MatchResult FuzzySearch(string query, string stringToCompare, MatchOption opt)
{
if (string.IsNullOrEmpty(stringToCompare) || string.IsNullOrEmpty(query)) return new MatchResult { Success = false };
2019-10-17 18:37:09 +08:00
query = query.Trim();
var fullStringToCompareWithoutCase = opt.IgnoreCase ? stringToCompare.ToLower() : stringToCompare;
var queryWithoutCase = opt.IgnoreCase ? query.ToLower() : query;
var querySubstrings = queryWithoutCase.Split(' ');
int currentQuerySubstringIndex = 0;
var currentQuerySubstring = querySubstrings[currentQuerySubstringIndex];
var currentQuerySubstringCharacterIndex = 0;
var firstMatchIndex = -1;
var firstMatchIndexInWord = -1;
var lastMatchIndex = 0;
bool allQuerySubstringsMatched = false;
bool matchFoundInPreviousLoop = false;
bool allWordsFullyMatched = true;
var indexList = new List<int>();
for (var compareStringIndex = 0; compareStringIndex < fullStringToCompareWithoutCase.Length; compareStringIndex++)
{
2020-01-06 16:15:05 +08:00
if (fullStringToCompareWithoutCase[compareStringIndex] != currentQuerySubstring[currentQuerySubstringCharacterIndex])
{
2020-01-06 16:15:05 +08:00
matchFoundInPreviousLoop = false;
continue;
}
if (firstMatchIndex < 0)
{
// first matched char will become the start of the compared string
firstMatchIndex = compareStringIndex;
}
if (currentQuerySubstringCharacterIndex == 0)
{
// first letter of current word
matchFoundInPreviousLoop = true;
firstMatchIndexInWord = compareStringIndex;
}
else if (!matchFoundInPreviousLoop)
{
// we want to verify that there is not a better match if this is not a full word
// in order to do so we need to verify all previous chars are part of the pattern
var startIndexToVerify = compareStringIndex - currentQuerySubstringCharacterIndex;
2020-01-06 16:15:05 +08:00
if (AllPreviousCharsMatched(startIndexToVerify, currentQuerySubstringCharacterIndex, fullStringToCompareWithoutCase, currentQuerySubstring))
{
matchFoundInPreviousLoop = true;
2020-01-06 16:15:05 +08:00
// if it's the begining character of the first query substring that is matched then we need to update start index
firstMatchIndex = currentQuerySubstringIndex == 0 ? startIndexToVerify : firstMatchIndex;
indexList = GetUpdatedIndexList(startIndexToVerify, currentQuerySubstringCharacterIndex, firstMatchIndexInWord, indexList);
}
2020-01-06 16:15:05 +08:00
}
2020-01-06 16:15:05 +08:00
lastMatchIndex = compareStringIndex + 1;
indexList.Add(compareStringIndex);
2020-01-06 16:15:05 +08:00
currentQuerySubstringCharacterIndex++;
2020-01-06 16:15:05 +08:00
// if finished looping through every character in the substring
if (currentQuerySubstringCharacterIndex == currentQuerySubstring.Length)
{
currentQuerySubstringIndex++;
2020-01-06 16:15:05 +08:00
// if all query substrings are matched
if (currentQuerySubstringIndex >= querySubstrings.Length)
{
allQuerySubstringsMatched = true;
break;
}
2020-01-06 16:15:05 +08:00
// otherwise move to the next query substring
currentQuerySubstring = querySubstrings[currentQuerySubstringIndex];
currentQuerySubstringCharacterIndex = 0;
2020-01-02 05:02:23 +08:00
2020-01-06 16:15:05 +08:00
if (!matchFoundInPreviousLoop)
{
2020-01-06 16:15:05 +08:00
// if any of the words was not fully matched all are not fully matched
allWordsFullyMatched = false;
}
}
}
// return rendered string if we have a match for every char or all substring without whitespaces matched
if (allQuerySubstringsMatched)
{
// check if all query string was contained in string to compare
bool containedFully = lastMatchIndex - firstMatchIndex == queryWithoutCase.Length;
var score = CalculateSearchScore(query, stringToCompare, firstMatchIndex, lastMatchIndex - firstMatchIndex, containedFully, allWordsFullyMatched);
var pinyinScore = ScoreForPinyin(stringToCompare, query);
var result = new MatchResult
{
Success = true,
MatchData = indexList,
RawScore = Math.Max(score, pinyinScore)
};
2019-12-12 02:10:11 +08:00
return result;
}
return new MatchResult { Success = false };
}
private static bool AllPreviousCharsMatched(int startIndexToVerify, int currentQuerySubstringCharacterIndex,
string fullStringToCompareWithoutCase, string currentQuerySubstring)
{
var allMatch = true;
for (int indexToCheck = 0; indexToCheck < currentQuerySubstringCharacterIndex; indexToCheck++)
{
if (fullStringToCompareWithoutCase[startIndexToVerify + indexToCheck] !=
currentQuerySubstring[indexToCheck])
{
allMatch = false;
}
}
return allMatch;
}
private static List<int> GetUpdatedIndexList(int startIndexToVerify, int currentQuerySubstringCharacterIndex, int firstMatchIndexInWord, List<int> indexList)
{
var updatedList = new List<int>();
indexList.RemoveAll(x => x >= firstMatchIndexInWord);
updatedList.AddRange(indexList);
for (int indexToCheck = 0; indexToCheck < currentQuerySubstringCharacterIndex; indexToCheck++)
{
updatedList.Add(startIndexToVerify + indexToCheck);
}
return updatedList;
}
private static int CalculateSearchScore(string query, string stringToCompare, int firstIndex, int matchLen,
bool isFullyContained, bool allWordsFullyMatched)
{
2019-11-28 19:44:01 +08:00
// A match found near the beginning of a string is scored more than a match found near the end
// A match is scored more if the characters in the patterns are closer to each other,
// while the score is lower if they are more spread out
var score = 100 * (query.Length + 1) / ((1 + firstIndex) + (matchLen + 1));
2019-11-28 19:44:01 +08:00
// A match with less characters assigning more weights
if (stringToCompare.Length - query.Length < 5)
2019-11-28 19:44:01 +08:00
{
2019-10-17 18:37:09 +08:00
score += 20;
2019-11-28 19:44:01 +08:00
}
else if (stringToCompare.Length - query.Length < 10)
2019-11-28 19:44:01 +08:00
{
2019-10-17 18:37:09 +08:00
score += 10;
2019-11-28 19:44:01 +08:00
}
if (isFullyContained)
{
score += 20; // honestly I'm not sure what would be a good number here or should it factor the size of the pattern
}
if (allWordsFullyMatched)
{
score += 20;
}
return score;
}
2019-09-29 13:03:30 +08:00
public enum SearchPrecisionScore
{
Regular = 50,
Low = 20,
None = 0
}
public static int ScoreForPinyin(string source, string target)
{
if (!ShouldUsePinyin)
{
return 0;
}
if (!string.IsNullOrEmpty(source) && !string.IsNullOrEmpty(target))
{
if (Alphabet.ContainsChinese(source))
{
var combination = Alphabet.PinyinComination(source);
var pinyinScore = combination
2019-10-17 18:37:09 +08:00
.Select(pinyin => FuzzySearch(target, string.Join("", pinyin)).Score)
.Max();
var acronymScore = combination.Select(Alphabet.Acronym)
2019-10-17 18:37:09 +08:00
.Select(pinyin => FuzzySearch(target, pinyin).Score)
.Max();
var score = Math.Max(pinyinScore, acronymScore);
return score;
}
else
{
return 0;
}
}
else
{
return 0;
}
}
}
2015-02-07 16:53:33 +08:00
public class MatchResult
{
public bool Success { get; set; }
/// <summary>
/// The final score of the match result with all search precision filters applied.
/// </summary>
public int Score { get; private set; }
/// <summary>
/// The raw calculated search score without any search precision filtering applied.
/// </summary>
private int _rawScore;
public int RawScore
{
get { return _rawScore; }
set
{
_rawScore = value;
Score = ApplySearchPrecisionFilter(_rawScore);
}
}
/// <summary>
/// Matched data to highlight.
/// </summary>
public List<int> MatchData { get; set; }
public bool IsSearchPrecisionScoreMet()
{
return IsSearchPrecisionScoreMet(Score);
}
private bool IsSearchPrecisionScoreMet(int score)
{
return score >= UserSettingSearchPrecision;
}
private int ApplySearchPrecisionFilter(int score)
{
return IsSearchPrecisionScoreMet(score) ? score : 0;
}
}
public class MatchOption
{
/// <summary>
/// prefix of match char, use for hightlight
/// </summary>
[Obsolete("this is never used")]
public string Prefix { get; set; } = "";
/// <summary>
/// suffix of match char, use for hightlight
/// </summary>
[Obsolete("this is never used")]
public string Suffix { get; set; } = "";
public bool IgnoreCase { get; set; } = true;
2015-02-07 16:53:33 +08:00
}
}