#region License // Copyright 2005-2019 Paul Kohler (https://github.com/paulkohler/minisqlquery). All rights reserved. // This source code is made available under the terms of the GNU Lesser General Public License v3.0 // https://github.com/paulkohler/minisqlquery/blob/master/LICENSE #endregion using System.Collections.Generic; using System.IO; namespace MiniSqlQuery.Core { /// /// Given a file name or extention the service will work out the most appropriate editor to use. /// /// /// The editors need to be registered using the method. /// /// /// IEditor editor = resolver.ResolveEditorInstance("c:\data.sql"); /// // will resolve to the SQL editor /// /// IEditor editor = resolver.ResolveEditorInstance("c:\foo.txt"); /// // will resolve to the basic text editor /// /// public class FileEditorResolverService : IFileEditorResolver { /// /// The extention map of files types to descriptors. /// private readonly Dictionary _extentionMap; /// /// The file editor descriptors. /// private readonly List _fileEditorDescriptors; /// /// The application services. /// private readonly IApplicationServices _services; /// /// Initializes a new instance of the class. /// /// The application services. public FileEditorResolverService(IApplicationServices services) { _services = services; _extentionMap = new Dictionary(); _fileEditorDescriptors = new List(); } /// /// Gets an array of the file descriptiors. /// /// An array of objects. public FileEditorDescriptor[] GetFileTypes() { return _fileEditorDescriptors.ToArray(); } /// /// Registers the specified file editor descriptor. /// It is recommended to use the method to /// set up the container correctly. /// /// The file editor descriptor. public void Register(FileEditorDescriptor fileEditorDescriptor) { _fileEditorDescriptors.Add(fileEditorDescriptor); if (fileEditorDescriptor.Extensions == null || fileEditorDescriptor.Extensions.Length == 0) { _extentionMap.Add("*", fileEditorDescriptor); } else { // create a map of all ext to editors foreach (string extention in fileEditorDescriptor.Extensions) { _extentionMap.Add(extention, fileEditorDescriptor); } } } /// /// Resolves the editor instance from the container based on the filename. /// /// The filename. /// An editor. public IEditor ResolveEditorInstance(string filename) { string ext = Path.GetExtension(filename); string editorName = ResolveEditorNameByExtension(ext); return _services.Resolve(editorName); } /// /// Works out the "name" of the editor to use based on the . /// /// The extention ("sql", "txt"/".txt" etc). /// The name of an editor in the container. public string ResolveEditorNameByExtension(string extension) { string editorName = _extentionMap["*"].EditorKeyName; if (extension != null) { if (extension.StartsWith(".")) { extension = extension.Substring(1); } // is there a specific editor for this file type if (_extentionMap.ContainsKey(extension)) { editorName = _extentionMap[extension].EditorKeyName; } } return editorName; } } }