diff --git a/GreenshotPlugin/Controls/GreenshotComboBox.cs b/GreenshotPlugin/Controls/GreenshotComboBox.cs index 39054204c..746a057b4 100644 --- a/GreenshotPlugin/Controls/GreenshotComboBox.cs +++ b/GreenshotPlugin/Controls/GreenshotComboBox.cs @@ -25,6 +25,8 @@ using GreenshotPlugin.Core; namespace GreenshotPlugin.Controls { public class GreenshotComboBox : ComboBox, IGreenshotConfigBindable { + private Type enumType = null; + private Enum selectedEnum = null; private string sectionName = "Core"; [Category("Greenshot"), DefaultValue("Core"), Description("Specifies the Ini-Section to map this control with.")] public string SectionName { @@ -42,41 +44,51 @@ namespace GreenshotPlugin.Controls { set; } - /// - /// This is a method to popululate the ComboBox - /// with the items from the enumeration - /// - /// TEnum to populate with - public void Populate(ILanguage language, Type enumType, object currentValue) { - var availableValues = Enum.GetValues(enumType); - this.Items.Clear(); - string enumTypeName = enumType.Name; - foreach (var enumValue in availableValues) { - string enumKey = enumTypeName + "." + enumValue.ToString(); - if (language.hasKey(enumKey)) { - string translation = language.GetString(enumKey); - this.Items.Add(translation); - } else { - this.Items.Add(enumValue.ToString()); - } - } + public GreenshotComboBox() { + this.SelectedIndexChanged += delegate { + StoreSelectedEnum(); + }; + } + + public void SetValue(Enum currentValue) { if (currentValue != null) { - string selectedEnumKey = enumTypeName + "." + currentValue.ToString(); - if (language.hasKey(selectedEnumKey)) { - this.SelectedItem = language.GetString(selectedEnumKey); + selectedEnum = currentValue; + string selectedEnumKey = enumType.Name + "." + currentValue.ToString(); + if (Language.hasKey(selectedEnumKey)) { + this.SelectedItem = Language.GetString(selectedEnumKey); } else { this.SelectedItem = currentValue.ToString(); } } } + /// + /// This is a method to popululate the ComboBox + /// with the items from the enumeration + /// + /// TEnum to populate with + public void Populate(Type enumType) { + // Store the enum-type, so we can work with it + this.enumType = enumType; + + var availableValues = Enum.GetValues(enumType); + this.Items.Clear(); + string enumTypeName = enumType.Name; + foreach (var enumValue in availableValues) { + string enumKey = enumTypeName + "." + enumValue.ToString(); + if (Language.hasKey(enumKey)) { + string translation = Language.GetString(enumKey); + this.Items.Add(translation); + } else { + this.Items.Add(enumValue.ToString()); + } + } + } /// - /// Get the selected enum value from the combobox, uses generics + /// Store the selected value internally /// - /// Combobox to get the value from - /// The generics value of the combobox - public object GetSelectedEnum(ILanguage language, Type enumType) { + private void StoreSelectedEnum() { string enumTypeName = enumType.Name; string selectedValue = this.SelectedItem as string; var availableValues = Enum.GetValues(enumType); @@ -84,20 +96,27 @@ namespace GreenshotPlugin.Controls { try { returnValue = Enum.Parse(enumType, selectedValue); - return returnValue; } catch (Exception) { } foreach (Enum enumValue in availableValues) { string enumKey = enumTypeName + "." + enumValue.ToString(); - if (language.hasKey(enumKey)) { - string translation = language.GetString(enumTypeName + "." + enumValue.ToString()); + if (Language.hasKey(enumKey)) { + string translation = Language.GetString(enumTypeName + "." + enumValue.ToString()); if (translation.Equals(selectedValue)) { - return enumValue; + returnValue = enumValue; } } } - return returnValue; + selectedEnum = (Enum)returnValue; + } + + /// + /// Get the selected enum value from the combobox, uses generics + /// + /// The enum value of the combobox + public Enum GetSelectedEnum() { + return selectedEnum; } } } diff --git a/GreenshotPlugin/Controls/GreenshotForm.cs b/GreenshotPlugin/Controls/GreenshotForm.cs index 3c61b8f2b..51f9a7919 100644 --- a/GreenshotPlugin/Controls/GreenshotForm.cs +++ b/GreenshotPlugin/Controls/GreenshotForm.cs @@ -12,43 +12,66 @@ using System.IO; namespace GreenshotPlugin.Controls { public abstract class GreenshotForm : Form, IGreenshotLanguageBindable { private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(GreenshotForm)); - protected ILanguage language; private IComponentChangeService m_changeService; - + private bool isLanguageSet = false; + private IDictionary designTimeControls; [Category("Greenshot"), DefaultValue(null), Description("Specifies key of the language file to use when displaying the text.")] public string LanguageKey { get; set; } - protected abstract string LanguagePattern { get; } - + /// + /// Code to initialize the language etc during design time + /// protected void InitializeForDesigner() { - if (language == null && this.DesignMode) { + if (this.DesignMode) { + designTimeControls = new Dictionary(); try { - if (!IniConfig.IsInited) { - IniConfig.Init("greenshot", "greenshot"); - } - ITypeResolutionService typeResService = GetService(typeof(ITypeResolutionService)) as ITypeResolutionService; Assembly currentAssembly = this.GetType().Assembly; string assemblyPath = typeResService.GetPathOfAssembly(currentAssembly.GetName()); - string designTimeLanguagePath = Path.Combine(Path.GetDirectoryName(assemblyPath), "../../Languages/"); - language = new LanguageContainer(LanguagePattern, designTimeLanguagePath); + string designTimeLanguagePath = Path.Combine(Path.GetDirectoryName(assemblyPath), "../../../Greenshot/Languages/"); + string designTimePluginLanguagePath = Path.Combine(Path.GetDirectoryName(assemblyPath), "../../Languages/"); + //MessageBox.Show(designTimeLanguagePath); + Language.AddLanguageFilePath(designTimeLanguagePath); + Language.AddLanguageFilePath(designTimePluginLanguagePath); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } } } + /// + /// This override is only for the design-time of the form + /// + /// + protected override void OnPaint(PaintEventArgs e) { + if (this.DesignMode) { + LOG.InfoFormat("OnPaint called from designer. Key={0}", LanguageKey); + if (!isLanguageSet) { + isLanguageSet = true; + try { + ApplyLanguage(); + } catch (Exception ex) { + MessageBox.Show(ex.ToString()); + } + } + } + base.OnPaint(e); + } + protected override void OnLoad(EventArgs e) { if (!this.DesignMode) { ApplyLanguage(); FillFields(); + base.OnLoad(e); } else { + LOG.Info("OnLoad called from designer."); InitializeForDesigner(); + base.OnLoad(e); + ApplyLanguage(); } - base.OnLoad(e); } /// @@ -65,8 +88,10 @@ namespace GreenshotPlugin.Controls { base.OnClosed(e); } - // This override allows the control to register event handlers for IComponentChangeService events - // at the time the control is sited, which happens only in design mode. + /// + /// This override allows the control to register event handlers for IComponentChangeService events + /// at the time the control is sited, which happens only in design mode. + /// public override ISite Site { get { return base.Site; @@ -93,6 +118,7 @@ namespace GreenshotPlugin.Controls { // Clear our the component change events to prepare for re-siting. if (m_changeService != null) { m_changeService.ComponentChanged -= new ComponentChangedEventHandler(OnComponentChanged); + m_changeService.ComponentAdded -= new ComponentEventHandler(OnComponentAdded); } } @@ -100,19 +126,37 @@ namespace GreenshotPlugin.Controls { // Register the event handlers for the IComponentChangeService events if (m_changeService != null) { m_changeService.ComponentChanged += new ComponentChangedEventHandler(OnComponentChanged); + m_changeService.ComponentAdded += new ComponentEventHandler(OnComponentAdded); } } - /* This method handles the OnComponentChanged event to display a notification. */ + /// + /// This method handles the OnComponentChanged event to display a notification. + /// + /// + /// private void OnComponentChanged(object sender, ComponentChangedEventArgs ce) { if (ce.Component != null && ((IComponent)ce.Component).Site != null && ce.Member != null) { - //OnUserChange("The " + ce.Member.Name + " member of the " + ((IComponent)ce.Component).Site.Name + " component has been changed."); if ("LanguageKey".Equals(ce.Member.Name)) { ApplyLanguage(ce.Component as Control, (string)ce.NewValue); } } } + private void OnComponentAdded(object sender, ComponentEventArgs ce) { + if (ce.Component != null && ((IComponent)ce.Component).Site != null) { + Control control = ce.Component as Control; + if (control != null) { + LOG.DebugFormat("Control {0} added.", control.Name); + if (!designTimeControls.ContainsKey(control.Name)) { + designTimeControls.Add(control.Name, control); + } else { + designTimeControls[control.Name] = control; + } + } + } + } + // Clean up any resources being used. protected override void Dispose(bool disposing) { if (disposing) { @@ -121,53 +165,67 @@ namespace GreenshotPlugin.Controls { base.Dispose(disposing); } + protected void ApplyLanguage(Control applyTo) { + IGreenshotLanguageBindable languageBindable = applyTo as IGreenshotLanguageBindable; + if (languageBindable == null) { + LOG.DebugFormat("Not bindable: {0}", applyTo.Name); + return; + } + + string languageKey = languageBindable.LanguageKey; + LOG.DebugFormat("Found language key '{0}' configured on control '{1}'", languageKey, applyTo.Name); + // Apply language text to the control + ApplyLanguage(applyTo, languageKey); + // Repopulate the combox boxes + if (typeof(IGreenshotConfigBindable).IsAssignableFrom(applyTo.GetType())) { + if (typeof(GreenshotComboBox).IsAssignableFrom(applyTo.GetType())) { + IGreenshotConfigBindable configBindable = applyTo as IGreenshotConfigBindable; + if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { + IniSection section = IniConfig.GetIniSection(configBindable.SectionName); + if (section != null) { + GreenshotComboBox comboxBox = applyTo as GreenshotComboBox; + // Only update the language, so get the actual value and than repopulate + Enum currentValue = (Enum)comboxBox.GetSelectedEnum(); + comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType); + comboxBox.SetValue(currentValue); + } + } + } + } + } /// /// Apply all the language settings to the "Greenshot" Controls on this form /// protected void ApplyLanguage() { - if (language == null) { - MessageBox.Show("Language not set!! Please use 'language = Language.GetInstance()' in your form constructor!"); - return; - } + LOG.DebugFormat("Applying language, using key {0}", LanguageKey); // Set title of the form if (!string.IsNullOrEmpty(LanguageKey)) { - this.Text = language.GetString(LanguageKey); + this.Text = Language.GetString(LanguageKey); } // Reset the text values for all GreenshotControls - foreach (FieldInfo field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)) { + foreach (FieldInfo field in this.GetType().GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance)) { + LOG.DebugFormat("Checking field {0}", field.Name); if (!field.FieldType.IsSubclassOf(typeof(Control))) { + LOG.DebugFormat("No control: {0}", field.Name); continue; } Object controlObject = field.GetValue(this); if (controlObject == null) { + LOG.DebugFormat("No value: {0}", field.Name); continue; } Control applyTo = controlObject as Control; if (applyTo == null) { // not a control + LOG.DebugFormat("No control: {0}", field.Name); continue; } - IGreenshotLanguageBindable languageBindable = applyTo as IGreenshotLanguageBindable; - if (languageBindable == null) { - continue; - } - string languageKey = languageBindable.LanguageKey; - // Apply language text to the control - ApplyLanguage(applyTo, languageKey); - // Repopulate the combox boxes - if (typeof(IGreenshotConfigBindable).IsAssignableFrom(field.FieldType)) { - if (typeof(GreenshotComboBox).IsAssignableFrom(field.FieldType)) { - IGreenshotConfigBindable configBindable = controlObject as IGreenshotConfigBindable; - if (!string.IsNullOrEmpty(configBindable.SectionName) && !string.IsNullOrEmpty(configBindable.PropertyName)) { - IniSection section = IniConfig.GetIniSection(configBindable.SectionName); - if (section != null) { - GreenshotComboBox comboxBox = controlObject as GreenshotComboBox; - // Only update the language, so get the actual value and than repopulate - object currentValue = comboxBox.GetSelectedEnum(language, section.Values[configBindable.PropertyName].ValueType); - comboxBox.Populate(language, section.Values[configBindable.PropertyName].ValueType, currentValue); - } - } - } + ApplyLanguage(applyTo); + } + + if (DesignMode) { + foreach (Control designControl in designTimeControls.Values) { + ApplyLanguage(designControl); } } } @@ -177,13 +235,18 @@ namespace GreenshotPlugin.Controls { /// protected void ApplyLanguage(Control applyTo, string languageKey) { if (!string.IsNullOrEmpty(languageKey)) { - if (!language.hasKey(languageKey)) { + if (!Language.hasKey(languageKey)) { + LOG.WarnFormat("Wrong language key '{0}' configured for control '{1}'", languageKey, applyTo.Name); MessageBox.Show(string.Format("Wrong language key '{0}' configured for control '{1}'", languageKey, applyTo.Name)); return; } - applyTo.Text = language.GetString(languageKey); + applyTo.Text = Language.GetString(languageKey); } else { - MessageBox.Show(string.Format("Greenshot control without language key: {0}", applyTo.Name)); + if (this.DesignMode) { + MessageBox.Show(string.Format("Greenshot control without language key: {0}", applyTo.Name)); + } else { + LOG.DebugFormat("Greenshot control without language key: {0}", applyTo.Name); + } } } @@ -213,7 +276,8 @@ namespace GreenshotPlugin.Controls { textBox.Text = (string)section.Values[configBindable.PropertyName].Value; } else if (typeof(GreenshotComboBox).IsAssignableFrom(field.FieldType)) { GreenshotComboBox comboxBox = controlObject as GreenshotComboBox; - comboxBox.Populate(language, section.Values[configBindable.PropertyName].ValueType, (Enum)section.Values[configBindable.PropertyName].Value); + comboxBox.Populate(section.Values[configBindable.PropertyName].ValueType); + comboxBox.SetValue((Enum)section.Values[configBindable.PropertyName].Value); } } } @@ -253,7 +317,7 @@ namespace GreenshotPlugin.Controls { iniDirty = true; } else if (typeof(GreenshotComboBox).IsAssignableFrom(field.FieldType)) { GreenshotComboBox comboxBox = controlObject as GreenshotComboBox; - section.Values[configBindable.PropertyName].Value = comboxBox.GetSelectedEnum(language, section.Values[configBindable.PropertyName].ValueType); + section.Values[configBindable.PropertyName].Value = comboxBox.GetSelectedEnum(); } } } diff --git a/GreenshotPlugin/Core/Language.cs b/GreenshotPlugin/Core/Language.cs new file mode 100644 index 000000000..8afc67f0b --- /dev/null +++ b/GreenshotPlugin/Core/Language.cs @@ -0,0 +1,472 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.IO; +using System.Reflection; +using Microsoft.Win32; +using System.Xml; +using Greenshot.IniFile; +using System.Text.RegularExpressions; + +namespace GreenshotPlugin.Core { + public class LanguageFile : IEquatable { + public string Description { + get; + set; + } + + public string Ietf { + get; + set; + } + + public Version Version { + get; + set; + } + + public string LanguageGroup { + get; + set; + } + + public string Filepath { + get; + set; + } + + public string Prefix { + get; + set; + } + + public bool Equals(LanguageFile other) { + if (Prefix != null) { + if (!Prefix.Equals(other.Prefix)) { + return false; + } + } else if (other.Prefix != null) { + return false; + } + if (Ietf != null) { + if (!Ietf.Equals(other.Ietf)) { + return false; + } + } else if (other.Ietf != null) { + return false; + } + if (Version != null) { + if (!Version.Equals(other.Version)) { + return false; + } + } else if (other.Version != null) { + return false; + } + if (Filepath != null) { + if (!Filepath.Equals(other.Filepath)) { + return false; + } + } else if (other.Filepath != null) { + return false; + } + return true; + } + } + + class HelpFile { + public string Ietf { + get; + set; + } + + public string Filepath { + get; + set; + } + } + + public class Language { + private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(Language)); + private static List languagePaths = new List(); + private static IDictionary> languageFiles = new Dictionary>(); + private static IDictionary helpFiles = new Dictionary(); + private const string DEFAULT_LANGUAGE = "en-US"; + private const string HELP_FILENAME_PATTERN = @"help-*.html"; + private const string LANGUAGE_FILENAME_PATTERN = @"language*.xml"; + private static Regex PREFIX_REGEXP = new Regex(@"language_([a-zA-Z0-9]+).*"); + private const string LANGUAGE_GROUPS_KEY = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; + private static List unsupportedLanguageGroups = new List(); + private static IDictionary resources = new Dictionary(); + private static string currentLanguage = null; + private static CoreConfiguration coreConfig = null; + + static Language() { + if (!LogHelper.isInitialized) { + LOG.Warn("Log4net hasn't been initialized yet! (Design mode?)"); + LogHelper.InitializeLog4NET(); + } + if (!IniConfig.IsInited) { + LOG.Warn("IniConfig hasn't been initialized yet! (Design mode?)"); + IniConfig.Init("greenshot", "greenshot"); + } + string applicationDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); + string applicationFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); + + // PAF Path + AddPath(Path.Combine(applicationFolder, @"App\Greenshot\Languages")); + + // Application data path + AddPath(Path.Combine(applicationDataFolder, @"Greenshot\Languages\")); + + // Startup path + AddPath(Path.Combine(applicationFolder, @"Languages")); + + try { + using (RegistryKey languageGroupsKey = Registry.LocalMachine.OpenSubKey(LANGUAGE_GROUPS_KEY, false)) { + if (languageGroupsKey != null) { + string [] groups = languageGroupsKey.GetValueNames(); + foreach(string group in groups) { + string groupValue = (string)languageGroupsKey.GetValue(group); + bool isGroupNotInstalled = "0".Equals(groupValue); + if (isGroupNotInstalled) { + unsupportedLanguageGroups.Add(group.ToLower()); + } + } + } + } + } catch(Exception e) { + LOG.Warn("Couldn't read the installed language groups.", e); + } + + coreConfig = IniConfig.GetIniSection(); + ScanFiles(); + if (!string.IsNullOrEmpty(coreConfig.Language)) { + currentLanguage = coreConfig.Language; + } else { + currentLanguage = DEFAULT_LANGUAGE; + } + Reload(); + } + + private static void AddPath(string path) { + if (!languagePaths.Contains(path)) { + if (Directory.Exists(path)) { + LOG.DebugFormat("Adding language path {0}", path); + languagePaths.Add(path); + } else { + LOG.InfoFormat("Not adding non existing language path {0}", path); + } + } + } + + public static void AddLanguageFilePath(string path) { + if (!languagePaths.Contains(path)) { + LOG.DebugFormat("New language path {0}", path); + AddPath(path); + ScanFiles(); + Reload(); + } + } + + private static void LoadFiles(string ietf) { + if (!languageFiles.ContainsKey(ietf)) { + LOG.ErrorFormat("No language {0} available.", ietf); + return; + } + List filesToLoad = languageFiles[ietf]; + foreach (LanguageFile fileToLoad in filesToLoad) { + LoadResources(fileToLoad); + } + } + + private static void Reload() { + resources.Clear(); + LoadFiles(DEFAULT_LANGUAGE); + if (currentLanguage != null && !currentLanguage.Equals(DEFAULT_LANGUAGE)) { + LoadFiles(currentLanguage); + } + } + + public static string CurrentLanguage { + get { + return currentLanguage; + } + set { + LOG.DebugFormat("CurrentLangue = {0}", value); + // Change the resources, if we can find the wanted value + if (!string.IsNullOrEmpty(value) && currentLanguage == null || (currentLanguage != null && !currentLanguage.Equals(value))) { + currentLanguage = value; + } + Reload(); + } + } + + public static string LanguageName(string ietf) { + return languageFiles[ietf][0].Description; + } + + public static IList SupportedLanguages { + get { + IList languages = new List(); + foreach (List langs in languageFiles.Values) { + foreach (LanguageFile langFile in langs) { + if (langFile.Prefix == null) { + languages.Add(langFile); + break; + } + } + } + return languages; + } + } + public static string HelpFilePath { + get { + if (helpFiles.ContainsKey(currentLanguage)) { + return helpFiles[currentLanguage].Filepath; + } + return helpFiles[DEFAULT_LANGUAGE].Filepath; + } + } + + /// + /// Load the resources from the language file + /// + /// File to load from + private static void LoadResources(LanguageFile languageFile) { + LOG.InfoFormat("Loading language file {0}", languageFile.Filepath); + try { + XmlDocument xmlDocument = new XmlDocument(); + xmlDocument.Load(languageFile.Filepath); + XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource"); + foreach (XmlNode resourceNode in resourceNodes) { + string key = resourceNode.Attributes["name"].Value; + if (!string.IsNullOrEmpty(languageFile.Prefix)) { + key = languageFile.Prefix + "." + key; + } + string text = resourceNode.InnerText; + if (!string.IsNullOrEmpty(text)) { + text = text.Trim(); + } + if (!resources.ContainsKey(key)) { + resources.Add(key, text); + } else { + resources[key] = text; + } + } + } catch (Exception e) { + LOG.Error("Could not load language file " + languageFile.Filepath, e); + } + } + + /// + /// Load the language file information + /// + /// + /// + private static LanguageFile LoadFileInfo(string languageFilePath) { + try { + XmlDocument xmlDocument = new XmlDocument(); + xmlDocument.Load(languageFilePath); + XmlNodeList nodes = xmlDocument.GetElementsByTagName("language"); + if (nodes.Count > 0) { + LanguageFile languageFile = new LanguageFile(); + languageFile.Filepath = languageFilePath; + XmlNode node = nodes.Item(0); + languageFile.Description = node.Attributes["description"].Value; + languageFile.Ietf = node.Attributes["ietf"].Value; + if (node.Attributes["version"] != null) { + languageFile.Version = new Version(node.Attributes["version"].Value); + } + if (node.Attributes["prefix"] != null) { + languageFile.Prefix = node.Attributes["prefix"].Value; + } + if (node.Attributes["languagegroup"] != null) { + string languageGroup = node.Attributes["languagegroup"].Value; + languageFile.LanguageGroup = languageGroup.ToLower(); + } + return languageFile; + } else { + throw new XmlException("Root element is missing"); + } + } catch (Exception e) { + LOG.Error("Could not load language file " + languageFilePath, e); + } + return null; + } + + /// + /// Scan the files in all directories + /// + private static void ScanFiles() { + languageFiles.Clear(); + helpFiles.Clear(); + foreach (string languagePath in languagePaths) { + if (!Directory.Exists(languagePath)) { + LOG.InfoFormat("Skipping non existing language path {0}", languagePath); + continue; + } + LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", languagePath, LANGUAGE_FILENAME_PATTERN); + try { + foreach (string languageFilepath in Directory.GetFiles(languagePath, LANGUAGE_FILENAME_PATTERN, SearchOption.AllDirectories)) { + LOG.DebugFormat("Found language file: {0}", languageFilepath); + LanguageFile languageFile = LoadFileInfo(languageFilepath); + if (languageFile != null) { + // build prefix + if (string.IsNullOrEmpty(languageFile.Prefix)) { + string languageFilename = Path.GetFileNameWithoutExtension(languageFilepath); + if (PREFIX_REGEXP.IsMatch(languageFilename)) { + languageFile.Prefix = PREFIX_REGEXP.Replace(languageFilename, "$1"); + if (!string.IsNullOrEmpty(languageFile.Prefix)) { + languageFile.Prefix = languageFile.Prefix.Replace("plugin", ""); + } + } + } + if (string.IsNullOrEmpty(languageFile.LanguageGroup) || !unsupportedLanguageGroups.Contains(languageFile.LanguageGroup)) { + List currentFiles = null; + if (languageFiles.ContainsKey(languageFile.Ietf)) { + currentFiles = languageFiles[languageFile.Ietf]; + bool needToAdd = true; + List deleteList = new List(); + foreach (LanguageFile compareWithLangfile in currentFiles) { + if ((languageFile.Prefix == null && compareWithLangfile.Prefix == null) || (languageFile.Prefix != null && languageFile.Prefix.Equals(compareWithLangfile.Prefix))) { + if (compareWithLangfile.Version > languageFile.Version) { + LOG.WarnFormat("Skipping {0}:{1}:{2} as {3}:{4}:{5} is newer", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); + needToAdd = false; + break; + } else { + LOG.WarnFormat("Found {0}:{1}:{2} and deleting {3}:{4}:{5}", languageFile.Filepath, languageFile.Prefix, languageFile.Version, compareWithLangfile.Filepath, compareWithLangfile.Prefix, compareWithLangfile.Version); + deleteList.Add(compareWithLangfile); + } + } + } + if (needToAdd) { + foreach (LanguageFile deleteFile in deleteList) { + currentFiles.Remove(deleteFile); + } + LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath); + currentFiles.Add(languageFile); + } + } else { + currentFiles = new List(); + currentFiles.Add(languageFile); + languageFiles.Add(languageFile.Ietf, currentFiles); + LOG.InfoFormat("Added language {0} from: {1}", languageFile.Description, languageFile.Filepath); + } + } else { + LOG.InfoFormat("Skipping unsupported language: {0}", languageFile.Description); + } + } + } + } catch (DirectoryNotFoundException) { + LOG.InfoFormat("Non existing language directory: {0}", languagePath); + } catch (Exception e) { + LOG.Error("Error trying for read directory " + languagePath, e); + } + LOG.InfoFormat("Searching language directory '{0}' for help files with pattern '{1}'", languagePath, HELP_FILENAME_PATTERN); + try { + foreach (string helpFilepath in Directory.GetFiles(languagePath, HELP_FILENAME_PATTERN, SearchOption.AllDirectories)) { + LOG.DebugFormat("Found help file: {0}", helpFilepath); + HelpFile helpFile = new HelpFile(); + helpFile.Filepath = helpFilepath; + string helpFilename = Path.GetFileName(helpFilepath); + helpFile.Ietf = helpFilename.Replace(".html", "").Replace("help-", ""); + if (!helpFiles.ContainsKey(helpFile.Ietf)) { + helpFiles.Add(helpFile.Ietf, helpFile); + } else { + LOG.WarnFormat("skipping help file {0}, already a file with the same IETF found!", helpFilepath); + } + } + } catch (DirectoryNotFoundException) { + LOG.InfoFormat("Non existing language directory: {0}", languagePath); + } catch (Exception e) { + LOG.Error("Error trying for read directory " + languagePath, e); + } + } + } + + public static string Dump() { + int max = 40; + StringBuilder dump = new StringBuilder(); + foreach (string key in resources.Keys) { + dump.AppendFormat("{0}={1}", key, resources[key]).AppendLine(); + if (max-- == 0) { + break; + } + } + return dump.ToString(); + } + public static bool hasKey(string prefix, Enum key) { + if (key == null) { + return false; + } + return hasKey(prefix + "." + key.ToString()); + } + + public static bool hasKey(Enum key) { + if (key == null) { + return false; + } + return hasKey(key.ToString()); + } + + public static bool hasKey(string prefix, string key) { + return hasKey(prefix + "." + key); + } + + public static bool hasKey(string key) { + if (key == null) { + return false; + } + return resources.ContainsKey(key); + } + + public static string GetString(Enum key) { + if (key == null) { + return null; + } + return GetString(key.ToString()); + } + + public static string GetString(string prefix, Enum key) { + if (key == null) { + return null; + } + return GetString(prefix + "." + key.ToString()); + } + + public static string GetString(string prefix, string key) { + return GetString(prefix + "." + key); + } + + public static string GetString(string key) { + if (key == null) { + return null; + } + string returnValue; + if (!resources.TryGetValue(key, out returnValue)) { + return "string ###" + key + "### not found"; + } + return returnValue; + } + + public static string GetFormattedString(Enum key, object param) { + return GetFormattedString(key.ToString(), param); + } + + public static string GetFormattedString(string prefix, Enum key, object param) { + return GetFormattedString(prefix, key.ToString(), param); + } + + public static string GetFormattedString(string prefix, string key, object param) { + return GetFormattedString(prefix + "." + key, param); + } + + public static string GetFormattedString(string key, object param) { + string returnValue; + if (!resources.TryGetValue(key, out returnValue)) { + return "string ###" + key + "### not found"; + } + return String.Format(returnValue, param); ; + } + } +} diff --git a/GreenshotPlugin/Core/LanguageHelper.cs b/GreenshotPlugin/Core/LanguageHelper.cs deleted file mode 100644 index 93de4faeb..000000000 --- a/GreenshotPlugin/Core/LanguageHelper.cs +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Greenshot - a free and open source screenshot tool - * Copyright (C) 2007-2012 Thomas Braun, Jens Klingen, Robin Krom - * - * For more information see: http://getgreenshot.org/ - * The Greenshot project is hosted on Sourceforge: http://sourceforge.net/projects/greenshot/ - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 1 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -using System; -using System.Collections.Generic; -using System.Globalization; -using System.IO; -using System.Reflection; -using System.Text; -using System.Threading; -using System.Xml; - -using Greenshot.IniFile; -using Microsoft.Win32; - -namespace GreenshotPlugin.Core { - - public interface ILanguage { - void Load(); - bool hasKey(Enum key); - bool hasKey(string key); - string GetString(Enum id); - string GetString(string id); - string GetFormattedString(Enum id, object param); - string GetFormattedString(string id, object param); - string GetHelpFilePath(); - - void FreeResources(); - - string CurrentLanguage { - get; - } - - List SupportedLanguages { - get; - } - - String LanguageFilePattern { - get; - set; - } - - LanguageConfiguration CurrentLanguageConfiguration { - get; - } - } - /// - /// Description of Language. - /// - public class LanguageContainer : ILanguage { - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(LanguageContainer)); - private static char [] TRIMCHARS = new char[] {' ', '\t', '\n', '\r'}; - private const string DEFAULT_LANGUAGE= "en-US"; - private static string APPLICATIONDATA_LANGUAGE_PATH = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),@"Greenshot\Languages\"); - private static string APPLICATION_PATH = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); - private static string STARTUP_LANGUAGE_PATH = Path.Combine(APPLICATION_PATH, @"Languages"); - private static string PAF_LANGUAGE_PATH = Path.Combine(APPLICATION_PATH, @"App\Greenshot\Languages"); - private const string HELP_FILENAME_PATTERN = @"help-*.html"; - private const string LANGUAGE_GROUPS_KEY = @"SYSTEM\CurrentControlSet\Control\Nls\Language Groups"; - private static string globalLanguage = DEFAULT_LANGUAGE; - private string additionalPath = null; // Set if the designer is used - - private Dictionary strings = new Dictionary(); - private List languages = new List(); - private string currentIETF = null; - private string languageFilePattern; - private static List supportedLanguageGroups = new List(); - private static List instances = new List(); - - static LanguageContainer() { - try { - using (RegistryKey languageGroupsKey = Registry.LocalMachine.OpenSubKey(LANGUAGE_GROUPS_KEY, false)) { - if (languageGroupsKey != null) { - string [] groups = languageGroupsKey.GetValueNames(); - foreach(string group in groups) { - string groupValue = (string)languageGroupsKey.GetValue(group); - bool isGroupInstalled = "1".Equals(groupValue); - if (isGroupInstalled) { - supportedLanguageGroups.Add(group.ToLower()); - } - } - } - } - } catch(Exception e) { - LOG.Warn("Couldn't read the installed language groups.", e); - } - } - - public LanguageContainer() { - instances.Add(this); - } - - public LanguageContainer(string filePattern) : this(filePattern, null) { - } - - public LanguageContainer(string filePattern, string additionalPath) { - this.additionalPath = additionalPath; - LanguageFilePattern = filePattern; - Load(); - SetInstanceLanguage(globalLanguage); - } - - public String LanguageFilePattern { - get { - return languageFilePattern; - } - set { - languageFilePattern = value; - } - } - - public void Load() { - languages = LoadFiles(languageFilePattern); - } - - public string CurrentLanguage { - get { - return currentIETF; - } - } - - public List SupportedLanguages { - get { - return languages; - } - } - - public LanguageConfiguration CurrentLanguageConfiguration { - get { - foreach(LanguageConfiguration languageConfiguration in SupportedLanguages) { - if (currentIETF.Equals(languageConfiguration.Ietf)) { - return languageConfiguration; - } - } - return null; - } - } - - public static void SynchronizeLanguageToCulture() { - if (globalLanguage == null || !globalLanguage.Equals(Thread.CurrentThread.CurrentUICulture.Name)) { - SetGlobalLanguage(Thread.CurrentThread.CurrentUICulture.Name); - } - } - - public static void SetGlobalLanguage(string wantedIETF) { - globalLanguage = wantedIETF; - foreach (LanguageContainer langInstance in instances) { - langInstance.SetInstanceLanguage(wantedIETF); - } - } - - /// - /// Set language - /// - /// wanted IETF - /// Actuall IETF - public string SetInstanceLanguage(string wantedIETF) { - LOG.Debug("SetLanguage called for : " + wantedIETF); - Dictionary identifiedLanguages = new Dictionary(); - - if (languages == null || languages.Count == 0) { - throw new FileNotFoundException(string.Format("No language files for {0} found!", wantedIETF)); - } - - // Find selected languages in available languages - foreach(LanguageConfiguration language in languages) { - LOG.Debug("Found language: " + language.Ietf); - if (!identifiedLanguages.ContainsKey(language.Ietf)) { - identifiedLanguages.Add(language.Ietf, language); - } else { - LOG.WarnFormat("Found double language file: {0}", language.File); - } - } - - LanguageConfiguration selectedLanguage = null; - if (identifiedLanguages.ContainsKey(wantedIETF)) { - selectedLanguage = identifiedLanguages[wantedIETF]; - } else { - LOG.Warn("Selecteded language " + wantedIETF + " not found."); - } - - // Make best match for language (e.g. en -> "en-US") - if (selectedLanguage == null) { - foreach(string ietf in identifiedLanguages.Keys) { - if (ietf.StartsWith(wantedIETF)) { - if (identifiedLanguages.ContainsKey(ietf)) { - selectedLanguage = identifiedLanguages[ietf]; - LOG.Info("Selecteded language " + ietf + " by near match for: " + wantedIETF); - wantedIETF = ietf; - break; - } else { - LOG.Warn("Selecteded language " + wantedIETF + " not found."); - } - } - } - } - - if (selectedLanguage == null && !DEFAULT_LANGUAGE.Equals(wantedIETF)) { - if (identifiedLanguages.ContainsKey(DEFAULT_LANGUAGE)) { - selectedLanguage = identifiedLanguages[DEFAULT_LANGUAGE]; - } else { - LOG.Warn("No english language file found!!"); - } - } - if (selectedLanguage == null) { - // Select first (maybe only) language! - selectedLanguage = languages[0]; - LOG.Warn("Selected " + selectedLanguage.Ietf + " as fallback language!"); - } - - // build directionary for the strings - strings.Clear(); - foreach(Resource resource in selectedLanguage.Resources) { - AddResource(resource); - } - - // Make sure we have all the missing resources, right after setting the language - // this way we can free all other resources. - AdoptMissingResourcesFromDefaultLanguage(); - - currentIETF = selectedLanguage.Ietf; - Thread.CurrentThread.CurrentUICulture = new CultureInfo(currentIETF); - - return currentIETF; - } - - /// - /// Free all language resources which aren't needed - /// - public void FreeResources() { - languages = null; - } - - private void AddResource(Resource resource) { - try { - if (resource.Text != null) { - strings.Add(resource.Name, resource.Text.Trim(TRIMCHARS)); - } else { - LOG.Warn("Resource is null: " + resource.Name); - strings.Add(resource.Name, ""); - } - } catch (ArgumentException ae) { - LOG.Error("Problem adding " + resource.Name, ae); - throw ae; - } - } - - private List LoadFiles(string languageFilePattern) { - List loadedLanguages = new List(); - List languageDirectories = new List(); - if (IniConfig.IsPortable) { - languageDirectories.Add(PAF_LANGUAGE_PATH); - } else { - languageDirectories.Add(APPLICATIONDATA_LANGUAGE_PATH); - } - if (additionalPath != null) { - languageDirectories.Add(additionalPath); - } - languageDirectories.Add(STARTUP_LANGUAGE_PATH); - foreach(string path in languageDirectories) { - if (!Directory.Exists(path)) { - LOG.InfoFormat("Skipping non existing language path {0}", path); - continue; - } - // Search in executable directory - LOG.InfoFormat("Searching language directory '{0}' for language files with pattern '{1}'", path, languageFilePattern); - try { - foreach(string languageFile in Directory.GetFiles(path, languageFilePattern, SearchOption.AllDirectories)) { - LOG.DebugFormat("Found language file: {0}", languageFile); - LanguageConfiguration languageConfig = LanguageConfiguration.Load(languageFile); - if (languageConfig != null) { - if (string.IsNullOrEmpty(languageConfig.LanguageGroup) || supportedLanguageGroups.Contains(languageConfig.LanguageGroup)) { - LOG.InfoFormat("Loaded language: {0}", languageConfig.Description); - loadedLanguages.Add(languageConfig); - } else { - LOG.InfoFormat("Skipping unsupported language: {0}", languageConfig.Description); - } - } - } - } catch (DirectoryNotFoundException) { - LOG.InfoFormat("Non existing language directory: {0}", path); - } catch (Exception e) { - LOG.Error("Error trying for read directory " + path, e); - } - } - - if (loadedLanguages.Count == 0) { - // Try to force internal english - try { - LOG.Info("No languages found, using embedded en-US."); - using (Stream stream = Assembly.GetEntryAssembly().GetManifestResourceStream("Greenshot.Languages.language-en-US.xml")) { - LanguageConfiguration languageConfig = LanguageConfiguration.Load(stream); - if (languageConfig != null) { - loadedLanguages.Add(languageConfig); - } - } - } catch (Exception ie) { - LOG.Error("Can't read internal 'Greenshot.Languages.language-en-US.xml'", ie); - } - } - return loadedLanguages; - } - - public void Validate(Enum languageKeys) { - Dictionary> keysPerLanguage = new Dictionary>(); - foreach(LanguageConfiguration languageToValidate in languages) { - List keys = new List(); - foreach(Resource resource in languageToValidate.Resources) { - keys.Add(resource.Name); - } - keys.Sort(); - keysPerLanguage.Add(languageToValidate.Ietf, keys); - } - - // Make list of values in the enum - List fixedKeys = new List(); - foreach(Enum langKey in Enum.GetValues(languageKeys.GetType())) { - fixedKeys.Add(langKey.ToString()); - } - - foreach(string ietf in keysPerLanguage.Keys) { - List keys = keysPerLanguage[ietf]; - foreach(string key in fixedKeys) { - if (!keys.Contains(key)) { - LOG.Warn(ietf + " is missing resource with name [" + key + "]"); - } - } - foreach(string key in keys) { - if (!fixedKeys.Contains(key)) { - LOG.Warn(ietf + " has additional resource with name [" + key + "]"); - } - } - } - } - - private void ToEnum() { - if (!LOG.IsDebugEnabled) { - return; - } - StringBuilder EnumClass = new StringBuilder(); - EnumClass.AppendLine("/*"); - EnumClass.AppendLine(" * Auto generated"); - EnumClass.AppendLine(" */"); - EnumClass.AppendLine("using System;"); - EnumClass.AppendLine(); - EnumClass.AppendLine("namespace Greenshot.Configuration {"); - EnumClass.AppendLine(" public enum LangKey {"); - - List keys = new List(); - foreach(LanguageConfiguration foundLanguage in languages) { - if (foundLanguage.Ietf.Equals(DEFAULT_LANGUAGE)) { - foreach(Resource resource in foundLanguage.Resources) { - keys.Add(resource.Name); - } - } - } - keys.Sort(); - bool added = false; - foreach(string key in keys) { - if (added) { - EnumClass.AppendLine(","); - } - EnumClass.Append(" " + key); - added = true; - } - EnumClass.AppendLine(); - EnumClass.AppendLine(" }"); - EnumClass.AppendLine("}"); - LOG.Debug("LangKeys should be: \r\n" + EnumClass.ToString()); - } - - public bool hasKey(Enum key) { - if (key == null) { - return false; - } - return hasKey(key.ToString()); - } - - public bool hasKey(string key) { - if (key == null) { - return false; - } - return strings.ContainsKey(key); - } - - public string GetString(Enum key) { - if (key == null) { - return null; - } - return GetString(key.ToString()); - } - - public string GetString(string key) { - if (key == null) { - return null; - } - try { - return strings[key]; - } catch (KeyNotFoundException) { - return "string ###"+key+"### not found"; - } - } - - public string GetFormattedString(Enum key, object param) { - return GetFormattedString(key.ToString(), param); - } - - public string GetFormattedString(string key, object param) { - try { - return String.Format(strings[key], param); - } catch (KeyNotFoundException) { - return "string ###"+key+"### not found"; - } - } - - private void AdoptMissingResourcesFromDefaultLanguage() { - LanguageConfiguration defaultLanguageConfiguration = GetDefaultLanguageConfiguration(); - if (defaultLanguageConfiguration != null) { - foreach(Resource resource in defaultLanguageConfiguration.Resources) { - if(resource != null && !strings.ContainsKey(resource.Name)) { - AddResource(resource); - if(LOG.IsWarnEnabled) { - LOG.Warn("Adopted missing string resource from default language: "+resource.Name); - } - } - } - } else { - LOG.Warn("Default language file is missing! The default language file is: " + DEFAULT_LANGUAGE); - } - } - - private LanguageConfiguration GetDefaultLanguageConfiguration() { - foreach(LanguageConfiguration language in languages) { - if(language.Ietf == DEFAULT_LANGUAGE) return language; - } - return null; - } - - /// finds a returns the path of the best matching help file. - /// 1st tries to find file for currentLanguage, 2nd for defaultLanguage. - /// if neither is found, the first help file found is returned - public string GetHelpFilePath() { - List helpFiles = new List(); - // Search in executable directory - if (Directory.Exists(STARTUP_LANGUAGE_PATH)) { - helpFiles.AddRange(Directory.GetFiles(STARTUP_LANGUAGE_PATH, HELP_FILENAME_PATTERN, SearchOption.AllDirectories)); - } - // Search in ApplicationData directory - if (Directory.Exists(APPLICATIONDATA_LANGUAGE_PATH)) { - helpFiles.AddRange(Directory.GetFiles(APPLICATIONDATA_LANGUAGE_PATH, HELP_FILENAME_PATTERN, SearchOption.AllDirectories)); - } - - foreach(string helpFile in helpFiles) { - if(helpFile.EndsWith(currentIETF+".html")) { - return helpFile; - } - } - foreach(string helpFile in helpFiles) { - if(helpFile.EndsWith(DEFAULT_LANGUAGE+".html")) { - return helpFile; - } - } - LOG.Warn("Help file not found for default language, will load "+helpFiles[0]); - return helpFiles[0]; - } - - } - - public class LanguageConfiguration { - - private static log4net.ILog LOG = log4net.LogManager.GetLogger(typeof(LanguageConfiguration)); - - public string description; - public string Description { - get { - return description; - } - set { - description = value; - } - } - - public string ietf; - public string Ietf { - get { - return ietf; - } - set { - ietf = value; - } - } - - public string version; - public string Version { - get { - return version; - } - set { - version = value; - } - } - - public string languageGroup; - public string LanguageGroup { - get { - return languageGroup; - } - set { - languageGroup = value; - } - } - - public string file; - public string File { - get { - return file; - } - set { - file = value; - } - } - - public List Resources; - - public LanguageConfiguration() { - Resources = new List(); - } - - /// - /// loads a language configuration from a file path - /// - public static LanguageConfiguration Load(string path) { - LanguageConfiguration languageConfiguration = null; - try { - XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.Load(path); - languageConfiguration = ProcessXML(xmlDocument); - languageConfiguration.File = path; - } catch(Exception e) { - LOG.Error("Could not load language file "+path, e); - } - return languageConfiguration; - } - - /// - /// loads a language configuration from a stream - /// - public static LanguageConfiguration Load(Stream stream) { - LanguageConfiguration languageConfiguration = null; - try { - XmlDocument xmlDocument = new XmlDocument(); - xmlDocument.Load(stream); - languageConfiguration = ProcessXML(xmlDocument); - languageConfiguration.File = "internal"; - } catch(Exception e) { - LOG.Error("Could not load internal language file", e); - } - return languageConfiguration; - } - - private static LanguageConfiguration ProcessXML(XmlDocument xmlDocument) { - LanguageConfiguration languageConfiguration = null; - XmlNodeList nodes = xmlDocument.GetElementsByTagName("language"); - if(nodes.Count > 0) { - languageConfiguration = new LanguageConfiguration(); - XmlNode node = nodes.Item(0); - languageConfiguration.Description = node.Attributes["description"].Value; - languageConfiguration.Ietf = node.Attributes["ietf"].Value; - languageConfiguration.Version = node.Attributes["version"].Value; - if (node.Attributes["languagegroup"] != null) { - string languageGroup = node.Attributes["languagegroup"].Value; - languageConfiguration.LanguageGroup = languageGroup.ToLower(); - } - - XmlNodeList resourceNodes = xmlDocument.GetElementsByTagName("resource"); - languageConfiguration.Resources = new List(resourceNodes.Count); - foreach(XmlNode resourceNode in resourceNodes) { - Resource res = new Resource(); - res.Name = resourceNode.Attributes["name"].Value; - res.Text = resourceNode.InnerText; - languageConfiguration.Resources.Add(res); - } - } else { - throw new XmlException("Root element is missing"); - } - return languageConfiguration; - } - } - - public class Resource { - - public string name; - public string Name {get; set;} - - public string text; - public string Text {get; set;} - - public override int GetHashCode() { - int hash = 7; - if (Text != null) { - hash = hash ^ Text.GetHashCode(); - } - if (Name != null) { - hash = hash ^ Name.GetHashCode(); - } - return hash; - } - - public override bool Equals(object obj) { - if (obj == null) { - return false; - } - if (obj is Resource) { - Resource other = (Resource) obj; - if(Name == null) { - if (other.Name != null) { - return false; - } - return true; - } - if(Text == null) { - if (other.Text != null) { - return false; - } - return true; - } - return (Name.Equals(other.Name) && Text.Equals(other.Text)); - } - return false; - } - } -} diff --git a/GreenshotPlugin/Core/LogHelper.cs b/GreenshotPlugin/Core/LogHelper.cs index bd2f3aee6..f82c287ad 100644 --- a/GreenshotPlugin/Core/LogHelper.cs +++ b/GreenshotPlugin/Core/LogHelper.cs @@ -35,13 +35,20 @@ namespace GreenshotPlugin.Core { /// public class LogHelper { private const string LOG4NET_FILE = "log4net.xml"; + private static bool isLog4NetConfigured = false; + + public static bool isInitialized { + get { + return isLog4NetConfigured; + } + } + // Initialize Log4J public static string InitializeLog4NET() { // Setup log4j, currently the file is called log4net.xml string pafLog4NetFilename = Path.Combine(Application.StartupPath, @"App\Greenshot\" + LOG4NET_FILE); string log4netFilename = Path.Combine(Application.StartupPath, LOG4NET_FILE); - bool isLog4NetConfigured = false; if (File.Exists(log4netFilename)) { try { XmlConfigurator.Configure(new FileInfo(log4netFilename)); @@ -51,19 +58,20 @@ namespace GreenshotPlugin.Core { try { XmlConfigurator.Configure(new FileInfo(pafLog4NetFilename)); isLog4NetConfigured = true; - } catch {} + } catch { } } + if (!isLog4NetConfigured) { try { - Assembly assem = typeof(LogHelper).Assembly; - using (Stream stream = assem.GetManifestResourceStream("GreenshotPlugin.log4net-embedded.xml")) { + Assembly assembly = typeof(LogHelper).Assembly; + using (Stream stream = assembly.GetManifestResourceStream("GreenshotPlugin.log4net-embedded.xml")) { XmlConfigurator.Configure(stream); isLog4NetConfigured = true; IniConfig.ForceIniInStartupPath(); } } catch {} } - + if (isLog4NetConfigured) { // Get the logfile name try { diff --git a/GreenshotPlugin/Core/NetworkHelper.cs b/GreenshotPlugin/Core/NetworkHelper.cs index 7e289c02e..24d08095f 100644 --- a/GreenshotPlugin/Core/NetworkHelper.cs +++ b/GreenshotPlugin/Core/NetworkHelper.cs @@ -42,7 +42,7 @@ namespace GreenshotPlugin.Core { /// string with the file content public static string DownloadFileAsString(Uri url, Encoding encoding) { try { - HttpWebRequest request = (HttpWebRequest)CreatedWebRequest(url); + HttpWebRequest request = (HttpWebRequest)CreateWebRequest(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (request.HaveResponse) { StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); @@ -63,7 +63,7 @@ namespace GreenshotPlugin.Core { public static Bitmap DownloadFavIcon(Uri baseUri) { Uri url = new Uri(baseUri, new Uri("favicon.ico")); try { - HttpWebRequest request = (HttpWebRequest)NetworkHelper.CreatedWebRequest(url); + HttpWebRequest request = (HttpWebRequest)NetworkHelper.CreateWebRequest(url); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); if (request.HaveResponse) { using (Image image = Image.FromStream(response.GetResponseStream())) { @@ -82,8 +82,8 @@ namespace GreenshotPlugin.Core { /// /// string with uri to connect to /// WebRequest - public static WebRequest CreatedWebRequest(string uri) { - return CreatedWebRequest(new Uri(uri)); + public static WebRequest CreateWebRequest(string uri) { + return CreateWebRequest(new Uri(uri)); } /// @@ -91,11 +91,11 @@ namespace GreenshotPlugin.Core { /// /// Uri with uri to connect to /// WebRequest - public static WebRequest CreatedWebRequest(Uri uri) { + public static WebRequest CreateWebRequest(Uri uri) { WebRequest webRequest = WebRequest.Create(uri); if (config.UseProxy) { - webRequest.Proxy = GreenshotPlugin.Core.NetworkHelper.CreateProxy(uri); - //webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; + webRequest.Proxy = GreenshotPlugin.Core.NetworkHelper.CreateProxy(uri); + //webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials; } return webRequest; } diff --git a/GreenshotPlugin/Core/SourceForgeHelper.cs b/GreenshotPlugin/Core/SourceForgeHelper.cs index c841a7545..8da0710b2 100644 --- a/GreenshotPlugin/Core/SourceForgeHelper.cs +++ b/GreenshotPlugin/Core/SourceForgeHelper.cs @@ -78,7 +78,7 @@ namespace GreenshotPlugin.Core { HttpWebRequest webRequest; XmlDocument rssDoc = new XmlDocument(); try { - webRequest = (HttpWebRequest)GreenshotPlugin.Core.NetworkHelper.CreatedWebRequest(RSSFEED); + webRequest = (HttpWebRequest)GreenshotPlugin.Core.NetworkHelper.CreateWebRequest(RSSFEED); XmlTextReader rssReader = new XmlTextReader(webRequest.GetResponse().GetResponseStream()); // Load the XML content into a XmlDocument diff --git a/GreenshotPlugin/GreenshotPlugin.csproj b/GreenshotPlugin/GreenshotPlugin.csproj index ae71e0ea6..c7f5a82bb 100644 --- a/GreenshotPlugin/GreenshotPlugin.csproj +++ b/GreenshotPlugin/GreenshotPlugin.csproj @@ -206,6 +206,7 @@ + @@ -220,7 +221,6 @@ - diff --git a/GreenshotPlugin/IniFile/IniConfig.cs b/GreenshotPlugin/IniFile/IniConfig.cs index f29c4e9f0..fc577af8a 100644 --- a/GreenshotPlugin/IniFile/IniConfig.cs +++ b/GreenshotPlugin/IniFile/IniConfig.cs @@ -170,7 +170,7 @@ namespace Greenshot.IniFile { try { applicationStartupPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location); } catch (Exception exception) { - LOG.WarnFormat("Problem retrieving the AssemblyLocation: {0}", exception.Message); + LOG.WarnFormat("Problem retrieving the AssemblyLocation: {0} (Designer mode?)", exception.Message); applicationStartupPath = @"."; } string pafPath = Path.Combine(applicationStartupPath, @"App\" + applicationName); diff --git a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs index 49af370b4..572f85381 100644 --- a/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs +++ b/GreenshotPlugin/Interfaces/Plugin/PluginInterfaces.cs @@ -153,14 +153,6 @@ namespace Greenshot.Plugin { /// Image to create capture for /// ICapture ICapture GetCapture(Image imageToCapture); - - /// - /// Get the core language object - /// - /// ILanguage for the Greenshot core - ILanguage CoreLanguage { - get; - } } public interface IGreenshotPlugin {