Flow.Launcher/Flow.Launcher.Infrastructure/PinyinAlphabet.cs

85 lines
2.7 KiB
C#
Raw Normal View History

using System;
2017-01-12 20:46:40 +00:00
using System.Collections.Concurrent;
using System.Linq;
using System.Text;
using JetBrains.Annotations;
2020-04-21 09:12:17 +00:00
using Flow.Launcher.Infrastructure.UserSettings;
2020-10-15 13:06:57 +00:00
using ToolGood.Words.Pinyin;
2020-04-21 09:12:17 +00:00
namespace Flow.Launcher.Infrastructure
{
public interface IAlphabet
{
string Translate(string stringToTranslate);
}
public class PinyinAlphabet : IAlphabet
{
2020-10-25 02:26:56 +00:00
private ConcurrentDictionary<string, string> _pinyinCache = new ConcurrentDictionary<string, string>();
private Settings _settings;
2020-10-15 13:06:57 +00:00
public void Initialize([NotNull] Settings settings)
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
2017-01-12 02:16:53 +00:00
}
2020-10-15 13:06:57 +00:00
public string Translate(string content)
{
2020-10-15 13:06:57 +00:00
if (_settings.ShouldUsePinyin)
{
2020-10-19 12:37:40 +00:00
if (!_pinyinCache.ContainsKey(content))
{
2020-10-15 13:06:57 +00:00
if (WordsHelper.HasChinese(content))
2017-01-12 20:46:40 +00:00
{
var resultList = WordsHelper.GetPinyinList(content);
StringBuilder resultBuilder = new StringBuilder();
2020-12-11 14:20:09 +00:00
for (int i = 0; i < resultList.Length; i++)
2020-12-11 14:20:09 +00:00
{
if (content[i] >= 0x3400 && content[i] <= 0x9FD5)
resultBuilder.Append(resultList[i].First());
2020-12-11 14:20:09 +00:00
}
resultBuilder.Append(' ');
bool pre = false;
for (int i = 0; i < resultList.Length; i++)
{
if (content[i] >= 0x3400 && content[i] <= 0x9FD5)
{
resultBuilder.Append(' ');
resultBuilder.Append(resultList[i]);
pre = true;
}
else
{
if (pre)
{
pre = false;
resultBuilder.Append(' ');
}
resultBuilder.Append(resultList[i]);
}
}
return _pinyinCache[content] = resultBuilder.ToString();
}
else
{
return content;
2017-01-12 20:46:40 +00:00
}
2017-01-12 02:16:53 +00:00
}
2020-10-18 03:48:17 +00:00
else
2020-10-19 12:40:22 +00:00
{
2020-10-18 03:48:17 +00:00
return _pinyinCache[content];
2020-10-19 12:40:22 +00:00
}
2017-01-12 02:16:53 +00:00
}
2017-01-12 20:46:40 +00:00
else
{
2020-10-15 13:06:57 +00:00
return content;
2017-01-12 20:46:40 +00:00
}
}
}
2020-10-15 13:06:57 +00:00
}