Source

Resharper Spell Checker / ReSpeller / SpellEngine / SpellChecker.cs

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using JetBrains.Application;
using JetBrains.Application.Settings;
using ReSpeller.Settings;
using ReSpeller.SpellEngine.Dictionaries;

namespace ReSpeller.SpellEngine
{
  [ShellComponent]
  public sealed class SpellChecker : IDisposable, ISpellChecker
  {
    private readonly IContextBoundSettingsStore myStore;
    private const string CurrentLanguage = "en_us";

    private readonly UserInternalDictionary myDictionary;
    private readonly string myPluginPath = Path.GetDirectoryName(Assembly.GetAssembly(typeof (ISpellChecker)).Location);
    private volatile object mySync = new object();
    private readonly ConfigurableWordChecker myWordChecker;
    private readonly IWordSuggestor myWordSuggestor;

    public SpellChecker(ISettingsStore store)
    {
      myStore = store.BindToContextTransient(ContextRange.ApplicationWide);      
      HunspellEngine.NativeDllPath = myPluginPath;
      string mainDictDir = Path.Combine(myPluginPath, Constants.MainDictSubDir);
      string userDictDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), Constants.UserDictSubDir);
      var userStorage = new FileDictionaryStorage(Path.Combine(userDictDir, CurrentLanguage + "." + Constants.DictExt));
      var internalStorage = new FileDictionaryStorage(Path.Combine(mainDictDir, CurrentLanguage + Constants.InternalDictSuffix + "." + Constants.DictExt));
      HunspellEngine hunspellEngine = HunspellEngine.CreateForLanguage(mainDictDir, CurrentLanguage);
      myDictionary = new UserInternalDictionary(hunspellEngine, CurrentLanguage, userStorage, internalStorage);
      myWordChecker = new ConfigurableWordChecker(new List<ILanguageDictionary> {myDictionary});
      myWordSuggestor = new SingleDictionarySuggestor(myDictionary);
    }

    #region IDisposable Members

    public void Dispose()
    {
      myDictionary.Dispose();
    }

    #endregion

    public bool CheckWordSpelling(string word)
    {     
      lock (mySync)
      {
        return myWordChecker.Check(word);
      }
    }

    public List<string> Suggestions(string word)
    {
      lock (mySync)
      {
        return myWordSuggestor.Suggest(word);
      }
    }

    public void AddWordToUserDict(string word)
    {
      lock (mySync)
      {
        myDictionary.AddToUserDict(word);
      }
    }

    public void AddWordToCustomDict(string word)
    {
      lock (mySync)
      {
        myDictionary.AddToInternalDict(word);
      }
    }

    public void UpdateConfig()
    {
      var settings = myStore.GetKey<ReSpellerSettings>(SettingsOptimization.DoMeSlowly);
      myWordChecker.Config.MinWordLength = settings.MinWordLength;
      myWordChecker.Config.SplitInPairs = settings.SplitInPairs;
    }
  }
}