Fixed design-time displaying of the language mappings

git-svn-id: http://svn.code.sf.net/p/greenshot/code/trunk@1777 7dccd23d-a4a3-4e1f-8c07-b4c1b4018ab4
This commit is contained in:
RKrom 2012-04-17 12:52:46 +00:00
commit 27910e584a
10 changed files with 656 additions and 750 deletions

View file

@ -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<LanguageFile> {
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<string> languagePaths = new List<string>();
private static IDictionary<string, List<LanguageFile>> languageFiles = new Dictionary<string, List<LanguageFile>>();
private static IDictionary<string, HelpFile> helpFiles = new Dictionary<string, HelpFile>();
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<string> unsupportedLanguageGroups = new List<string>();
private static IDictionary<string, string> resources = new Dictionary<string, string>();
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<CoreConfiguration>();
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<LanguageFile> 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<LanguageFile> SupportedLanguages {
get {
IList<LanguageFile> languages = new List<LanguageFile>();
foreach (List<LanguageFile> 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;
}
}
/// <summary>
/// Load the resources from the language file
/// </summary>
/// <param name="languageFile">File to load from</param>
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);
}
}
/// <summary>
/// Load the language file information
/// </summary>
/// <param name="languageFilePath"></param>
/// <returns></returns>
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 <language> is missing");
}
} catch (Exception e) {
LOG.Error("Could not load language file " + languageFilePath, e);
}
return null;
}
/// <summary>
/// Scan the files in all directories
/// </summary>
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<LanguageFile> currentFiles = null;
if (languageFiles.ContainsKey(languageFile.Ietf)) {
currentFiles = languageFiles[languageFile.Ietf];
bool needToAdd = true;
List<LanguageFile> deleteList = new List<LanguageFile>();
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<LanguageFile>();
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); ;
}
}
}

View file

@ -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 <http://www.gnu.org/licenses/>.
*/
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<LanguageConfiguration> SupportedLanguages {
get;
}
String LanguageFilePattern {
get;
set;
}
LanguageConfiguration CurrentLanguageConfiguration {
get;
}
}
/// <summary>
/// Description of Language.
/// </summary>
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<string, string> strings = new Dictionary<string, string>();
private List<LanguageConfiguration> languages = new List<LanguageConfiguration>();
private string currentIETF = null;
private string languageFilePattern;
private static List<string> supportedLanguageGroups = new List<string>();
private static List<LanguageContainer> instances = new List<LanguageContainer>();
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<LanguageConfiguration> 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);
}
}
/// <summary>
/// Set language
/// </summary>
/// <param name="wantedIETF">wanted IETF</param>
/// <returns>Actuall IETF </returns>
public string SetInstanceLanguage(string wantedIETF) {
LOG.Debug("SetLanguage called for : " + wantedIETF);
Dictionary<string, LanguageConfiguration> identifiedLanguages = new Dictionary<string, LanguageConfiguration>();
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;
}
/// <summary>
/// Free all language resources which aren't needed
/// </summary>
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<LanguageConfiguration> LoadFiles(string languageFilePattern) {
List<LanguageConfiguration> loadedLanguages = new List<LanguageConfiguration>();
List<string> languageDirectories = new List<string>();
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<string, List<string>> keysPerLanguage = new Dictionary<string, List<string>>();
foreach(LanguageConfiguration languageToValidate in languages) {
List<string> keys = new List<string>();
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<string> fixedKeys = new List<string>();
foreach(Enum langKey in Enum.GetValues(languageKeys.GetType())) {
fixedKeys.Add(langKey.ToString());
}
foreach(string ietf in keysPerLanguage.Keys) {
List<string> 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<string> keys = new List<string>();
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<string> helpFiles = new List<string>();
// 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<Resource> Resources;
public LanguageConfiguration() {
Resources = new List<Resource>();
}
/// <summary>
/// loads a language configuration from a file path
/// </summary>
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;
}
/// <summary>
/// loads a language configuration from a stream
/// </summary>
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<Resource>(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 <language> 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;
}
}
}

View file

@ -35,13 +35,20 @@ namespace GreenshotPlugin.Core {
/// </summary>
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 {

View file

@ -42,7 +42,7 @@ namespace GreenshotPlugin.Core {
/// <returns>string with the file content</returns>
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 {
/// </summary>
/// <param name="uri">string with uri to connect to</param>
/// <returns>WebRequest</returns>
public static WebRequest CreatedWebRequest(string uri) {
return CreatedWebRequest(new Uri(uri));
public static WebRequest CreateWebRequest(string uri) {
return CreateWebRequest(new Uri(uri));
}
/// <summary>
@ -91,11 +91,11 @@ namespace GreenshotPlugin.Core {
/// </summary>
/// <param name="uri">Uri with uri to connect to</param>
/// <returns>WebRequest</returns>
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;
}

View file

@ -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